]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_dump.c
Ensure schema qualification in pg_restore DISABLE/ENABLE TRIGGER commands.
[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_d.h"
46 #include "catalog/pg_am_d.h"
47 #include "catalog/pg_attribute_d.h"
48 #include "catalog/pg_cast_d.h"
49 #include "catalog/pg_class_d.h"
50 #include "catalog/pg_default_acl_d.h"
51 #include "catalog/pg_largeobject_d.h"
52 #include "catalog/pg_largeobject_metadata_d.h"
53 #include "catalog/pg_proc_d.h"
54 #include "catalog/pg_trigger_d.h"
55 #include "catalog/pg_type_d.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/connect.h"
64 #include "fe_utils/string_utils.h"
65
66
67 typedef struct
68 {
69         const char *descr;                      /* comment for an object */
70         Oid                     classoid;               /* object class (catalog OID) */
71         Oid                     objoid;                 /* object OID */
72         int                     objsubid;               /* subobject (table column #) */
73 } CommentItem;
74
75 typedef struct
76 {
77         const char *provider;           /* label provider of this security label */
78         const char *label;                      /* security label for an object */
79         Oid                     classoid;               /* object class (catalog OID) */
80         Oid                     objoid;                 /* object OID */
81         int                     objsubid;               /* subobject (table column #) */
82 } SecLabelItem;
83
84 typedef enum OidOptions
85 {
86         zeroAsOpaque = 1,
87         zeroAsAny = 2,
88         zeroAsStar = 4,
89         zeroAsNone = 8
90 } OidOptions;
91
92 /* global decls */
93 bool            g_verbose;                      /* User wants verbose narration of our
94                                                                  * activities. */
95 static bool dosync = true;              /* Issue fsync() to make dump durable on disk. */
96
97 /* subquery used to convert user ID (eg, datdba) to user name */
98 static const char *username_subquery;
99
100 /*
101  * For 8.0 and earlier servers, pulled from pg_database, for 8.1+ we use
102  * FirstNormalObjectId - 1.
103  */
104 static Oid      g_last_builtin_oid; /* value of the last builtin oid */
105
106 /* The specified names/patterns should to match at least one entity */
107 static int      strict_names = 0;
108
109 /*
110  * Object inclusion/exclusion lists
111  *
112  * The string lists record the patterns given by command-line switches,
113  * which we then convert to lists of OIDs of matching objects.
114  */
115 static SimpleStringList schema_include_patterns = {NULL, NULL};
116 static SimpleOidList schema_include_oids = {NULL, NULL};
117 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
118 static SimpleOidList schema_exclude_oids = {NULL, NULL};
119
120 static SimpleStringList table_include_patterns = {NULL, NULL};
121 static SimpleOidList table_include_oids = {NULL, NULL};
122 static SimpleStringList table_exclude_patterns = {NULL, NULL};
123 static SimpleOidList table_exclude_oids = {NULL, NULL};
124 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
125 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
126
127
128 char            g_opaque_type[10];      /* name for the opaque type */
129
130 /* placeholders for the delimiters for comments */
131 char            g_comment_start[10];
132 char            g_comment_end[10];
133
134 static const CatalogId nilCatalogId = {0, 0};
135
136 /*
137  * Macro for producing quoted, schema-qualified name of a dumpable object.
138  */
139 #define fmtQualifiedDumpable(obj) \
140         fmtQualifiedId((obj)->dobj.namespace->dobj.name, \
141                                    (obj)->dobj.name)
142
143 static void help(const char *progname);
144 static void setup_connection(Archive *AH,
145                                  const char *dumpencoding, const char *dumpsnapshot,
146                                  char *use_role);
147 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
148 static void expand_schema_name_patterns(Archive *fout,
149                                                         SimpleStringList *patterns,
150                                                         SimpleOidList *oids,
151                                                         bool strict_names);
152 static void expand_table_name_patterns(Archive *fout,
153                                                    SimpleStringList *patterns,
154                                                    SimpleOidList *oids,
155                                                    bool strict_names);
156 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid);
157 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
158 static void refreshMatViewData(Archive *fout, TableDataInfo *tdinfo);
159 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
160 static void dumpComment(Archive *fout, const char *type, const char *name,
161                         const char *namespace, const char *owner,
162                         CatalogId catalogId, int subid, DumpId dumpId);
163 static int findComments(Archive *fout, Oid classoid, Oid objoid,
164                          CommentItem **items);
165 static int      collectComments(Archive *fout, CommentItem **items);
166 static void dumpSecLabel(Archive *fout, const char *type, const char *name,
167                          const char *namespace, const char *owner,
168                          CatalogId catalogId, int subid, DumpId dumpId);
169 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
170                           SecLabelItem **items);
171 static int      collectSecLabels(Archive *fout, SecLabelItem **items);
172 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
173 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
174 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
175 static void dumpType(Archive *fout, TypeInfo *tyinfo);
176 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
177 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
178 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
179 static void dumpUndefinedType(Archive *fout, TypeInfo *tyinfo);
180 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
181 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
182 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
183 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
184 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
185 static void dumpFunc(Archive *fout, FuncInfo *finfo);
186 static void dumpCast(Archive *fout, CastInfo *cast);
187 static void dumpTransform(Archive *fout, TransformInfo *transform);
188 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
189 static void dumpAccessMethod(Archive *fout, AccessMethodInfo *oprinfo);
190 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
191 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
192 static void dumpCollation(Archive *fout, CollInfo *collinfo);
193 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
194 static void dumpRule(Archive *fout, RuleInfo *rinfo);
195 static void dumpAgg(Archive *fout, AggInfo *agginfo);
196 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
197 static void dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo);
198 static void dumpTable(Archive *fout, TableInfo *tbinfo);
199 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
200 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
201 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
202 static void dumpSequenceData(Archive *fout, TableDataInfo *tdinfo);
203 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
204 static void dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo);
205 static void dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo);
206 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
207 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
208 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
209 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
210 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
211 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
212 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
213 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
214 static void dumpUserMappings(Archive *fout,
215                                  const char *servername, const char *namespace,
216                                  const char *owner, CatalogId catalogId, DumpId dumpId);
217 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
218
219 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
220                 const char *type, const char *name, const char *subname,
221                 const char *nspname, const char *owner,
222                 const char *acls, const char *racls,
223                 const char *initacls, const char *initracls);
224
225 static void getDependencies(Archive *fout);
226 static void BuildArchiveDependencies(Archive *fout);
227 static void findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
228                                                  DumpId **dependencies, int *nDeps, int *allocDeps);
229
230 static DumpableObject *createBoundaryObjects(void);
231 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
232                                                 DumpableObject *boundaryObjs);
233
234 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
235 static void getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, bool oids, char relkind);
236 static void makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo, bool oids);
237 static void buildMatViewRefreshDependencies(Archive *fout);
238 static void getTableDataFKConstraints(void);
239 static char *format_function_arguments(FuncInfo *finfo, char *funcargs,
240                                                   bool is_agg);
241 static char *format_function_arguments_old(Archive *fout,
242                                                           FuncInfo *finfo, int nallargs,
243                                                           char **allargtypes,
244                                                           char **argmodes,
245                                                           char **argnames);
246 static char *format_function_signature(Archive *fout,
247                                                   FuncInfo *finfo, bool honor_quotes);
248 static char *convertRegProcReference(Archive *fout,
249                                                 const char *proc);
250 static char *getFormattedOperatorName(Archive *fout, const char *oproid);
251 static char *convertTSFunction(Archive *fout, Oid funcOid);
252 static Oid      findLastBuiltinOid_V71(Archive *fout);
253 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
254 static void getBlobs(Archive *fout);
255 static void dumpBlob(Archive *fout, BlobInfo *binfo);
256 static int      dumpBlobs(Archive *fout, void *arg);
257 static void dumpPolicy(Archive *fout, PolicyInfo *polinfo);
258 static void dumpPublication(Archive *fout, PublicationInfo *pubinfo);
259 static void dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo);
260 static void dumpSubscription(Archive *fout, SubscriptionInfo *subinfo);
261 static void dumpDatabase(Archive *AH);
262 static void dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
263                                    const char *dbname, Oid dboid);
264 static void dumpEncoding(Archive *AH);
265 static void dumpStdStrings(Archive *AH);
266 static void dumpSearchPath(Archive *AH);
267 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
268                                                                                  PQExpBuffer upgrade_buffer,
269                                                                                  Oid pg_type_oid,
270                                                                                  bool force_array_type);
271 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
272                                                                                 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
273 static void binary_upgrade_set_pg_class_oids(Archive *fout,
274                                                                  PQExpBuffer upgrade_buffer,
275                                                                  Oid pg_class_oid, bool is_index);
276 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
277                                                                 DumpableObject *dobj,
278                                                                 const char *objtype,
279                                                                 const char *objname,
280                                                                 const char *objnamespace);
281 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
282 static const char *fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer);
283 static bool nonemptyReloptions(const char *reloptions);
284 static void appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
285                                                 const char *prefix, Archive *fout);
286 static char *get_synchronized_snapshot(Archive *fout);
287 static void setupDumpWorker(Archive *AHX);
288 static TableInfo *getRootTableInfo(TableInfo *tbinfo);
289
290
291 int
292 main(int argc, char **argv)
293 {
294         int                     c;
295         const char *filename = NULL;
296         const char *format = "p";
297         TableInfo  *tblinfo;
298         int                     numTables;
299         DumpableObject **dobjs;
300         int                     numObjs;
301         DumpableObject *boundaryObjs;
302         int                     i;
303         int                     optindex;
304         RestoreOptions *ropt;
305         Archive    *fout;                       /* the script file */
306         const char *dumpencoding = NULL;
307         const char *dumpsnapshot = NULL;
308         char       *use_role = NULL;
309         int                     numWorkers = 1;
310         trivalue        prompt_password = TRI_DEFAULT;
311         int                     compressLevel = -1;
312         int                     plainText = 0;
313         ArchiveFormat archiveFormat = archUnknown;
314         ArchiveMode archiveMode;
315
316         static DumpOptions dopt;
317
318         static struct option long_options[] = {
319                 {"data-only", no_argument, NULL, 'a'},
320                 {"blobs", no_argument, NULL, 'b'},
321                 {"no-blobs", no_argument, NULL, 'B'},
322                 {"clean", no_argument, NULL, 'c'},
323                 {"create", no_argument, NULL, 'C'},
324                 {"dbname", required_argument, NULL, 'd'},
325                 {"file", required_argument, NULL, 'f'},
326                 {"format", required_argument, NULL, 'F'},
327                 {"host", required_argument, NULL, 'h'},
328                 {"jobs", 1, NULL, 'j'},
329                 {"no-reconnect", no_argument, NULL, 'R'},
330                 {"oids", no_argument, NULL, 'o'},
331                 {"no-owner", no_argument, NULL, 'O'},
332                 {"port", required_argument, NULL, 'p'},
333                 {"schema", required_argument, NULL, 'n'},
334                 {"exclude-schema", required_argument, NULL, 'N'},
335                 {"schema-only", no_argument, NULL, 's'},
336                 {"superuser", required_argument, NULL, 'S'},
337                 {"table", required_argument, NULL, 't'},
338                 {"exclude-table", required_argument, NULL, 'T'},
339                 {"no-password", no_argument, NULL, 'w'},
340                 {"password", no_argument, NULL, 'W'},
341                 {"username", required_argument, NULL, 'U'},
342                 {"verbose", no_argument, NULL, 'v'},
343                 {"no-privileges", no_argument, NULL, 'x'},
344                 {"no-acl", no_argument, NULL, 'x'},
345                 {"compress", required_argument, NULL, 'Z'},
346                 {"encoding", required_argument, NULL, 'E'},
347                 {"help", no_argument, NULL, '?'},
348                 {"version", no_argument, NULL, 'V'},
349
350                 /*
351                  * the following options don't have an equivalent short option letter
352                  */
353                 {"attribute-inserts", no_argument, &dopt.column_inserts, 1},
354                 {"binary-upgrade", no_argument, &dopt.binary_upgrade, 1},
355                 {"column-inserts", no_argument, &dopt.column_inserts, 1},
356                 {"disable-dollar-quoting", no_argument, &dopt.disable_dollar_quoting, 1},
357                 {"disable-triggers", no_argument, &dopt.disable_triggers, 1},
358                 {"enable-row-security", no_argument, &dopt.enable_row_security, 1},
359                 {"exclude-table-data", required_argument, NULL, 4},
360                 {"if-exists", no_argument, &dopt.if_exists, 1},
361                 {"inserts", no_argument, &dopt.dump_inserts, 1},
362                 {"lock-wait-timeout", required_argument, NULL, 2},
363                 {"no-tablespaces", no_argument, &dopt.outputNoTablespaces, 1},
364                 {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
365                 {"load-via-partition-root", no_argument, &dopt.load_via_partition_root, 1},
366                 {"role", required_argument, NULL, 3},
367                 {"section", required_argument, NULL, 5},
368                 {"serializable-deferrable", no_argument, &dopt.serializable_deferrable, 1},
369                 {"snapshot", required_argument, NULL, 6},
370                 {"strict-names", no_argument, &strict_names, 1},
371                 {"use-set-session-authorization", no_argument, &dopt.use_setsessauth, 1},
372                 {"no-comments", no_argument, &dopt.no_comments, 1},
373                 {"no-publications", no_argument, &dopt.no_publications, 1},
374                 {"no-security-labels", no_argument, &dopt.no_security_labels, 1},
375                 {"no-synchronized-snapshots", no_argument, &dopt.no_synchronized_snapshots, 1},
376                 {"no-unlogged-table-data", no_argument, &dopt.no_unlogged_table_data, 1},
377                 {"no-subscriptions", no_argument, &dopt.no_subscriptions, 1},
378                 {"no-sync", no_argument, NULL, 7},
379                 {"on-conflict-do-nothing", no_argument, &dopt.do_nothing, 1},
380
381                 {NULL, 0, NULL, 0}
382         };
383
384         set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
385
386         /*
387          * Initialize what we need for parallel execution, especially for thread
388          * support on Windows.
389          */
390         init_parallel_dump_utils();
391
392         g_verbose = false;
393
394         strcpy(g_comment_start, "-- ");
395         g_comment_end[0] = '\0';
396         strcpy(g_opaque_type, "opaque");
397
398         progname = get_progname(argv[0]);
399
400         if (argc > 1)
401         {
402                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
403                 {
404                         help(progname);
405                         exit_nicely(0);
406                 }
407                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
408                 {
409                         puts("pg_dump (PostgreSQL) " PG_VERSION);
410                         exit_nicely(0);
411                 }
412         }
413
414         InitDumpOptions(&dopt);
415
416         while ((c = getopt_long(argc, argv, "abBcCd:E:f:F:h:j:n:N:oOp:RsS:t:T:U:vwWxZ:",
417                                                         long_options, &optindex)) != -1)
418         {
419                 switch (c)
420                 {
421                         case 'a':                       /* Dump data only */
422                                 dopt.dataOnly = true;
423                                 break;
424
425                         case 'b':                       /* Dump blobs */
426                                 dopt.outputBlobs = true;
427                                 break;
428
429                         case 'B':                       /* Don't dump blobs */
430                                 dopt.dontOutputBlobs = true;
431                                 break;
432
433                         case 'c':                       /* clean (i.e., drop) schema prior to create */
434                                 dopt.outputClean = 1;
435                                 break;
436
437                         case 'C':                       /* Create DB */
438                                 dopt.outputCreateDB = 1;
439                                 break;
440
441                         case 'd':                       /* database name */
442                                 dopt.dbname = pg_strdup(optarg);
443                                 break;
444
445                         case 'E':                       /* Dump encoding */
446                                 dumpencoding = pg_strdup(optarg);
447                                 break;
448
449                         case 'f':
450                                 filename = pg_strdup(optarg);
451                                 break;
452
453                         case 'F':
454                                 format = pg_strdup(optarg);
455                                 break;
456
457                         case 'h':                       /* server host */
458                                 dopt.pghost = pg_strdup(optarg);
459                                 break;
460
461                         case 'j':                       /* number of dump jobs */
462                                 numWorkers = atoi(optarg);
463                                 break;
464
465                         case 'n':                       /* include schema(s) */
466                                 simple_string_list_append(&schema_include_patterns, optarg);
467                                 dopt.include_everything = false;
468                                 break;
469
470                         case 'N':                       /* exclude schema(s) */
471                                 simple_string_list_append(&schema_exclude_patterns, optarg);
472                                 break;
473
474                         case 'o':                       /* Dump oids */
475                                 dopt.oids = true;
476                                 break;
477
478                         case 'O':                       /* Don't reconnect to match owner */
479                                 dopt.outputNoOwner = 1;
480                                 break;
481
482                         case 'p':                       /* server port */
483                                 dopt.pgport = pg_strdup(optarg);
484                                 break;
485
486                         case 'R':
487                                 /* no-op, still accepted for backwards compatibility */
488                                 break;
489
490                         case 's':                       /* dump schema only */
491                                 dopt.schemaOnly = true;
492                                 break;
493
494                         case 'S':                       /* Username for superuser in plain text output */
495                                 dopt.outputSuperuser = pg_strdup(optarg);
496                                 break;
497
498                         case 't':                       /* include table(s) */
499                                 simple_string_list_append(&table_include_patterns, optarg);
500                                 dopt.include_everything = false;
501                                 break;
502
503                         case 'T':                       /* exclude table(s) */
504                                 simple_string_list_append(&table_exclude_patterns, optarg);
505                                 break;
506
507                         case 'U':
508                                 dopt.username = pg_strdup(optarg);
509                                 break;
510
511                         case 'v':                       /* verbose */
512                                 g_verbose = true;
513                                 break;
514
515                         case 'w':
516                                 prompt_password = TRI_NO;
517                                 break;
518
519                         case 'W':
520                                 prompt_password = TRI_YES;
521                                 break;
522
523                         case 'x':                       /* skip ACL dump */
524                                 dopt.aclsSkip = true;
525                                 break;
526
527                         case 'Z':                       /* Compression Level */
528                                 compressLevel = atoi(optarg);
529                                 if (compressLevel < 0 || compressLevel > 9)
530                                 {
531                                         write_msg(NULL, "compression level must be in range 0..9\n");
532                                         exit_nicely(1);
533                                 }
534                                 break;
535
536                         case 0:
537                                 /* This covers the long options. */
538                                 break;
539
540                         case 2:                         /* lock-wait-timeout */
541                                 dopt.lockWaitTimeout = pg_strdup(optarg);
542                                 break;
543
544                         case 3:                         /* SET ROLE */
545                                 use_role = pg_strdup(optarg);
546                                 break;
547
548                         case 4:                         /* exclude table(s) data */
549                                 simple_string_list_append(&tabledata_exclude_patterns, optarg);
550                                 break;
551
552                         case 5:                         /* section */
553                                 set_dump_section(optarg, &dopt.dumpSections);
554                                 break;
555
556                         case 6:                         /* snapshot */
557                                 dumpsnapshot = pg_strdup(optarg);
558                                 break;
559
560                         case 7:                         /* no-sync */
561                                 dosync = false;
562                                 break;
563
564                         default:
565                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
566                                 exit_nicely(1);
567                 }
568         }
569
570         /*
571          * Non-option argument specifies database name as long as it wasn't
572          * already specified with -d / --dbname
573          */
574         if (optind < argc && dopt.dbname == NULL)
575                 dopt.dbname = argv[optind++];
576
577         /* Complain if any arguments remain */
578         if (optind < argc)
579         {
580                 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
581                                 progname, argv[optind]);
582                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
583                                 progname);
584                 exit_nicely(1);
585         }
586
587         /* --column-inserts implies --inserts */
588         if (dopt.column_inserts)
589                 dopt.dump_inserts = 1;
590
591         /*
592          * Binary upgrade mode implies dumping sequence data even in schema-only
593          * mode.  This is not exposed as a separate option, but kept separate
594          * internally for clarity.
595          */
596         if (dopt.binary_upgrade)
597                 dopt.sequence_data = 1;
598
599         if (dopt.dataOnly && dopt.schemaOnly)
600         {
601                 write_msg(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
602                 exit_nicely(1);
603         }
604
605         if (dopt.dataOnly && dopt.outputClean)
606         {
607                 write_msg(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
608                 exit_nicely(1);
609         }
610
611         if (dopt.dump_inserts && dopt.oids)
612         {
613                 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
614                 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
615                 exit_nicely(1);
616         }
617
618         if (dopt.if_exists && !dopt.outputClean)
619                 exit_horribly(NULL, "option --if-exists requires option -c/--clean\n");
620
621         if (dopt.do_nothing && !(dopt.dump_inserts || dopt.column_inserts))
622                 exit_horribly(NULL, "option --on-conflict-do-nothing requires option --inserts or --column-inserts\n");
623
624         /* Identify archive format to emit */
625         archiveFormat = parseArchiveFormat(format, &archiveMode);
626
627         /* archiveFormat specific setup */
628         if (archiveFormat == archNull)
629                 plainText = 1;
630
631         /* Custom and directory formats are compressed by default, others not */
632         if (compressLevel == -1)
633         {
634 #ifdef HAVE_LIBZ
635                 if (archiveFormat == archCustom || archiveFormat == archDirectory)
636                         compressLevel = Z_DEFAULT_COMPRESSION;
637                 else
638 #endif
639                         compressLevel = 0;
640         }
641
642 #ifndef HAVE_LIBZ
643         if (compressLevel != 0)
644                 write_msg(NULL, "WARNING: requested compression not available in this "
645                                   "installation -- archive will be uncompressed\n");
646         compressLevel = 0;
647 #endif
648
649         /*
650          * If emitting an archive format, we always want to emit a DATABASE item,
651          * in case --create is specified at pg_restore time.
652          */
653         if (!plainText)
654                 dopt.outputCreateDB = 1;
655
656         /*
657          * On Windows we can only have at most MAXIMUM_WAIT_OBJECTS (= 64 usually)
658          * parallel jobs because that's the maximum limit for the
659          * WaitForMultipleObjects() call.
660          */
661         if (numWorkers <= 0
662 #ifdef WIN32
663                 || numWorkers > MAXIMUM_WAIT_OBJECTS
664 #endif
665                 )
666                 exit_horribly(NULL, "invalid number of parallel jobs\n");
667
668         /* Parallel backup only in the directory archive format so far */
669         if (archiveFormat != archDirectory && numWorkers > 1)
670                 exit_horribly(NULL, "parallel backup only supported by the directory format\n");
671
672         /* Open the output file */
673         fout = CreateArchive(filename, archiveFormat, compressLevel, dosync,
674                                                  archiveMode, setupDumpWorker);
675
676         /* Make dump options accessible right away */
677         SetArchiveOptions(fout, &dopt, NULL);
678
679         /* Register the cleanup hook */
680         on_exit_close_archive(fout);
681
682         /* Let the archiver know how noisy to be */
683         fout->verbose = g_verbose;
684
685         /*
686          * We allow the server to be back to 8.0, and up to any minor release of
687          * our own major version.  (See also version check in pg_dumpall.c.)
688          */
689         fout->minRemoteVersion = 80000;
690         fout->maxRemoteVersion = (PG_VERSION_NUM / 100) * 100 + 99;
691
692         fout->numWorkers = numWorkers;
693
694         /*
695          * Open the database using the Archiver, so it knows about it. Errors mean
696          * death.
697          */
698         ConnectDatabase(fout, dopt.dbname, dopt.pghost, dopt.pgport, dopt.username, prompt_password);
699         setup_connection(fout, dumpencoding, dumpsnapshot, use_role);
700
701         /*
702          * Disable security label support if server version < v9.1.x (prevents
703          * access to nonexistent pg_seclabel catalog)
704          */
705         if (fout->remoteVersion < 90100)
706                 dopt.no_security_labels = 1;
707
708         /*
709          * On hot standbys, never try to dump unlogged table data, since it will
710          * just throw an error.
711          */
712         if (fout->isStandby)
713                 dopt.no_unlogged_table_data = true;
714
715         /* Select the appropriate subquery to convert user IDs to names */
716         if (fout->remoteVersion >= 80100)
717                 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
718         else
719                 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
720
721         /* check the version for the synchronized snapshots feature */
722         if (numWorkers > 1 && fout->remoteVersion < 90200
723                 && !dopt.no_synchronized_snapshots)
724                 exit_horribly(NULL,
725                                           "Synchronized snapshots are not supported by this server version.\n"
726                                           "Run with --no-synchronized-snapshots instead if you do not need\n"
727                                           "synchronized snapshots.\n");
728
729         /* check the version when a snapshot is explicitly specified by user */
730         if (dumpsnapshot && fout->remoteVersion < 90200)
731                 exit_horribly(NULL,
732                                           "Exported snapshots are not supported by this server version.\n");
733
734         /*
735          * Find the last built-in OID, if needed (prior to 8.1)
736          *
737          * With 8.1 and above, we can just use FirstNormalObjectId - 1.
738          */
739         if (fout->remoteVersion < 80100)
740                 g_last_builtin_oid = findLastBuiltinOid_V71(fout);
741         else
742                 g_last_builtin_oid = FirstNormalObjectId - 1;
743
744         if (g_verbose)
745                 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
746
747         /* Expand schema selection patterns into OID lists */
748         if (schema_include_patterns.head != NULL)
749         {
750                 expand_schema_name_patterns(fout, &schema_include_patterns,
751                                                                         &schema_include_oids,
752                                                                         strict_names);
753                 if (schema_include_oids.head == NULL)
754                         exit_horribly(NULL, "no matching schemas were found\n");
755         }
756         expand_schema_name_patterns(fout, &schema_exclude_patterns,
757                                                                 &schema_exclude_oids,
758                                                                 false);
759         /* non-matching exclusion patterns aren't an error */
760
761         /* Expand table selection patterns into OID lists */
762         if (table_include_patterns.head != NULL)
763         {
764                 expand_table_name_patterns(fout, &table_include_patterns,
765                                                                    &table_include_oids,
766                                                                    strict_names);
767                 if (table_include_oids.head == NULL)
768                         exit_horribly(NULL, "no matching tables were found\n");
769         }
770         expand_table_name_patterns(fout, &table_exclude_patterns,
771                                                            &table_exclude_oids,
772                                                            false);
773
774         expand_table_name_patterns(fout, &tabledata_exclude_patterns,
775                                                            &tabledata_exclude_oids,
776                                                            false);
777
778         /* non-matching exclusion patterns aren't an error */
779
780         /*
781          * Dumping blobs is the default for dumps where an inclusion switch is not
782          * used (an "include everything" dump).  -B can be used to exclude blobs
783          * from those dumps.  -b can be used to include blobs even when an
784          * inclusion switch is used.
785          *
786          * -s means "schema only" and blobs are data, not schema, so we never
787          * include blobs when -s is used.
788          */
789         if (dopt.include_everything && !dopt.schemaOnly && !dopt.dontOutputBlobs)
790                 dopt.outputBlobs = true;
791
792         /*
793          * Now scan the database and create DumpableObject structs for all the
794          * objects we intend to dump.
795          */
796         tblinfo = getSchemaData(fout, &numTables);
797
798         if (fout->remoteVersion < 80400)
799                 guessConstraintInheritance(tblinfo, numTables);
800
801         if (!dopt.schemaOnly)
802         {
803                 getTableData(&dopt, tblinfo, numTables, dopt.oids, 0);
804                 buildMatViewRefreshDependencies(fout);
805                 if (dopt.dataOnly)
806                         getTableDataFKConstraints();
807         }
808
809         if (dopt.schemaOnly && dopt.sequence_data)
810                 getTableData(&dopt, tblinfo, numTables, dopt.oids, RELKIND_SEQUENCE);
811
812         /*
813          * In binary-upgrade mode, we do not have to worry about the actual blob
814          * data or the associated metadata that resides in the pg_largeobject and
815          * pg_largeobject_metadata tables, respectively.
816          *
817          * However, we do need to collect blob information as there may be
818          * comments or other information on blobs that we do need to dump out.
819          */
820         if (dopt.outputBlobs || dopt.binary_upgrade)
821                 getBlobs(fout);
822
823         /*
824          * Collect dependency data to assist in ordering the objects.
825          */
826         getDependencies(fout);
827
828         /* Lastly, create dummy objects to represent the section boundaries */
829         boundaryObjs = createBoundaryObjects();
830
831         /* Get pointers to all the known DumpableObjects */
832         getDumpableObjects(&dobjs, &numObjs);
833
834         /*
835          * Add dummy dependencies to enforce the dump section ordering.
836          */
837         addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
838
839         /*
840          * Sort the objects into a safe dump order (no forward references).
841          *
842          * We rely on dependency information to help us determine a safe order, so
843          * the initial sort is mostly for cosmetic purposes: we sort by name to
844          * ensure that logically identical schemas will dump identically.
845          */
846         sortDumpableObjectsByTypeName(dobjs, numObjs);
847
848         /* If we do a parallel dump, we want the largest tables to go first */
849         if (archiveFormat == archDirectory && numWorkers > 1)
850                 sortDataAndIndexObjectsBySize(dobjs, numObjs);
851
852         sortDumpableObjects(dobjs, numObjs,
853                                                 boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
854
855         /*
856          * Create archive TOC entries for all the objects to be dumped, in a safe
857          * order.
858          */
859
860         /* First the special ENCODING, STDSTRINGS, and SEARCHPATH entries. */
861         dumpEncoding(fout);
862         dumpStdStrings(fout);
863         dumpSearchPath(fout);
864
865         /* The database items are always next, unless we don't want them at all */
866         if (dopt.outputCreateDB)
867                 dumpDatabase(fout);
868
869         /* Now the rearrangeable objects. */
870         for (i = 0; i < numObjs; i++)
871                 dumpDumpableObject(fout, dobjs[i]);
872
873         /*
874          * Set up options info to ensure we dump what we want.
875          */
876         ropt = NewRestoreOptions();
877         ropt->filename = filename;
878
879         /* if you change this list, see dumpOptionsFromRestoreOptions */
880         ropt->dropSchema = dopt.outputClean;
881         ropt->dataOnly = dopt.dataOnly;
882         ropt->schemaOnly = dopt.schemaOnly;
883         ropt->if_exists = dopt.if_exists;
884         ropt->column_inserts = dopt.column_inserts;
885         ropt->dumpSections = dopt.dumpSections;
886         ropt->aclsSkip = dopt.aclsSkip;
887         ropt->superuser = dopt.outputSuperuser;
888         ropt->createDB = dopt.outputCreateDB;
889         ropt->noOwner = dopt.outputNoOwner;
890         ropt->noTablespace = dopt.outputNoTablespaces;
891         ropt->disable_triggers = dopt.disable_triggers;
892         ropt->use_setsessauth = dopt.use_setsessauth;
893         ropt->disable_dollar_quoting = dopt.disable_dollar_quoting;
894         ropt->dump_inserts = dopt.dump_inserts;
895         ropt->no_comments = dopt.no_comments;
896         ropt->no_publications = dopt.no_publications;
897         ropt->no_security_labels = dopt.no_security_labels;
898         ropt->no_subscriptions = dopt.no_subscriptions;
899         ropt->lockWaitTimeout = dopt.lockWaitTimeout;
900         ropt->include_everything = dopt.include_everything;
901         ropt->enable_row_security = dopt.enable_row_security;
902         ropt->sequence_data = dopt.sequence_data;
903         ropt->binary_upgrade = dopt.binary_upgrade;
904
905         if (compressLevel == -1)
906                 ropt->compression = 0;
907         else
908                 ropt->compression = compressLevel;
909
910         ropt->suppressDumpWarnings = true;      /* We've already shown them */
911
912         SetArchiveOptions(fout, &dopt, ropt);
913
914         /* Mark which entries should be output */
915         ProcessArchiveRestoreOptions(fout);
916
917         /*
918          * The archive's TOC entries are now marked as to which ones will actually
919          * be output, so we can set up their dependency lists properly. This isn't
920          * necessary for plain-text output, though.
921          */
922         if (!plainText)
923                 BuildArchiveDependencies(fout);
924
925         /*
926          * And finally we can do the actual output.
927          *
928          * Note: for non-plain-text output formats, the output file is written
929          * inside CloseArchive().  This is, um, bizarre; but not worth changing
930          * right now.
931          */
932         if (plainText)
933                 RestoreArchive(fout);
934
935         CloseArchive(fout);
936
937         exit_nicely(0);
938 }
939
940
941 static void
942 help(const char *progname)
943 {
944         printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
945         printf(_("Usage:\n"));
946         printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
947
948         printf(_("\nGeneral options:\n"));
949         printf(_("  -f, --file=FILENAME          output file or directory name\n"));
950         printf(_("  -F, --format=c|d|t|p         output file format (custom, directory, tar,\n"
951                          "                               plain text (default))\n"));
952         printf(_("  -j, --jobs=NUM               use this many parallel jobs to dump\n"));
953         printf(_("  -v, --verbose                verbose mode\n"));
954         printf(_("  -V, --version                output version information, then exit\n"));
955         printf(_("  -Z, --compress=0-9           compression level for compressed formats\n"));
956         printf(_("  --lock-wait-timeout=TIMEOUT  fail after waiting TIMEOUT for a table lock\n"));
957         printf(_("  --no-sync                    do not wait for changes to be written safely to disk\n"));
958         printf(_("  -?, --help                   show this help, then exit\n"));
959
960         printf(_("\nOptions controlling the output content:\n"));
961         printf(_("  -a, --data-only              dump only the data, not the schema\n"));
962         printf(_("  -b, --blobs                  include large objects in dump\n"));
963         printf(_("  -B, --no-blobs               exclude large objects in dump\n"));
964         printf(_("  -c, --clean                  clean (drop) database objects before recreating\n"));
965         printf(_("  -C, --create                 include commands to create database in dump\n"));
966         printf(_("  -E, --encoding=ENCODING      dump the data in encoding ENCODING\n"));
967         printf(_("  -n, --schema=SCHEMA          dump the named schema(s) only\n"));
968         printf(_("  -N, --exclude-schema=SCHEMA  do NOT dump the named schema(s)\n"));
969         printf(_("  -o, --oids                   include OIDs in dump\n"));
970         printf(_("  -O, --no-owner               skip restoration of object ownership in\n"
971                          "                               plain-text format\n"));
972         printf(_("  -s, --schema-only            dump only the schema, no data\n"));
973         printf(_("  -S, --superuser=NAME         superuser user name to use in plain-text format\n"));
974         printf(_("  -t, --table=TABLE            dump the named table(s) only\n"));
975         printf(_("  -T, --exclude-table=TABLE    do NOT dump the named table(s)\n"));
976         printf(_("  -x, --no-privileges          do not dump privileges (grant/revoke)\n"));
977         printf(_("  --binary-upgrade             for use by upgrade utilities only\n"));
978         printf(_("  --column-inserts             dump data as INSERT commands with column names\n"));
979         printf(_("  --disable-dollar-quoting     disable dollar quoting, use SQL standard quoting\n"));
980         printf(_("  --disable-triggers           disable triggers during data-only restore\n"));
981         printf(_("  --enable-row-security        enable row security (dump only content user has\n"
982                          "                               access to)\n"));
983         printf(_("  --exclude-table-data=TABLE   do NOT dump data for the named table(s)\n"));
984         printf(_("  --if-exists                  use IF EXISTS when dropping objects\n"));
985         printf(_("  --inserts                    dump data as INSERT commands, rather than COPY\n"));
986         printf(_("  --load-via-partition-root    load partitions via the root table\n"));
987         printf(_("  --no-comments                do not dump comments\n"));
988         printf(_("  --no-publications            do not dump publications\n"));
989         printf(_("  --no-security-labels         do not dump security label assignments\n"));
990         printf(_("  --no-subscriptions           do not dump subscriptions\n"));
991         printf(_("  --no-synchronized-snapshots  do not use synchronized snapshots in parallel jobs\n"));
992         printf(_("  --no-tablespaces             do not dump tablespace assignments\n"));
993         printf(_("  --no-unlogged-table-data     do not dump unlogged table data\n"));
994         printf(_("  --on-conflict-do-nothing     add ON CONFLICT DO NOTHING to INSERT commands\n"));
995         printf(_("  --quote-all-identifiers      quote all identifiers, even if not key words\n"));
996         printf(_("  --section=SECTION            dump named section (pre-data, data, or post-data)\n"));
997         printf(_("  --serializable-deferrable    wait until the dump can run without anomalies\n"));
998         printf(_("  --snapshot=SNAPSHOT          use given snapshot for the dump\n"));
999         printf(_("  --strict-names               require table and/or schema include patterns to\n"
1000                          "                               match at least one entity each\n"));
1001         printf(_("  --use-set-session-authorization\n"
1002                          "                               use SET SESSION AUTHORIZATION commands instead of\n"
1003                          "                               ALTER OWNER commands to set ownership\n"));
1004
1005         printf(_("\nConnection options:\n"));
1006         printf(_("  -d, --dbname=DBNAME      database to dump\n"));
1007         printf(_("  -h, --host=HOSTNAME      database server host or socket directory\n"));
1008         printf(_("  -p, --port=PORT          database server port number\n"));
1009         printf(_("  -U, --username=NAME      connect as specified database user\n"));
1010         printf(_("  -w, --no-password        never prompt for password\n"));
1011         printf(_("  -W, --password           force password prompt (should happen automatically)\n"));
1012         printf(_("  --role=ROLENAME          do SET ROLE before dump\n"));
1013
1014         printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
1015                          "variable value is used.\n\n"));
1016         printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
1017 }
1018
1019 static void
1020 setup_connection(Archive *AH, const char *dumpencoding,
1021                                  const char *dumpsnapshot, char *use_role)
1022 {
1023         DumpOptions *dopt = AH->dopt;
1024         PGconn     *conn = GetConnection(AH);
1025         const char *std_strings;
1026
1027         PQclear(ExecuteSqlQueryForSingleRow(AH, ALWAYS_SECURE_SEARCH_PATH_SQL));
1028
1029         /*
1030          * Set the client encoding if requested.
1031          */
1032         if (dumpencoding)
1033         {
1034                 if (PQsetClientEncoding(conn, dumpencoding) < 0)
1035                         exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
1036                                                   dumpencoding);
1037         }
1038
1039         /*
1040          * Get the active encoding and the standard_conforming_strings setting, so
1041          * we know how to escape strings.
1042          */
1043         AH->encoding = PQclientEncoding(conn);
1044
1045         std_strings = PQparameterStatus(conn, "standard_conforming_strings");
1046         AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
1047
1048         /*
1049          * Set the role if requested.  In a parallel dump worker, we'll be passed
1050          * use_role == NULL, but AH->use_role is already set (if user specified it
1051          * originally) and we should use that.
1052          */
1053         if (!use_role && AH->use_role)
1054                 use_role = AH->use_role;
1055
1056         /* Set the role if requested */
1057         if (use_role && AH->remoteVersion >= 80100)
1058         {
1059                 PQExpBuffer query = createPQExpBuffer();
1060
1061                 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
1062                 ExecuteSqlStatement(AH, query->data);
1063                 destroyPQExpBuffer(query);
1064
1065                 /* save it for possible later use by parallel workers */
1066                 if (!AH->use_role)
1067                         AH->use_role = pg_strdup(use_role);
1068         }
1069
1070         /* Set the datestyle to ISO to ensure the dump's portability */
1071         ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
1072
1073         /* Likewise, avoid using sql_standard intervalstyle */
1074         if (AH->remoteVersion >= 80400)
1075                 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
1076
1077         /*
1078          * Set extra_float_digits so that we can dump float data exactly (given
1079          * correctly implemented float I/O code, anyway)
1080          */
1081         if (AH->remoteVersion >= 90000)
1082                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
1083         else
1084                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
1085
1086         /*
1087          * If synchronized scanning is supported, disable it, to prevent
1088          * unpredictable changes in row ordering across a dump and reload.
1089          */
1090         if (AH->remoteVersion >= 80300)
1091                 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
1092
1093         /*
1094          * Disable timeouts if supported.
1095          */
1096         ExecuteSqlStatement(AH, "SET statement_timeout = 0");
1097         if (AH->remoteVersion >= 90300)
1098                 ExecuteSqlStatement(AH, "SET lock_timeout = 0");
1099         if (AH->remoteVersion >= 90600)
1100                 ExecuteSqlStatement(AH, "SET idle_in_transaction_session_timeout = 0");
1101
1102         /*
1103          * Quote all identifiers, if requested.
1104          */
1105         if (quote_all_identifiers && AH->remoteVersion >= 90100)
1106                 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
1107
1108         /*
1109          * Adjust row-security mode, if supported.
1110          */
1111         if (AH->remoteVersion >= 90500)
1112         {
1113                 if (dopt->enable_row_security)
1114                         ExecuteSqlStatement(AH, "SET row_security = on");
1115                 else
1116                         ExecuteSqlStatement(AH, "SET row_security = off");
1117         }
1118
1119         /*
1120          * Start transaction-snapshot mode transaction to dump consistent data.
1121          */
1122         ExecuteSqlStatement(AH, "BEGIN");
1123         if (AH->remoteVersion >= 90100)
1124         {
1125                 /*
1126                  * To support the combination of serializable_deferrable with the jobs
1127                  * option we use REPEATABLE READ for the worker connections that are
1128                  * passed a snapshot.  As long as the snapshot is acquired in a
1129                  * SERIALIZABLE, READ ONLY, DEFERRABLE transaction, its use within a
1130                  * REPEATABLE READ transaction provides the appropriate integrity
1131                  * guarantees.  This is a kluge, but safe for back-patching.
1132                  */
1133                 if (dopt->serializable_deferrable && AH->sync_snapshot_id == NULL)
1134                         ExecuteSqlStatement(AH,
1135                                                                 "SET TRANSACTION ISOLATION LEVEL "
1136                                                                 "SERIALIZABLE, READ ONLY, DEFERRABLE");
1137                 else
1138                         ExecuteSqlStatement(AH,
1139                                                                 "SET TRANSACTION ISOLATION LEVEL "
1140                                                                 "REPEATABLE READ, READ ONLY");
1141         }
1142         else
1143         {
1144                 ExecuteSqlStatement(AH,
1145                                                         "SET TRANSACTION ISOLATION LEVEL "
1146                                                         "SERIALIZABLE, READ ONLY");
1147         }
1148
1149         /*
1150          * If user specified a snapshot to use, select that.  In a parallel dump
1151          * worker, we'll be passed dumpsnapshot == NULL, but AH->sync_snapshot_id
1152          * is already set (if the server can handle it) and we should use that.
1153          */
1154         if (dumpsnapshot)
1155                 AH->sync_snapshot_id = pg_strdup(dumpsnapshot);
1156
1157         if (AH->sync_snapshot_id)
1158         {
1159                 PQExpBuffer query = createPQExpBuffer();
1160
1161                 appendPQExpBuffer(query, "SET TRANSACTION SNAPSHOT ");
1162                 appendStringLiteralConn(query, AH->sync_snapshot_id, conn);
1163                 ExecuteSqlStatement(AH, query->data);
1164                 destroyPQExpBuffer(query);
1165         }
1166         else if (AH->numWorkers > 1 &&
1167                          AH->remoteVersion >= 90200 &&
1168                          !dopt->no_synchronized_snapshots)
1169         {
1170                 if (AH->isStandby && AH->remoteVersion < 100000)
1171                         exit_horribly(NULL,
1172                                                   "Synchronized snapshots on standby servers are not supported by this server version.\n"
1173                                                   "Run with --no-synchronized-snapshots instead if you do not need\n"
1174                                                   "synchronized snapshots.\n");
1175
1176
1177                 AH->sync_snapshot_id = get_synchronized_snapshot(AH);
1178         }
1179 }
1180
1181 /* Set up connection for a parallel worker process */
1182 static void
1183 setupDumpWorker(Archive *AH)
1184 {
1185         /*
1186          * We want to re-select all the same values the master connection is
1187          * using.  We'll have inherited directly-usable values in
1188          * AH->sync_snapshot_id and AH->use_role, but we need to translate the
1189          * inherited encoding value back to a string to pass to setup_connection.
1190          */
1191         setup_connection(AH,
1192                                          pg_encoding_to_char(AH->encoding),
1193                                          NULL,
1194                                          NULL);
1195 }
1196
1197 static char *
1198 get_synchronized_snapshot(Archive *fout)
1199 {
1200         char       *query = "SELECT pg_catalog.pg_export_snapshot()";
1201         char       *result;
1202         PGresult   *res;
1203
1204         res = ExecuteSqlQueryForSingleRow(fout, query);
1205         result = pg_strdup(PQgetvalue(res, 0, 0));
1206         PQclear(res);
1207
1208         return result;
1209 }
1210
1211 static ArchiveFormat
1212 parseArchiveFormat(const char *format, ArchiveMode *mode)
1213 {
1214         ArchiveFormat archiveFormat;
1215
1216         *mode = archModeWrite;
1217
1218         if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
1219         {
1220                 /* This is used by pg_dumpall, and is not documented */
1221                 archiveFormat = archNull;
1222                 *mode = archModeAppend;
1223         }
1224         else if (pg_strcasecmp(format, "c") == 0)
1225                 archiveFormat = archCustom;
1226         else if (pg_strcasecmp(format, "custom") == 0)
1227                 archiveFormat = archCustom;
1228         else if (pg_strcasecmp(format, "d") == 0)
1229                 archiveFormat = archDirectory;
1230         else if (pg_strcasecmp(format, "directory") == 0)
1231                 archiveFormat = archDirectory;
1232         else if (pg_strcasecmp(format, "p") == 0)
1233                 archiveFormat = archNull;
1234         else if (pg_strcasecmp(format, "plain") == 0)
1235                 archiveFormat = archNull;
1236         else if (pg_strcasecmp(format, "t") == 0)
1237                 archiveFormat = archTar;
1238         else if (pg_strcasecmp(format, "tar") == 0)
1239                 archiveFormat = archTar;
1240         else
1241                 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
1242         return archiveFormat;
1243 }
1244
1245 /*
1246  * Find the OIDs of all schemas matching the given list of patterns,
1247  * and append them to the given OID list.
1248  */
1249 static void
1250 expand_schema_name_patterns(Archive *fout,
1251                                                         SimpleStringList *patterns,
1252                                                         SimpleOidList *oids,
1253                                                         bool strict_names)
1254 {
1255         PQExpBuffer query;
1256         PGresult   *res;
1257         SimpleStringListCell *cell;
1258         int                     i;
1259
1260         if (patterns->head == NULL)
1261                 return;                                 /* nothing to do */
1262
1263         query = createPQExpBuffer();
1264
1265         /*
1266          * The loop below runs multiple SELECTs might sometimes result in
1267          * duplicate entries in the OID list, but we don't care.
1268          */
1269
1270         for (cell = patterns->head; cell; cell = cell->next)
1271         {
1272                 appendPQExpBuffer(query,
1273                                                   "SELECT oid FROM pg_catalog.pg_namespace n\n");
1274                 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1275                                                           false, NULL, "n.nspname", NULL, NULL);
1276
1277                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1278                 if (strict_names && PQntuples(res) == 0)
1279                         exit_horribly(NULL, "no matching schemas were found for pattern \"%s\"\n", cell->val);
1280
1281                 for (i = 0; i < PQntuples(res); i++)
1282                 {
1283                         simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1284                 }
1285
1286                 PQclear(res);
1287                 resetPQExpBuffer(query);
1288         }
1289
1290         destroyPQExpBuffer(query);
1291 }
1292
1293 /*
1294  * Find the OIDs of all tables matching the given list of patterns,
1295  * and append them to the given OID list.
1296  */
1297 static void
1298 expand_table_name_patterns(Archive *fout,
1299                                                    SimpleStringList *patterns, SimpleOidList *oids,
1300                                                    bool strict_names)
1301 {
1302         PQExpBuffer query;
1303         PGresult   *res;
1304         SimpleStringListCell *cell;
1305         int                     i;
1306
1307         if (patterns->head == NULL)
1308                 return;                                 /* nothing to do */
1309
1310         query = createPQExpBuffer();
1311
1312         /*
1313          * this might sometimes result in duplicate entries in the OID list, but
1314          * we don't care.
1315          */
1316
1317         for (cell = patterns->head; cell; cell = cell->next)
1318         {
1319                 /*
1320                  * Query must remain ABSOLUTELY devoid of unqualified names.  This
1321                  * would be unnecessary given a pg_table_is_visible() variant taking a
1322                  * search_path argument.
1323                  */
1324                 appendPQExpBuffer(query,
1325                                                   "SELECT c.oid"
1326                                                   "\nFROM pg_catalog.pg_class c"
1327                                                   "\n     LEFT JOIN pg_catalog.pg_namespace n"
1328                                                   "\n     ON n.oid OPERATOR(pg_catalog.=) c.relnamespace"
1329                                                   "\nWHERE c.relkind OPERATOR(pg_catalog.=) ANY"
1330                                                   "\n    (array['%c', '%c', '%c', '%c', '%c', '%c'])\n",
1331                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1332                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
1333                                                   RELKIND_PARTITIONED_TABLE);
1334                 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1335                                                           false, "n.nspname", "c.relname", NULL,
1336                                                           "pg_catalog.pg_table_is_visible(c.oid)");
1337
1338                 ExecuteSqlStatement(fout, "RESET search_path");
1339                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1340                 PQclear(ExecuteSqlQueryForSingleRow(fout,
1341                                                                                         ALWAYS_SECURE_SEARCH_PATH_SQL));
1342                 if (strict_names && PQntuples(res) == 0)
1343                         exit_horribly(NULL, "no matching tables were found for pattern \"%s\"\n", cell->val);
1344
1345                 for (i = 0; i < PQntuples(res); i++)
1346                 {
1347                         simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1348                 }
1349
1350                 PQclear(res);
1351                 resetPQExpBuffer(query);
1352         }
1353
1354         destroyPQExpBuffer(query);
1355 }
1356
1357 /*
1358  * checkExtensionMembership
1359  *              Determine whether object is an extension member, and if so,
1360  *              record an appropriate dependency and set the object's dump flag.
1361  *
1362  * It's important to call this for each object that could be an extension
1363  * member.  Generally, we integrate this with determining the object's
1364  * to-be-dumped-ness, since extension membership overrides other rules for that.
1365  *
1366  * Returns true if object is an extension member, else false.
1367  */
1368 static bool
1369 checkExtensionMembership(DumpableObject *dobj, Archive *fout)
1370 {
1371         ExtensionInfo *ext = findOwningExtension(dobj->catId);
1372
1373         if (ext == NULL)
1374                 return false;
1375
1376         dobj->ext_member = true;
1377
1378         /* Record dependency so that getDependencies needn't deal with that */
1379         addObjectDependency(dobj, ext->dobj.dumpId);
1380
1381         /*
1382          * In 9.6 and above, mark the member object to have any non-initial ACL,
1383          * policies, and security labels dumped.
1384          *
1385          * Note that any initial ACLs (see pg_init_privs) will be removed when we
1386          * extract the information about the object.  We don't provide support for
1387          * initial policies and security labels and it seems unlikely for those to
1388          * ever exist, but we may have to revisit this later.
1389          *
1390          * Prior to 9.6, we do not include any extension member components.
1391          *
1392          * In binary upgrades, we still dump all components of the members
1393          * individually, since the idea is to exactly reproduce the database
1394          * contents rather than replace the extension contents with something
1395          * different.
1396          */
1397         if (fout->dopt->binary_upgrade)
1398                 dobj->dump = ext->dobj.dump;
1399         else
1400         {
1401                 if (fout->remoteVersion < 90600)
1402                         dobj->dump = DUMP_COMPONENT_NONE;
1403                 else
1404                         dobj->dump = ext->dobj.dump_contains & (DUMP_COMPONENT_ACL |
1405                                                                                                         DUMP_COMPONENT_SECLABEL |
1406                                                                                                         DUMP_COMPONENT_POLICY);
1407         }
1408
1409         return true;
1410 }
1411
1412 /*
1413  * selectDumpableNamespace: policy-setting subroutine
1414  *              Mark a namespace as to be dumped or not
1415  */
1416 static void
1417 selectDumpableNamespace(NamespaceInfo *nsinfo, Archive *fout)
1418 {
1419         /*
1420          * If specific tables are being dumped, do not dump any complete
1421          * namespaces. If specific namespaces are being dumped, dump just those
1422          * namespaces. Otherwise, dump all non-system namespaces.
1423          */
1424         if (table_include_oids.head != NULL)
1425                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1426         else if (schema_include_oids.head != NULL)
1427                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump =
1428                         simple_oid_list_member(&schema_include_oids,
1429                                                                    nsinfo->dobj.catId.oid) ?
1430                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1431         else if (fout->remoteVersion >= 90600 &&
1432                          strcmp(nsinfo->dobj.name, "pg_catalog") == 0)
1433         {
1434                 /*
1435                  * In 9.6 and above, we dump out any ACLs defined in pg_catalog, if
1436                  * they are interesting (and not the original ACLs which were set at
1437                  * initdb time, see pg_init_privs).
1438                  */
1439                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1440         }
1441         else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1442                          strcmp(nsinfo->dobj.name, "information_schema") == 0)
1443         {
1444                 /* Other system schemas don't get dumped */
1445                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1446         }
1447         else if (strcmp(nsinfo->dobj.name, "public") == 0)
1448         {
1449                 /*
1450                  * The public schema is a strange beast that sits in a sort of
1451                  * no-mans-land between being a system object and a user object.  We
1452                  * don't want to dump creation or comment commands for it, because
1453                  * that complicates matters for non-superuser use of pg_dump.  But we
1454                  * should dump any ACL changes that have occurred for it, and of
1455                  * course we should dump contained objects.
1456                  */
1457                 nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1458                 nsinfo->dobj.dump_contains = DUMP_COMPONENT_ALL;
1459         }
1460         else
1461                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ALL;
1462
1463         /*
1464          * In any case, a namespace can be excluded by an exclusion switch
1465          */
1466         if (nsinfo->dobj.dump_contains &&
1467                 simple_oid_list_member(&schema_exclude_oids,
1468                                                            nsinfo->dobj.catId.oid))
1469                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1470
1471         /*
1472          * If the schema belongs to an extension, allow extension membership to
1473          * override the dump decision for the schema itself.  However, this does
1474          * not change dump_contains, so this won't change what we do with objects
1475          * within the schema.  (If they belong to the extension, they'll get
1476          * suppressed by it, otherwise not.)
1477          */
1478         (void) checkExtensionMembership(&nsinfo->dobj, fout);
1479 }
1480
1481 /*
1482  * selectDumpableTable: policy-setting subroutine
1483  *              Mark a table as to be dumped or not
1484  */
1485 static void
1486 selectDumpableTable(TableInfo *tbinfo, Archive *fout)
1487 {
1488         if (checkExtensionMembership(&tbinfo->dobj, fout))
1489                 return;                                 /* extension membership overrides all else */
1490
1491         /*
1492          * If specific tables are being dumped, dump just those tables; else, dump
1493          * according to the parent namespace's dump flag.
1494          */
1495         if (table_include_oids.head != NULL)
1496                 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1497                                                                                                    tbinfo->dobj.catId.oid) ?
1498                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1499         else
1500                 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump_contains;
1501
1502         /*
1503          * In any case, a table can be excluded by an exclusion switch
1504          */
1505         if (tbinfo->dobj.dump &&
1506                 simple_oid_list_member(&table_exclude_oids,
1507                                                            tbinfo->dobj.catId.oid))
1508                 tbinfo->dobj.dump = DUMP_COMPONENT_NONE;
1509 }
1510
1511 /*
1512  * selectDumpableType: policy-setting subroutine
1513  *              Mark a type as to be dumped or not
1514  *
1515  * If it's a table's rowtype or an autogenerated array type, we also apply a
1516  * special type code to facilitate sorting into the desired order.  (We don't
1517  * want to consider those to be ordinary types because that would bring tables
1518  * up into the datatype part of the dump order.)  We still set the object's
1519  * dump flag; that's not going to cause the dummy type to be dumped, but we
1520  * need it so that casts involving such types will be dumped correctly -- see
1521  * dumpCast.  This means the flag should be set the same as for the underlying
1522  * object (the table or base type).
1523  */
1524 static void
1525 selectDumpableType(TypeInfo *tyinfo, Archive *fout)
1526 {
1527         /* skip complex types, except for standalone composite types */
1528         if (OidIsValid(tyinfo->typrelid) &&
1529                 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1530         {
1531                 TableInfo  *tytable = findTableByOid(tyinfo->typrelid);
1532
1533                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1534                 if (tytable != NULL)
1535                         tyinfo->dobj.dump = tytable->dobj.dump;
1536                 else
1537                         tyinfo->dobj.dump = DUMP_COMPONENT_NONE;
1538                 return;
1539         }
1540
1541         /* skip auto-generated array types */
1542         if (tyinfo->isArray)
1543         {
1544                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1545
1546                 /*
1547                  * Fall through to set the dump flag; we assume that the subsequent
1548                  * rules will do the same thing as they would for the array's base
1549                  * type.  (We cannot reliably look up the base type here, since
1550                  * getTypes may not have processed it yet.)
1551                  */
1552         }
1553
1554         if (checkExtensionMembership(&tyinfo->dobj, fout))
1555                 return;                                 /* extension membership overrides all else */
1556
1557         /* Dump based on if the contents of the namespace are being dumped */
1558         tyinfo->dobj.dump = tyinfo->dobj.namespace->dobj.dump_contains;
1559 }
1560
1561 /*
1562  * selectDumpableDefaultACL: policy-setting subroutine
1563  *              Mark a default ACL as to be dumped or not
1564  *
1565  * For per-schema default ACLs, dump if the schema is to be dumped.
1566  * Otherwise dump if we are dumping "everything".  Note that dataOnly
1567  * and aclsSkip are checked separately.
1568  */
1569 static void
1570 selectDumpableDefaultACL(DefaultACLInfo *dinfo, DumpOptions *dopt)
1571 {
1572         /* Default ACLs can't be extension members */
1573
1574         if (dinfo->dobj.namespace)
1575                 /* default ACLs are considered part of the namespace */
1576                 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump_contains;
1577         else
1578                 dinfo->dobj.dump = dopt->include_everything ?
1579                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1580 }
1581
1582 /*
1583  * selectDumpableCast: policy-setting subroutine
1584  *              Mark a cast as to be dumped or not
1585  *
1586  * Casts do not belong to any particular namespace (since they haven't got
1587  * names), nor do they have identifiable owners.  To distinguish user-defined
1588  * casts from built-in ones, we must resort to checking whether the cast's
1589  * OID is in the range reserved for initdb.
1590  */
1591 static void
1592 selectDumpableCast(CastInfo *cast, Archive *fout)
1593 {
1594         if (checkExtensionMembership(&cast->dobj, fout))
1595                 return;                                 /* extension membership overrides all else */
1596
1597         /*
1598          * This would be DUMP_COMPONENT_ACL for from-initdb casts, but they do not
1599          * support ACLs currently.
1600          */
1601         if (cast->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1602                 cast->dobj.dump = DUMP_COMPONENT_NONE;
1603         else
1604                 cast->dobj.dump = fout->dopt->include_everything ?
1605                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1606 }
1607
1608 /*
1609  * selectDumpableProcLang: policy-setting subroutine
1610  *              Mark a procedural language as to be dumped or not
1611  *
1612  * Procedural languages do not belong to any particular namespace.  To
1613  * identify built-in languages, we must resort to checking whether the
1614  * language's OID is in the range reserved for initdb.
1615  */
1616 static void
1617 selectDumpableProcLang(ProcLangInfo *plang, Archive *fout)
1618 {
1619         if (checkExtensionMembership(&plang->dobj, fout))
1620                 return;                                 /* extension membership overrides all else */
1621
1622         /*
1623          * Only include procedural languages when we are dumping everything.
1624          *
1625          * For from-initdb procedural languages, only include ACLs, as we do for
1626          * the pg_catalog namespace.  We need this because procedural languages do
1627          * not live in any namespace.
1628          */
1629         if (!fout->dopt->include_everything)
1630                 plang->dobj.dump = DUMP_COMPONENT_NONE;
1631         else
1632         {
1633                 if (plang->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1634                         plang->dobj.dump = fout->remoteVersion < 90600 ?
1635                                 DUMP_COMPONENT_NONE : DUMP_COMPONENT_ACL;
1636                 else
1637                         plang->dobj.dump = DUMP_COMPONENT_ALL;
1638         }
1639 }
1640
1641 /*
1642  * selectDumpableAccessMethod: policy-setting subroutine
1643  *              Mark an access method as to be dumped or not
1644  *
1645  * Access methods do not belong to any particular namespace.  To identify
1646  * built-in access methods, we must resort to checking whether the
1647  * method's OID is in the range reserved for initdb.
1648  */
1649 static void
1650 selectDumpableAccessMethod(AccessMethodInfo *method, Archive *fout)
1651 {
1652         if (checkExtensionMembership(&method->dobj, fout))
1653                 return;                                 /* extension membership overrides all else */
1654
1655         /*
1656          * This would be DUMP_COMPONENT_ACL for from-initdb access methods, but
1657          * they do not support ACLs currently.
1658          */
1659         if (method->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1660                 method->dobj.dump = DUMP_COMPONENT_NONE;
1661         else
1662                 method->dobj.dump = fout->dopt->include_everything ?
1663                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1664 }
1665
1666 /*
1667  * selectDumpableExtension: policy-setting subroutine
1668  *              Mark an extension as to be dumped or not
1669  *
1670  * Built-in extensions should be skipped except for checking ACLs, since we
1671  * assume those will already be installed in the target database.  We identify
1672  * such extensions by their having OIDs in the range reserved for initdb.
1673  * We dump all user-added extensions by default, or none of them if
1674  * include_everything is false (i.e., a --schema or --table switch was given).
1675  */
1676 static void
1677 selectDumpableExtension(ExtensionInfo *extinfo, DumpOptions *dopt)
1678 {
1679         /*
1680          * Use DUMP_COMPONENT_ACL for built-in extensions, to allow users to
1681          * change permissions on their member objects, if they wish to, and have
1682          * those changes preserved.
1683          */
1684         if (extinfo->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1685                 extinfo->dobj.dump = extinfo->dobj.dump_contains = DUMP_COMPONENT_ACL;
1686         else
1687                 extinfo->dobj.dump = extinfo->dobj.dump_contains =
1688                         dopt->include_everything ? DUMP_COMPONENT_ALL :
1689                         DUMP_COMPONENT_NONE;
1690 }
1691
1692 /*
1693  * selectDumpablePublicationTable: policy-setting subroutine
1694  *              Mark a publication table as to be dumped or not
1695  *
1696  * Publication tables have schemas, but those are ignored in decision making,
1697  * because publications are only dumped when we are dumping everything.
1698  */
1699 static void
1700 selectDumpablePublicationTable(DumpableObject *dobj, Archive *fout)
1701 {
1702         if (checkExtensionMembership(dobj, fout))
1703                 return;                                 /* extension membership overrides all else */
1704
1705         dobj->dump = fout->dopt->include_everything ?
1706                 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1707 }
1708
1709 /*
1710  * selectDumpableObject: policy-setting subroutine
1711  *              Mark a generic dumpable object as to be dumped or not
1712  *
1713  * Use this only for object types without a special-case routine above.
1714  */
1715 static void
1716 selectDumpableObject(DumpableObject *dobj, Archive *fout)
1717 {
1718         if (checkExtensionMembership(dobj, fout))
1719                 return;                                 /* extension membership overrides all else */
1720
1721         /*
1722          * Default policy is to dump if parent namespace is dumpable, or for
1723          * non-namespace-associated items, dump if we're dumping "everything".
1724          */
1725         if (dobj->namespace)
1726                 dobj->dump = dobj->namespace->dobj.dump_contains;
1727         else
1728                 dobj->dump = fout->dopt->include_everything ?
1729                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1730 }
1731
1732 /*
1733  *      Dump a table's contents for loading using the COPY command
1734  *      - this routine is called by the Archiver when it wants the table
1735  *        to be dumped.
1736  */
1737
1738 static int
1739 dumpTableData_copy(Archive *fout, void *dcontext)
1740 {
1741         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1742         TableInfo  *tbinfo = tdinfo->tdtable;
1743         const char *classname = tbinfo->dobj.name;
1744         const bool      hasoids = tbinfo->hasoids;
1745         const bool      oids = tdinfo->oids;
1746         PQExpBuffer q = createPQExpBuffer();
1747
1748         /*
1749          * Note: can't use getThreadLocalPQExpBuffer() here, we're calling fmtId
1750          * which uses it already.
1751          */
1752         PQExpBuffer clistBuf = createPQExpBuffer();
1753         PGconn     *conn = GetConnection(fout);
1754         PGresult   *res;
1755         int                     ret;
1756         char       *copybuf;
1757         const char *column_list;
1758
1759         if (g_verbose)
1760                 write_msg(NULL, "dumping contents of table \"%s.%s\"\n",
1761                                   tbinfo->dobj.namespace->dobj.name, classname);
1762
1763         /*
1764          * Specify the column list explicitly so that we have no possibility of
1765          * retrieving data in the wrong column order.  (The default column
1766          * ordering of COPY will not be what we want in certain corner cases
1767          * involving ADD COLUMN and inheritance.)
1768          */
1769         column_list = fmtCopyColumnList(tbinfo, clistBuf);
1770
1771         if (oids && hasoids)
1772         {
1773                 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1774                                                   fmtQualifiedDumpable(tbinfo),
1775                                                   column_list);
1776         }
1777         else if (tdinfo->filtercond)
1778         {
1779                 /* Note: this syntax is only supported in 8.2 and up */
1780                 appendPQExpBufferStr(q, "COPY (SELECT ");
1781                 /* klugery to get rid of parens in column list */
1782                 if (strlen(column_list) > 2)
1783                 {
1784                         appendPQExpBufferStr(q, column_list + 1);
1785                         q->data[q->len - 1] = ' ';
1786                 }
1787                 else
1788                         appendPQExpBufferStr(q, "* ");
1789                 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1790                                                   fmtQualifiedDumpable(tbinfo),
1791                                                   tdinfo->filtercond);
1792         }
1793         else
1794         {
1795                 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1796                                                   fmtQualifiedDumpable(tbinfo),
1797                                                   column_list);
1798         }
1799         res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1800         PQclear(res);
1801         destroyPQExpBuffer(clistBuf);
1802
1803         for (;;)
1804         {
1805                 ret = PQgetCopyData(conn, &copybuf, 0);
1806
1807                 if (ret < 0)
1808                         break;                          /* done or error */
1809
1810                 if (copybuf)
1811                 {
1812                         WriteData(fout, copybuf, ret);
1813                         PQfreemem(copybuf);
1814                 }
1815
1816                 /* ----------
1817                  * THROTTLE:
1818                  *
1819                  * There was considerable discussion in late July, 2000 regarding
1820                  * slowing down pg_dump when backing up large tables. Users with both
1821                  * slow & fast (multi-processor) machines experienced performance
1822                  * degradation when doing a backup.
1823                  *
1824                  * Initial attempts based on sleeping for a number of ms for each ms
1825                  * of work were deemed too complex, then a simple 'sleep in each loop'
1826                  * implementation was suggested. The latter failed because the loop
1827                  * was too tight. Finally, the following was implemented:
1828                  *
1829                  * If throttle is non-zero, then
1830                  *              See how long since the last sleep.
1831                  *              Work out how long to sleep (based on ratio).
1832                  *              If sleep is more than 100ms, then
1833                  *                      sleep
1834                  *                      reset timer
1835                  *              EndIf
1836                  * EndIf
1837                  *
1838                  * where the throttle value was the number of ms to sleep per ms of
1839                  * work. The calculation was done in each loop.
1840                  *
1841                  * Most of the hard work is done in the backend, and this solution
1842                  * still did not work particularly well: on slow machines, the ratio
1843                  * was 50:1, and on medium paced machines, 1:1, and on fast
1844                  * multi-processor machines, it had little or no effect, for reasons
1845                  * that were unclear.
1846                  *
1847                  * Further discussion ensued, and the proposal was dropped.
1848                  *
1849                  * For those people who want this feature, it can be implemented using
1850                  * gettimeofday in each loop, calculating the time since last sleep,
1851                  * multiplying that by the sleep ratio, then if the result is more
1852                  * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1853                  * function to sleep for a subsecond period ie.
1854                  *
1855                  * select(0, NULL, NULL, NULL, &tvi);
1856                  *
1857                  * This will return after the interval specified in the structure tvi.
1858                  * Finally, call gettimeofday again to save the 'last sleep time'.
1859                  * ----------
1860                  */
1861         }
1862         archprintf(fout, "\\.\n\n\n");
1863
1864         if (ret == -2)
1865         {
1866                 /* copy data transfer failed */
1867                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1868                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1869                 write_msg(NULL, "The command was: %s\n", q->data);
1870                 exit_nicely(1);
1871         }
1872
1873         /* Check command status and return to normal libpq state */
1874         res = PQgetResult(conn);
1875         if (PQresultStatus(res) != PGRES_COMMAND_OK)
1876         {
1877                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1878                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1879                 write_msg(NULL, "The command was: %s\n", q->data);
1880                 exit_nicely(1);
1881         }
1882         PQclear(res);
1883
1884         /* Do this to ensure we've pumped libpq back to idle state */
1885         if (PQgetResult(conn) != NULL)
1886                 write_msg(NULL, "WARNING: unexpected extra results during COPY of table \"%s\"\n",
1887                                   classname);
1888
1889         destroyPQExpBuffer(q);
1890         return 1;
1891 }
1892
1893 /*
1894  * Dump table data using INSERT commands.
1895  *
1896  * Caution: when we restore from an archive file direct to database, the
1897  * INSERT commands emitted by this function have to be parsed by
1898  * pg_backup_db.c's ExecuteSimpleCommands(), which will not handle comments,
1899  * E'' strings, or dollar-quoted strings.  So don't emit anything like that.
1900  */
1901 static int
1902 dumpTableData_insert(Archive *fout, void *dcontext)
1903 {
1904         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1905         TableInfo  *tbinfo = tdinfo->tdtable;
1906         DumpOptions *dopt = fout->dopt;
1907         PQExpBuffer q = createPQExpBuffer();
1908         PQExpBuffer insertStmt = NULL;
1909         PGresult   *res;
1910         int                     tuple;
1911         int                     nfields;
1912         int                     field;
1913
1914         appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1915                                           "SELECT * FROM ONLY %s",
1916                                           fmtQualifiedDumpable(tbinfo));
1917         if (tdinfo->filtercond)
1918                 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1919
1920         ExecuteSqlStatement(fout, q->data);
1921
1922         while (1)
1923         {
1924                 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1925                                                           PGRES_TUPLES_OK);
1926                 nfields = PQnfields(res);
1927                 for (tuple = 0; tuple < PQntuples(res); tuple++)
1928                 {
1929                         /*
1930                          * First time through, we build as much of the INSERT statement as
1931                          * possible in "insertStmt", which we can then just print for each
1932                          * line. If the table happens to have zero columns then this will
1933                          * be a complete statement, otherwise it will end in "VALUES(" and
1934                          * be ready to have the row's column values appended.
1935                          */
1936                         if (insertStmt == NULL)
1937                         {
1938                                 TableInfo  *targettab;
1939
1940                                 insertStmt = createPQExpBuffer();
1941
1942                                 /*
1943                                  * When load-via-partition-root is set, get the root table
1944                                  * name for the partition table, so that we can reload data
1945                                  * through the root table.
1946                                  */
1947                                 if (dopt->load_via_partition_root && tbinfo->ispartition)
1948                                         targettab = getRootTableInfo(tbinfo);
1949                                 else
1950                                         targettab = tbinfo;
1951
1952                                 appendPQExpBuffer(insertStmt, "INSERT INTO %s ",
1953                                                                   fmtQualifiedDumpable(targettab));
1954
1955                                 /* corner case for zero-column table */
1956                                 if (nfields == 0)
1957                                 {
1958                                         appendPQExpBufferStr(insertStmt, "DEFAULT VALUES;\n");
1959                                 }
1960                                 else
1961                                 {
1962                                         /* append the list of column names if required */
1963                                         if (dopt->column_inserts)
1964                                         {
1965                                                 appendPQExpBufferChar(insertStmt, '(');
1966                                                 for (field = 0; field < nfields; field++)
1967                                                 {
1968                                                         if (field > 0)
1969                                                                 appendPQExpBufferStr(insertStmt, ", ");
1970                                                         appendPQExpBufferStr(insertStmt,
1971                                                                                                  fmtId(PQfname(res, field)));
1972                                                 }
1973                                                 appendPQExpBufferStr(insertStmt, ") ");
1974                                         }
1975
1976                                         if (tbinfo->needs_override)
1977                                                 appendPQExpBufferStr(insertStmt, "OVERRIDING SYSTEM VALUE ");
1978
1979                                         appendPQExpBufferStr(insertStmt, "VALUES (");
1980                                 }
1981                         }
1982
1983                         archputs(insertStmt->data, fout);
1984
1985                         /* if it is zero-column table then we're done */
1986                         if (nfields == 0)
1987                                 continue;
1988
1989                         for (field = 0; field < nfields; field++)
1990                         {
1991                                 if (field > 0)
1992                                         archputs(", ", fout);
1993                                 if (PQgetisnull(res, tuple, field))
1994                                 {
1995                                         archputs("NULL", fout);
1996                                         continue;
1997                                 }
1998
1999                                 /* XXX This code is partially duplicated in ruleutils.c */
2000                                 switch (PQftype(res, field))
2001                                 {
2002                                         case INT2OID:
2003                                         case INT4OID:
2004                                         case INT8OID:
2005                                         case OIDOID:
2006                                         case FLOAT4OID:
2007                                         case FLOAT8OID:
2008                                         case NUMERICOID:
2009                                                 {
2010                                                         /*
2011                                                          * These types are printed without quotes unless
2012                                                          * they contain values that aren't accepted by the
2013                                                          * scanner unquoted (e.g., 'NaN').  Note that
2014                                                          * strtod() and friends might accept NaN, so we
2015                                                          * can't use that to test.
2016                                                          *
2017                                                          * In reality we only need to defend against
2018                                                          * infinity and NaN, so we need not get too crazy
2019                                                          * about pattern matching here.
2020                                                          */
2021                                                         const char *s = PQgetvalue(res, tuple, field);
2022
2023                                                         if (strspn(s, "0123456789 +-eE.") == strlen(s))
2024                                                                 archputs(s, fout);
2025                                                         else
2026                                                                 archprintf(fout, "'%s'", s);
2027                                                 }
2028                                                 break;
2029
2030                                         case BITOID:
2031                                         case VARBITOID:
2032                                                 archprintf(fout, "B'%s'",
2033                                                                    PQgetvalue(res, tuple, field));
2034                                                 break;
2035
2036                                         case BOOLOID:
2037                                                 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
2038                                                         archputs("true", fout);
2039                                                 else
2040                                                         archputs("false", fout);
2041                                                 break;
2042
2043                                         default:
2044                                                 /* All other types are printed as string literals. */
2045                                                 resetPQExpBuffer(q);
2046                                                 appendStringLiteralAH(q,
2047                                                                                           PQgetvalue(res, tuple, field),
2048                                                                                           fout);
2049                                                 archputs(q->data, fout);
2050                                                 break;
2051                                 }
2052                         }
2053
2054                         if (!dopt->do_nothing)
2055                                 archputs(");\n", fout);
2056                         else
2057                                 archputs(") ON CONFLICT DO NOTHING;\n", fout);
2058                 }
2059
2060                 if (PQntuples(res) <= 0)
2061                 {
2062                         PQclear(res);
2063                         break;
2064                 }
2065                 PQclear(res);
2066         }
2067
2068         archputs("\n\n", fout);
2069
2070         ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
2071
2072         destroyPQExpBuffer(q);
2073         if (insertStmt != NULL)
2074                 destroyPQExpBuffer(insertStmt);
2075
2076         return 1;
2077 }
2078
2079 /*
2080  * getRootTableInfo:
2081  *     get the root TableInfo for the given partition table.
2082  */
2083 static TableInfo *
2084 getRootTableInfo(TableInfo *tbinfo)
2085 {
2086         TableInfo  *parentTbinfo;
2087
2088         Assert(tbinfo->ispartition);
2089         Assert(tbinfo->numParents == 1);
2090
2091         parentTbinfo = tbinfo->parents[0];
2092         while (parentTbinfo->ispartition)
2093         {
2094                 Assert(parentTbinfo->numParents == 1);
2095                 parentTbinfo = parentTbinfo->parents[0];
2096         }
2097
2098         return parentTbinfo;
2099 }
2100
2101 /*
2102  * dumpTableData -
2103  *        dump the contents of a single table
2104  *
2105  * Actually, this just makes an ArchiveEntry for the table contents.
2106  */
2107 static void
2108 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
2109 {
2110         DumpOptions *dopt = fout->dopt;
2111         TableInfo  *tbinfo = tdinfo->tdtable;
2112         PQExpBuffer copyBuf = createPQExpBuffer();
2113         PQExpBuffer clistBuf = createPQExpBuffer();
2114         DataDumperPtr dumpFn;
2115         char       *copyStmt;
2116         const char *copyFrom;
2117
2118         if (!dopt->dump_inserts)
2119         {
2120                 /* Dump/restore using COPY */
2121                 dumpFn = dumpTableData_copy;
2122
2123                 /*
2124                  * When load-via-partition-root is set, get the root table name for
2125                  * the partition table, so that we can reload data through the root
2126                  * table.
2127                  */
2128                 if (dopt->load_via_partition_root && tbinfo->ispartition)
2129                 {
2130                         TableInfo  *parentTbinfo;
2131
2132                         parentTbinfo = getRootTableInfo(tbinfo);
2133                         copyFrom = fmtQualifiedDumpable(parentTbinfo);
2134                 }
2135                 else
2136                         copyFrom = fmtQualifiedDumpable(tbinfo);
2137
2138                 /* must use 2 steps here 'cause fmtId is nonreentrant */
2139                 appendPQExpBuffer(copyBuf, "COPY %s ",
2140                                                   copyFrom);
2141                 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
2142                                                   fmtCopyColumnList(tbinfo, clistBuf),
2143                                                   (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
2144                 copyStmt = copyBuf->data;
2145         }
2146         else
2147         {
2148                 /* Restore using INSERT */
2149                 dumpFn = dumpTableData_insert;
2150                 copyStmt = NULL;
2151         }
2152
2153         /*
2154          * Note: although the TableDataInfo is a full DumpableObject, we treat its
2155          * dependency on its table as "special" and pass it to ArchiveEntry now.
2156          * See comments for BuildArchiveDependencies.
2157          */
2158         if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2159                 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
2160                                          tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
2161                                          NULL, tbinfo->rolname,
2162                                          false, "TABLE DATA", SECTION_DATA,
2163                                          "", "", copyStmt,
2164                                          &(tbinfo->dobj.dumpId), 1,
2165                                          dumpFn, tdinfo);
2166
2167         destroyPQExpBuffer(copyBuf);
2168         destroyPQExpBuffer(clistBuf);
2169 }
2170
2171 /*
2172  * refreshMatViewData -
2173  *        load or refresh the contents of a single materialized view
2174  *
2175  * Actually, this just makes an ArchiveEntry for the REFRESH MATERIALIZED VIEW
2176  * statement.
2177  */
2178 static void
2179 refreshMatViewData(Archive *fout, TableDataInfo *tdinfo)
2180 {
2181         TableInfo  *tbinfo = tdinfo->tdtable;
2182         PQExpBuffer q;
2183
2184         /* If the materialized view is not flagged as populated, skip this. */
2185         if (!tbinfo->relispopulated)
2186                 return;
2187
2188         q = createPQExpBuffer();
2189
2190         appendPQExpBuffer(q, "REFRESH MATERIALIZED VIEW %s;\n",
2191                                           fmtQualifiedDumpable(tbinfo));
2192
2193         if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2194                 ArchiveEntry(fout,
2195                                          tdinfo->dobj.catId,    /* catalog ID */
2196                                          tdinfo->dobj.dumpId,   /* dump ID */
2197                                          tbinfo->dobj.name, /* Name */
2198                                          tbinfo->dobj.namespace->dobj.name, /* Namespace */
2199                                          NULL,          /* Tablespace */
2200                                          tbinfo->rolname,       /* Owner */
2201                                          false,         /* with oids */
2202                                          "MATERIALIZED VIEW DATA",      /* Desc */
2203                                          SECTION_POST_DATA, /* Section */
2204                                          q->data,       /* Create */
2205                                          "",            /* Del */
2206                                          NULL,          /* Copy */
2207                                          tdinfo->dobj.dependencies, /* Deps */
2208                                          tdinfo->dobj.nDeps,    /* # Deps */
2209                                          NULL,          /* Dumper */
2210                                          NULL);         /* Dumper Arg */
2211
2212         destroyPQExpBuffer(q);
2213 }
2214
2215 /*
2216  * getTableData -
2217  *        set up dumpable objects representing the contents of tables
2218  */
2219 static void
2220 getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, bool oids, char relkind)
2221 {
2222         int                     i;
2223
2224         for (i = 0; i < numTables; i++)
2225         {
2226                 if (tblinfo[i].dobj.dump & DUMP_COMPONENT_DATA &&
2227                         (!relkind || tblinfo[i].relkind == relkind))
2228                         makeTableDataInfo(dopt, &(tblinfo[i]), oids);
2229         }
2230 }
2231
2232 /*
2233  * Make a dumpable object for the data of this specific table
2234  *
2235  * Note: we make a TableDataInfo if and only if we are going to dump the
2236  * table data; the "dump" flag in such objects isn't used.
2237  */
2238 static void
2239 makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo, bool oids)
2240 {
2241         TableDataInfo *tdinfo;
2242
2243         /*
2244          * Nothing to do if we already decided to dump the table.  This will
2245          * happen for "config" tables.
2246          */
2247         if (tbinfo->dataObj != NULL)
2248                 return;
2249
2250         /* Skip VIEWs (no data to dump) */
2251         if (tbinfo->relkind == RELKIND_VIEW)
2252                 return;
2253         /* Skip FOREIGN TABLEs (no data to dump) */
2254         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
2255                 return;
2256         /* Skip partitioned tables (data in partitions) */
2257         if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
2258                 return;
2259
2260         /* Don't dump data in unlogged tables, if so requested */
2261         if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
2262                 dopt->no_unlogged_table_data)
2263                 return;
2264
2265         /* Check that the data is not explicitly excluded */
2266         if (simple_oid_list_member(&tabledata_exclude_oids,
2267                                                            tbinfo->dobj.catId.oid))
2268                 return;
2269
2270         /* OK, let's dump it */
2271         tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
2272
2273         if (tbinfo->relkind == RELKIND_MATVIEW)
2274                 tdinfo->dobj.objType = DO_REFRESH_MATVIEW;
2275         else if (tbinfo->relkind == RELKIND_SEQUENCE)
2276                 tdinfo->dobj.objType = DO_SEQUENCE_SET;
2277         else
2278                 tdinfo->dobj.objType = DO_TABLE_DATA;
2279
2280         /*
2281          * Note: use tableoid 0 so that this object won't be mistaken for
2282          * something that pg_depend entries apply to.
2283          */
2284         tdinfo->dobj.catId.tableoid = 0;
2285         tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
2286         AssignDumpId(&tdinfo->dobj);
2287         tdinfo->dobj.name = tbinfo->dobj.name;
2288         tdinfo->dobj.namespace = tbinfo->dobj.namespace;
2289         tdinfo->tdtable = tbinfo;
2290         tdinfo->oids = oids;
2291         tdinfo->filtercond = NULL;      /* might get set later */
2292         addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
2293
2294         tbinfo->dataObj = tdinfo;
2295 }
2296
2297 /*
2298  * The refresh for a materialized view must be dependent on the refresh for
2299  * any materialized view that this one is dependent on.
2300  *
2301  * This must be called after all the objects are created, but before they are
2302  * sorted.
2303  */
2304 static void
2305 buildMatViewRefreshDependencies(Archive *fout)
2306 {
2307         PQExpBuffer query;
2308         PGresult   *res;
2309         int                     ntups,
2310                                 i;
2311         int                     i_classid,
2312                                 i_objid,
2313                                 i_refobjid;
2314
2315         /* No Mat Views before 9.3. */
2316         if (fout->remoteVersion < 90300)
2317                 return;
2318
2319         query = createPQExpBuffer();
2320
2321         appendPQExpBufferStr(query, "WITH RECURSIVE w AS "
2322                                                  "( "
2323                                                  "SELECT d1.objid, d2.refobjid, c2.relkind AS refrelkind "
2324                                                  "FROM pg_depend d1 "
2325                                                  "JOIN pg_class c1 ON c1.oid = d1.objid "
2326                                                  "AND c1.relkind = " CppAsString2(RELKIND_MATVIEW)
2327                                                  " JOIN pg_rewrite r1 ON r1.ev_class = d1.objid "
2328                                                  "JOIN pg_depend d2 ON d2.classid = 'pg_rewrite'::regclass "
2329                                                  "AND d2.objid = r1.oid "
2330                                                  "AND d2.refobjid <> d1.objid "
2331                                                  "JOIN pg_class c2 ON c2.oid = d2.refobjid "
2332                                                  "AND c2.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2333                                                  CppAsString2(RELKIND_VIEW) ") "
2334                                                  "WHERE d1.classid = 'pg_class'::regclass "
2335                                                  "UNION "
2336                                                  "SELECT w.objid, d3.refobjid, c3.relkind "
2337                                                  "FROM w "
2338                                                  "JOIN pg_rewrite r3 ON r3.ev_class = w.refobjid "
2339                                                  "JOIN pg_depend d3 ON d3.classid = 'pg_rewrite'::regclass "
2340                                                  "AND d3.objid = r3.oid "
2341                                                  "AND d3.refobjid <> w.refobjid "
2342                                                  "JOIN pg_class c3 ON c3.oid = d3.refobjid "
2343                                                  "AND c3.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2344                                                  CppAsString2(RELKIND_VIEW) ") "
2345                                                  ") "
2346                                                  "SELECT 'pg_class'::regclass::oid AS classid, objid, refobjid "
2347                                                  "FROM w "
2348                                                  "WHERE refrelkind = " CppAsString2(RELKIND_MATVIEW));
2349
2350         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2351
2352         ntups = PQntuples(res);
2353
2354         i_classid = PQfnumber(res, "classid");
2355         i_objid = PQfnumber(res, "objid");
2356         i_refobjid = PQfnumber(res, "refobjid");
2357
2358         for (i = 0; i < ntups; i++)
2359         {
2360                 CatalogId       objId;
2361                 CatalogId       refobjId;
2362                 DumpableObject *dobj;
2363                 DumpableObject *refdobj;
2364                 TableInfo  *tbinfo;
2365                 TableInfo  *reftbinfo;
2366
2367                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
2368                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
2369                 refobjId.tableoid = objId.tableoid;
2370                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
2371
2372                 dobj = findObjectByCatalogId(objId);
2373                 if (dobj == NULL)
2374                         continue;
2375
2376                 Assert(dobj->objType == DO_TABLE);
2377                 tbinfo = (TableInfo *) dobj;
2378                 Assert(tbinfo->relkind == RELKIND_MATVIEW);
2379                 dobj = (DumpableObject *) tbinfo->dataObj;
2380                 if (dobj == NULL)
2381                         continue;
2382                 Assert(dobj->objType == DO_REFRESH_MATVIEW);
2383
2384                 refdobj = findObjectByCatalogId(refobjId);
2385                 if (refdobj == NULL)
2386                         continue;
2387
2388                 Assert(refdobj->objType == DO_TABLE);
2389                 reftbinfo = (TableInfo *) refdobj;
2390                 Assert(reftbinfo->relkind == RELKIND_MATVIEW);
2391                 refdobj = (DumpableObject *) reftbinfo->dataObj;
2392                 if (refdobj == NULL)
2393                         continue;
2394                 Assert(refdobj->objType == DO_REFRESH_MATVIEW);
2395
2396                 addObjectDependency(dobj, refdobj->dumpId);
2397
2398                 if (!reftbinfo->relispopulated)
2399                         tbinfo->relispopulated = false;
2400         }
2401
2402         PQclear(res);
2403
2404         destroyPQExpBuffer(query);
2405 }
2406
2407 /*
2408  * getTableDataFKConstraints -
2409  *        add dump-order dependencies reflecting foreign key constraints
2410  *
2411  * This code is executed only in a data-only dump --- in schema+data dumps
2412  * we handle foreign key issues by not creating the FK constraints until
2413  * after the data is loaded.  In a data-only dump, however, we want to
2414  * order the table data objects in such a way that a table's referenced
2415  * tables are restored first.  (In the presence of circular references or
2416  * self-references this may be impossible; we'll detect and complain about
2417  * that during the dependency sorting step.)
2418  */
2419 static void
2420 getTableDataFKConstraints(void)
2421 {
2422         DumpableObject **dobjs;
2423         int                     numObjs;
2424         int                     i;
2425
2426         /* Search through all the dumpable objects for FK constraints */
2427         getDumpableObjects(&dobjs, &numObjs);
2428         for (i = 0; i < numObjs; i++)
2429         {
2430                 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
2431                 {
2432                         ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
2433                         TableInfo  *ftable;
2434
2435                         /* Not interesting unless both tables are to be dumped */
2436                         if (cinfo->contable == NULL ||
2437                                 cinfo->contable->dataObj == NULL)
2438                                 continue;
2439                         ftable = findTableByOid(cinfo->confrelid);
2440                         if (ftable == NULL ||
2441                                 ftable->dataObj == NULL)
2442                                 continue;
2443
2444                         /*
2445                          * Okay, make referencing table's TABLE_DATA object depend on the
2446                          * referenced table's TABLE_DATA object.
2447                          */
2448                         addObjectDependency(&cinfo->contable->dataObj->dobj,
2449                                                                 ftable->dataObj->dobj.dumpId);
2450                 }
2451         }
2452         free(dobjs);
2453 }
2454
2455
2456 /*
2457  * guessConstraintInheritance:
2458  *      In pre-8.4 databases, we can't tell for certain which constraints
2459  *      are inherited.  We assume a CHECK constraint is inherited if its name
2460  *      matches the name of any constraint in the parent.  Originally this code
2461  *      tried to compare the expression texts, but that can fail for various
2462  *      reasons --- for example, if the parent and child tables are in different
2463  *      schemas, reverse-listing of function calls may produce different text
2464  *      (schema-qualified or not) depending on search path.
2465  *
2466  *      In 8.4 and up we can rely on the conislocal field to decide which
2467  *      constraints must be dumped; much safer.
2468  *
2469  *      This function assumes all conislocal flags were initialized to true.
2470  *      It clears the flag on anything that seems to be inherited.
2471  */
2472 static void
2473 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
2474 {
2475         int                     i,
2476                                 j,
2477                                 k;
2478
2479         for (i = 0; i < numTables; i++)
2480         {
2481                 TableInfo  *tbinfo = &(tblinfo[i]);
2482                 int                     numParents;
2483                 TableInfo **parents;
2484                 TableInfo  *parent;
2485
2486                 /* Sequences and views never have parents */
2487                 if (tbinfo->relkind == RELKIND_SEQUENCE ||
2488                         tbinfo->relkind == RELKIND_VIEW)
2489                         continue;
2490
2491                 /* Don't bother computing anything for non-target tables, either */
2492                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
2493                         continue;
2494
2495                 numParents = tbinfo->numParents;
2496                 parents = tbinfo->parents;
2497
2498                 if (numParents == 0)
2499                         continue;                       /* nothing to see here, move along */
2500
2501                 /* scan for inherited CHECK constraints */
2502                 for (j = 0; j < tbinfo->ncheck; j++)
2503                 {
2504                         ConstraintInfo *constr;
2505
2506                         constr = &(tbinfo->checkexprs[j]);
2507
2508                         for (k = 0; k < numParents; k++)
2509                         {
2510                                 int                     l;
2511
2512                                 parent = parents[k];
2513                                 for (l = 0; l < parent->ncheck; l++)
2514                                 {
2515                                         ConstraintInfo *pconstr = &(parent->checkexprs[l]);
2516
2517                                         if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
2518                                         {
2519                                                 constr->conislocal = false;
2520                                                 break;
2521                                         }
2522                                 }
2523                                 if (!constr->conislocal)
2524                                         break;
2525                         }
2526                 }
2527         }
2528 }
2529
2530
2531 /*
2532  * dumpDatabase:
2533  *      dump the database definition
2534  */
2535 static void
2536 dumpDatabase(Archive *fout)
2537 {
2538         DumpOptions *dopt = fout->dopt;
2539         PQExpBuffer dbQry = createPQExpBuffer();
2540         PQExpBuffer delQry = createPQExpBuffer();
2541         PQExpBuffer creaQry = createPQExpBuffer();
2542         PQExpBuffer labelq = createPQExpBuffer();
2543         PGconn     *conn = GetConnection(fout);
2544         PGresult   *res;
2545         int                     i_tableoid,
2546                                 i_oid,
2547                                 i_datname,
2548                                 i_dba,
2549                                 i_encoding,
2550                                 i_collate,
2551                                 i_ctype,
2552                                 i_frozenxid,
2553                                 i_minmxid,
2554                                 i_datacl,
2555                                 i_rdatacl,
2556                                 i_datistemplate,
2557                                 i_datconnlimit,
2558                                 i_tablespace;
2559         CatalogId       dbCatId;
2560         DumpId          dbDumpId;
2561         const char *datname,
2562                            *dba,
2563                            *encoding,
2564                            *collate,
2565                            *ctype,
2566                            *datacl,
2567                            *rdatacl,
2568                            *datistemplate,
2569                            *datconnlimit,
2570                            *tablespace;
2571         uint32          frozenxid,
2572                                 minmxid;
2573         char       *qdatname;
2574
2575         if (g_verbose)
2576                 write_msg(NULL, "saving database definition\n");
2577
2578         /* Fetch the database-level properties for this database */
2579         if (fout->remoteVersion >= 90600)
2580         {
2581                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2582                                                   "(%s datdba) AS dba, "
2583                                                   "pg_encoding_to_char(encoding) AS encoding, "
2584                                                   "datcollate, datctype, datfrozenxid, datminmxid, "
2585                                                   "(SELECT array_agg(acl ORDER BY acl::text COLLATE \"C\") FROM ( "
2586                                                   "  SELECT unnest(coalesce(datacl,acldefault('d',datdba))) AS acl "
2587                                                   "  EXCEPT SELECT unnest(acldefault('d',datdba))) as datacls)"
2588                                                   " AS datacl, "
2589                                                   "(SELECT array_agg(acl ORDER BY acl::text COLLATE \"C\") FROM ( "
2590                                                   "  SELECT unnest(acldefault('d',datdba)) AS acl "
2591                                                   "  EXCEPT SELECT unnest(coalesce(datacl,acldefault('d',datdba)))) as rdatacls)"
2592                                                   " AS rdatacl, "
2593                                                   "datistemplate, datconnlimit, "
2594                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2595                                                   "shobj_description(oid, 'pg_database') AS description "
2596
2597                                                   "FROM pg_database "
2598                                                   "WHERE datname = current_database()",
2599                                                   username_subquery);
2600         }
2601         else if (fout->remoteVersion >= 90300)
2602         {
2603                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2604                                                   "(%s datdba) AS dba, "
2605                                                   "pg_encoding_to_char(encoding) AS encoding, "
2606                                                   "datcollate, datctype, datfrozenxid, datminmxid, "
2607                                                   "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2608                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2609                                                   "shobj_description(oid, 'pg_database') AS description "
2610
2611                                                   "FROM pg_database "
2612                                                   "WHERE datname = current_database()",
2613                                                   username_subquery);
2614         }
2615         else if (fout->remoteVersion >= 80400)
2616         {
2617                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2618                                                   "(%s datdba) AS dba, "
2619                                                   "pg_encoding_to_char(encoding) AS encoding, "
2620                                                   "datcollate, datctype, datfrozenxid, 0 AS datminmxid, "
2621                                                   "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2622                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2623                                                   "shobj_description(oid, 'pg_database') AS description "
2624
2625                                                   "FROM pg_database "
2626                                                   "WHERE datname = current_database()",
2627                                                   username_subquery);
2628         }
2629         else if (fout->remoteVersion >= 80200)
2630         {
2631                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2632                                                   "(%s datdba) AS dba, "
2633                                                   "pg_encoding_to_char(encoding) AS encoding, "
2634                                                   "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2635                                                   "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2636                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2637                                                   "shobj_description(oid, 'pg_database') AS description "
2638
2639                                                   "FROM pg_database "
2640                                                   "WHERE datname = current_database()",
2641                                                   username_subquery);
2642         }
2643         else
2644         {
2645                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2646                                                   "(%s datdba) AS dba, "
2647                                                   "pg_encoding_to_char(encoding) AS encoding, "
2648                                                   "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2649                                                   "datacl, '' as rdatacl, datistemplate, "
2650                                                   "-1 as datconnlimit, "
2651                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
2652                                                   "FROM pg_database "
2653                                                   "WHERE datname = current_database()",
2654                                                   username_subquery);
2655         }
2656
2657         res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
2658
2659         i_tableoid = PQfnumber(res, "tableoid");
2660         i_oid = PQfnumber(res, "oid");
2661         i_datname = PQfnumber(res, "datname");
2662         i_dba = PQfnumber(res, "dba");
2663         i_encoding = PQfnumber(res, "encoding");
2664         i_collate = PQfnumber(res, "datcollate");
2665         i_ctype = PQfnumber(res, "datctype");
2666         i_frozenxid = PQfnumber(res, "datfrozenxid");
2667         i_minmxid = PQfnumber(res, "datminmxid");
2668         i_datacl = PQfnumber(res, "datacl");
2669         i_rdatacl = PQfnumber(res, "rdatacl");
2670         i_datistemplate = PQfnumber(res, "datistemplate");
2671         i_datconnlimit = PQfnumber(res, "datconnlimit");
2672         i_tablespace = PQfnumber(res, "tablespace");
2673
2674         dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
2675         dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
2676         datname = PQgetvalue(res, 0, i_datname);
2677         dba = PQgetvalue(res, 0, i_dba);
2678         encoding = PQgetvalue(res, 0, i_encoding);
2679         collate = PQgetvalue(res, 0, i_collate);
2680         ctype = PQgetvalue(res, 0, i_ctype);
2681         frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
2682         minmxid = atooid(PQgetvalue(res, 0, i_minmxid));
2683         datacl = PQgetvalue(res, 0, i_datacl);
2684         rdatacl = PQgetvalue(res, 0, i_rdatacl);
2685         datistemplate = PQgetvalue(res, 0, i_datistemplate);
2686         datconnlimit = PQgetvalue(res, 0, i_datconnlimit);
2687         tablespace = PQgetvalue(res, 0, i_tablespace);
2688
2689         qdatname = pg_strdup(fmtId(datname));
2690
2691         /*
2692          * Prepare the CREATE DATABASE command.  We must specify encoding, locale,
2693          * and tablespace since those can't be altered later.  Other DB properties
2694          * are left to the DATABASE PROPERTIES entry, so that they can be applied
2695          * after reconnecting to the target DB.
2696          */
2697         appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
2698                                           qdatname);
2699         if (strlen(encoding) > 0)
2700         {
2701                 appendPQExpBufferStr(creaQry, " ENCODING = ");
2702                 appendStringLiteralAH(creaQry, encoding, fout);
2703         }
2704         if (strlen(collate) > 0)
2705         {
2706                 appendPQExpBufferStr(creaQry, " LC_COLLATE = ");
2707                 appendStringLiteralAH(creaQry, collate, fout);
2708         }
2709         if (strlen(ctype) > 0)
2710         {
2711                 appendPQExpBufferStr(creaQry, " LC_CTYPE = ");
2712                 appendStringLiteralAH(creaQry, ctype, fout);
2713         }
2714
2715         /*
2716          * Note: looking at dopt->outputNoTablespaces here is completely the wrong
2717          * thing; the decision whether to specify a tablespace should be left till
2718          * pg_restore, so that pg_restore --no-tablespaces applies.  Ideally we'd
2719          * label the DATABASE entry with the tablespace and let the normal
2720          * tablespace selection logic work ... but CREATE DATABASE doesn't pay
2721          * attention to default_tablespace, so that won't work.
2722          */
2723         if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0 &&
2724                 !dopt->outputNoTablespaces)
2725                 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
2726                                                   fmtId(tablespace));
2727         appendPQExpBufferStr(creaQry, ";\n");
2728
2729         appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
2730                                           qdatname);
2731
2732         dbDumpId = createDumpId();
2733
2734         ArchiveEntry(fout,
2735                                  dbCatId,               /* catalog ID */
2736                                  dbDumpId,              /* dump ID */
2737                                  datname,               /* Name */
2738                                  NULL,                  /* Namespace */
2739                                  NULL,                  /* Tablespace */
2740                                  dba,                   /* Owner */
2741                                  false,                 /* with oids */
2742                                  "DATABASE",    /* Desc */
2743                                  SECTION_PRE_DATA,      /* Section */
2744                                  creaQry->data, /* Create */
2745                                  delQry->data,  /* Del */
2746                                  NULL,                  /* Copy */
2747                                  NULL,                  /* Deps */
2748                                  0,                             /* # Deps */
2749                                  NULL,                  /* Dumper */
2750                                  NULL);                 /* Dumper Arg */
2751
2752         /* Compute correct tag for archive entry */
2753         appendPQExpBuffer(labelq, "DATABASE %s", qdatname);
2754
2755         /* Dump DB comment if any */
2756         if (fout->remoteVersion >= 80200)
2757         {
2758                 /*
2759                  * 8.2 and up keep comments on shared objects in a shared table, so we
2760                  * cannot use the dumpComment() code used for other database objects.
2761                  * Be careful that the ArchiveEntry parameters match that function.
2762                  */
2763                 char       *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2764
2765                 if (comment && *comment && !dopt->no_comments)
2766                 {
2767                         resetPQExpBuffer(dbQry);
2768
2769                         /*
2770                          * Generates warning when loaded into a differently-named
2771                          * database.
2772                          */
2773                         appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", qdatname);
2774                         appendStringLiteralAH(dbQry, comment, fout);
2775                         appendPQExpBufferStr(dbQry, ";\n");
2776
2777                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2778                                                  labelq->data, NULL, NULL, dba,
2779                                                  false, "COMMENT", SECTION_NONE,
2780                                                  dbQry->data, "", NULL,
2781                                                  &(dbDumpId), 1,
2782                                                  NULL, NULL);
2783                 }
2784         }
2785         else
2786         {
2787                 dumpComment(fout, "DATABASE", qdatname, NULL, dba,
2788                                         dbCatId, 0, dbDumpId);
2789         }
2790
2791         /* Dump DB security label, if enabled */
2792         if (!dopt->no_security_labels && fout->remoteVersion >= 90200)
2793         {
2794                 PGresult   *shres;
2795                 PQExpBuffer seclabelQry;
2796
2797                 seclabelQry = createPQExpBuffer();
2798
2799                 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2800                 shres = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2801                 resetPQExpBuffer(seclabelQry);
2802                 emitShSecLabels(conn, shres, seclabelQry, "DATABASE", datname);
2803                 if (seclabelQry->len > 0)
2804                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2805                                                  labelq->data, NULL, NULL, dba,
2806                                                  false, "SECURITY LABEL", SECTION_NONE,
2807                                                  seclabelQry->data, "", NULL,
2808                                                  &(dbDumpId), 1,
2809                                                  NULL, NULL);
2810                 destroyPQExpBuffer(seclabelQry);
2811                 PQclear(shres);
2812         }
2813
2814         /*
2815          * Dump ACL if any.  Note that we do not support initial privileges
2816          * (pg_init_privs) on databases.
2817          */
2818         dumpACL(fout, dbCatId, dbDumpId, "DATABASE",
2819                         qdatname, NULL, NULL,
2820                         dba, datacl, rdatacl, "", "");
2821
2822         /*
2823          * Now construct a DATABASE PROPERTIES archive entry to restore any
2824          * non-default database-level properties.  (The reason this must be
2825          * separate is that we cannot put any additional commands into the TOC
2826          * entry that has CREATE DATABASE.  pg_restore would execute such a group
2827          * in an implicit transaction block, and the backend won't allow CREATE
2828          * DATABASE in that context.)
2829          */
2830         resetPQExpBuffer(creaQry);
2831         resetPQExpBuffer(delQry);
2832
2833         if (strlen(datconnlimit) > 0 && strcmp(datconnlimit, "-1") != 0)
2834                 appendPQExpBuffer(creaQry, "ALTER DATABASE %s CONNECTION LIMIT = %s;\n",
2835                                                   qdatname, datconnlimit);
2836
2837         if (strcmp(datistemplate, "t") == 0)
2838         {
2839                 appendPQExpBuffer(creaQry, "ALTER DATABASE %s IS_TEMPLATE = true;\n",
2840                                                   qdatname);
2841
2842                 /*
2843                  * The backend won't accept DROP DATABASE on a template database.  We
2844                  * can deal with that by removing the template marking before the DROP
2845                  * gets issued.  We'd prefer to use ALTER DATABASE IF EXISTS here, but
2846                  * since no such command is currently supported, fake it with a direct
2847                  * UPDATE on pg_database.
2848                  */
2849                 appendPQExpBufferStr(delQry, "UPDATE pg_catalog.pg_database "
2850                                                          "SET datistemplate = false WHERE datname = ");
2851                 appendStringLiteralAH(delQry, datname, fout);
2852                 appendPQExpBufferStr(delQry, ";\n");
2853         }
2854
2855         /* Add database-specific SET options */
2856         dumpDatabaseConfig(fout, creaQry, datname, dbCatId.oid);
2857
2858         /*
2859          * We stick this binary-upgrade query into the DATABASE PROPERTIES archive
2860          * entry, too, for lack of a better place.
2861          */
2862         if (dopt->binary_upgrade)
2863         {
2864                 appendPQExpBufferStr(creaQry, "\n-- For binary upgrade, set datfrozenxid and datminmxid.\n");
2865                 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
2866                                                   "SET datfrozenxid = '%u', datminmxid = '%u'\n"
2867                                                   "WHERE datname = ",
2868                                                   frozenxid, minmxid);
2869                 appendStringLiteralAH(creaQry, datname, fout);
2870                 appendPQExpBufferStr(creaQry, ";\n");
2871         }
2872
2873         if (creaQry->len > 0)
2874                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2875                                          datname, NULL, NULL, dba,
2876                                          false, "DATABASE PROPERTIES", SECTION_PRE_DATA,
2877                                          creaQry->data, delQry->data, NULL,
2878                                          &(dbDumpId), 1,
2879                                          NULL, NULL);
2880
2881         /*
2882          * pg_largeobject and pg_largeobject_metadata come from the old system
2883          * intact, so set their relfrozenxids and relminmxids.
2884          */
2885         if (dopt->binary_upgrade)
2886         {
2887                 PGresult   *lo_res;
2888                 PQExpBuffer loFrozenQry = createPQExpBuffer();
2889                 PQExpBuffer loOutQry = createPQExpBuffer();
2890                 int                     i_relfrozenxid,
2891                                         i_relminmxid;
2892
2893                 /*
2894                  * pg_largeobject
2895                  */
2896                 if (fout->remoteVersion >= 90300)
2897                         appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
2898                                                           "FROM pg_catalog.pg_class\n"
2899                                                           "WHERE oid = %u;\n",
2900                                                           LargeObjectRelationId);
2901                 else
2902                         appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
2903                                                           "FROM pg_catalog.pg_class\n"
2904                                                           "WHERE oid = %u;\n",
2905                                                           LargeObjectRelationId);
2906
2907                 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2908
2909                 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2910                 i_relminmxid = PQfnumber(lo_res, "relminmxid");
2911
2912                 appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject relfrozenxid and relminmxid\n");
2913                 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2914                                                   "SET relfrozenxid = '%u', relminmxid = '%u'\n"
2915                                                   "WHERE oid = %u;\n",
2916                                                   atooid(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2917                                                   atooid(PQgetvalue(lo_res, 0, i_relminmxid)),
2918                                                   LargeObjectRelationId);
2919                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2920                                          "pg_largeobject", NULL, NULL, "",
2921                                          false, "pg_largeobject", SECTION_PRE_DATA,
2922                                          loOutQry->data, "", NULL,
2923                                          NULL, 0,
2924                                          NULL, NULL);
2925
2926                 PQclear(lo_res);
2927
2928                 /*
2929                  * pg_largeobject_metadata
2930                  */
2931                 if (fout->remoteVersion >= 90000)
2932                 {
2933                         resetPQExpBuffer(loFrozenQry);
2934                         resetPQExpBuffer(loOutQry);
2935
2936                         if (fout->remoteVersion >= 90300)
2937                                 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
2938                                                                   "FROM pg_catalog.pg_class\n"
2939                                                                   "WHERE oid = %u;\n",
2940                                                                   LargeObjectMetadataRelationId);
2941                         else
2942                                 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
2943                                                                   "FROM pg_catalog.pg_class\n"
2944                                                                   "WHERE oid = %u;\n",
2945                                                                   LargeObjectMetadataRelationId);
2946
2947                         lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2948
2949                         i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2950                         i_relminmxid = PQfnumber(lo_res, "relminmxid");
2951
2952                         appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata relfrozenxid and relminmxid\n");
2953                         appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2954                                                           "SET relfrozenxid = '%u', relminmxid = '%u'\n"
2955                                                           "WHERE oid = %u;\n",
2956                                                           atooid(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2957                                                           atooid(PQgetvalue(lo_res, 0, i_relminmxid)),
2958                                                           LargeObjectMetadataRelationId);
2959                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2960                                                  "pg_largeobject_metadata", NULL, NULL, "",
2961                                                  false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2962                                                  loOutQry->data, "", NULL,
2963                                                  NULL, 0,
2964                                                  NULL, NULL);
2965
2966                         PQclear(lo_res);
2967                 }
2968
2969                 destroyPQExpBuffer(loFrozenQry);
2970                 destroyPQExpBuffer(loOutQry);
2971         }
2972
2973         PQclear(res);
2974
2975         free(qdatname);
2976         destroyPQExpBuffer(dbQry);
2977         destroyPQExpBuffer(delQry);
2978         destroyPQExpBuffer(creaQry);
2979         destroyPQExpBuffer(labelq);
2980 }
2981
2982 /*
2983  * Collect any database-specific or role-and-database-specific SET options
2984  * for this database, and append them to outbuf.
2985  */
2986 static void
2987 dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
2988                                    const char *dbname, Oid dboid)
2989 {
2990         PGconn     *conn = GetConnection(AH);
2991         PQExpBuffer buf = createPQExpBuffer();
2992         PGresult   *res;
2993         int                     count = 1;
2994
2995         /*
2996          * First collect database-specific options.  Pre-8.4 server versions lack
2997          * unnest(), so we do this the hard way by querying once per subscript.
2998          */
2999         for (;;)
3000         {
3001                 if (AH->remoteVersion >= 90000)
3002                         printfPQExpBuffer(buf, "SELECT setconfig[%d] FROM pg_db_role_setting "
3003                                                           "WHERE setrole = 0 AND setdatabase = '%u'::oid",
3004                                                           count, dboid);
3005                 else
3006                         printfPQExpBuffer(buf, "SELECT datconfig[%d] FROM pg_database WHERE oid = '%u'::oid", count, dboid);
3007
3008                 res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3009
3010                 if (PQntuples(res) == 1 &&
3011                         !PQgetisnull(res, 0, 0))
3012                 {
3013                         makeAlterConfigCommand(conn, PQgetvalue(res, 0, 0),
3014                                                                    "DATABASE", dbname, NULL, NULL,
3015                                                                    outbuf);
3016                         PQclear(res);
3017                         count++;
3018                 }
3019                 else
3020                 {
3021                         PQclear(res);
3022                         break;
3023                 }
3024         }
3025
3026         /* Now look for role-and-database-specific options */
3027         if (AH->remoteVersion >= 90000)
3028         {
3029                 /* Here we can assume we have unnest() */
3030                 printfPQExpBuffer(buf, "SELECT rolname, unnest(setconfig) "
3031                                                   "FROM pg_db_role_setting s, pg_roles r "
3032                                                   "WHERE setrole = r.oid AND setdatabase = '%u'::oid",
3033                                                   dboid);
3034
3035                 res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3036
3037                 if (PQntuples(res) > 0)
3038                 {
3039                         int                     i;
3040
3041                         for (i = 0; i < PQntuples(res); i++)
3042                                 makeAlterConfigCommand(conn, PQgetvalue(res, i, 1),
3043                                                                            "ROLE", PQgetvalue(res, i, 0),
3044                                                                            "DATABASE", dbname,
3045                                                                            outbuf);
3046                 }
3047
3048                 PQclear(res);
3049         }
3050
3051         destroyPQExpBuffer(buf);
3052 }
3053
3054 /*
3055  * dumpEncoding: put the correct encoding into the archive
3056  */
3057 static void
3058 dumpEncoding(Archive *AH)
3059 {
3060         const char *encname = pg_encoding_to_char(AH->encoding);
3061         PQExpBuffer qry = createPQExpBuffer();
3062
3063         if (g_verbose)
3064                 write_msg(NULL, "saving encoding = %s\n", encname);
3065
3066         appendPQExpBufferStr(qry, "SET client_encoding = ");
3067         appendStringLiteralAH(qry, encname, AH);
3068         appendPQExpBufferStr(qry, ";\n");
3069
3070         ArchiveEntry(AH, nilCatalogId, createDumpId(),
3071                                  "ENCODING", NULL, NULL, "",
3072                                  false, "ENCODING", SECTION_PRE_DATA,
3073                                  qry->data, "", NULL,
3074                                  NULL, 0,
3075                                  NULL, NULL);
3076
3077         destroyPQExpBuffer(qry);
3078 }
3079
3080
3081 /*
3082  * dumpStdStrings: put the correct escape string behavior into the archive
3083  */
3084 static void
3085 dumpStdStrings(Archive *AH)
3086 {
3087         const char *stdstrings = AH->std_strings ? "on" : "off";
3088         PQExpBuffer qry = createPQExpBuffer();
3089
3090         if (g_verbose)
3091                 write_msg(NULL, "saving standard_conforming_strings = %s\n",
3092                                   stdstrings);
3093
3094         appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
3095                                           stdstrings);
3096
3097         ArchiveEntry(AH, nilCatalogId, createDumpId(),
3098                                  "STDSTRINGS", NULL, NULL, "",
3099                                  false, "STDSTRINGS", SECTION_PRE_DATA,
3100                                  qry->data, "", NULL,
3101                                  NULL, 0,
3102                                  NULL, NULL);
3103
3104         destroyPQExpBuffer(qry);
3105 }
3106
3107 /*
3108  * dumpSearchPath: record the active search_path in the archive
3109  */
3110 static void
3111 dumpSearchPath(Archive *AH)
3112 {
3113         PQExpBuffer qry = createPQExpBuffer();
3114         PQExpBuffer path = createPQExpBuffer();
3115         PGresult   *res;
3116         char      **schemanames = NULL;
3117         int                     nschemanames = 0;
3118         int                     i;
3119
3120         /*
3121          * We use the result of current_schemas(), not the search_path GUC,
3122          * because that might contain wildcards such as "$user", which won't
3123          * necessarily have the same value during restore.  Also, this way avoids
3124          * listing schemas that may appear in search_path but not actually exist,
3125          * which seems like a prudent exclusion.
3126          */
3127         res = ExecuteSqlQueryForSingleRow(AH,
3128                                                                           "SELECT pg_catalog.current_schemas(false)");
3129
3130         if (!parsePGArray(PQgetvalue(res, 0, 0), &schemanames, &nschemanames))
3131                 exit_horribly(NULL, "could not parse result of current_schemas()\n");
3132
3133         /*
3134          * We use set_config(), not a simple "SET search_path" command, because
3135          * the latter has less-clean behavior if the search path is empty.  While
3136          * that's likely to get fixed at some point, it seems like a good idea to
3137          * be as backwards-compatible as possible in what we put into archives.
3138          */
3139         for (i = 0; i < nschemanames; i++)
3140         {
3141                 if (i > 0)
3142                         appendPQExpBufferStr(path, ", ");
3143                 appendPQExpBufferStr(path, fmtId(schemanames[i]));
3144         }
3145
3146         appendPQExpBufferStr(qry, "SELECT pg_catalog.set_config('search_path', ");
3147         appendStringLiteralAH(qry, path->data, AH);
3148         appendPQExpBufferStr(qry, ", false);\n");
3149
3150         if (g_verbose)
3151                 write_msg(NULL, "saving search_path = %s\n", path->data);
3152
3153         ArchiveEntry(AH, nilCatalogId, createDumpId(),
3154                                  "SEARCHPATH", NULL, NULL, "",
3155                                  false, "SEARCHPATH", SECTION_PRE_DATA,
3156                                  qry->data, "", NULL,
3157                                  NULL, 0,
3158                                  NULL, NULL);
3159
3160         /* Also save it in AH->searchpath, in case we're doing plain text dump */
3161         AH->searchpath = pg_strdup(qry->data);
3162
3163         if (schemanames)
3164                 free(schemanames);
3165         PQclear(res);
3166         destroyPQExpBuffer(qry);
3167         destroyPQExpBuffer(path);
3168 }
3169
3170
3171 /*
3172  * getBlobs:
3173  *      Collect schema-level data about large objects
3174  */
3175 static void
3176 getBlobs(Archive *fout)
3177 {
3178         DumpOptions *dopt = fout->dopt;
3179         PQExpBuffer blobQry = createPQExpBuffer();
3180         BlobInfo   *binfo;
3181         DumpableObject *bdata;
3182         PGresult   *res;
3183         int                     ntups;
3184         int                     i;
3185         int                     i_oid;
3186         int                     i_lomowner;
3187         int                     i_lomacl;
3188         int                     i_rlomacl;
3189         int                     i_initlomacl;
3190         int                     i_initrlomacl;
3191
3192         /* Verbose message */
3193         if (g_verbose)
3194                 write_msg(NULL, "reading large objects\n");
3195
3196         /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
3197         if (fout->remoteVersion >= 90600)
3198         {
3199                 PQExpBuffer acl_subquery = createPQExpBuffer();
3200                 PQExpBuffer racl_subquery = createPQExpBuffer();
3201                 PQExpBuffer init_acl_subquery = createPQExpBuffer();
3202                 PQExpBuffer init_racl_subquery = createPQExpBuffer();
3203
3204                 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
3205                                                 init_racl_subquery, "l.lomacl", "l.lomowner", "'L'",
3206                                                 dopt->binary_upgrade);
3207
3208                 appendPQExpBuffer(blobQry,
3209                                                   "SELECT l.oid, (%s l.lomowner) AS rolname, "
3210                                                   "%s AS lomacl, "
3211                                                   "%s AS rlomacl, "
3212                                                   "%s AS initlomacl, "
3213                                                   "%s AS initrlomacl "
3214                                                   "FROM pg_largeobject_metadata l "
3215                                                   "LEFT JOIN pg_init_privs pip ON "
3216                                                   "(l.oid = pip.objoid "
3217                                                   "AND pip.classoid = 'pg_largeobject'::regclass "
3218                                                   "AND pip.objsubid = 0) ",
3219                                                   username_subquery,
3220                                                   acl_subquery->data,
3221                                                   racl_subquery->data,
3222                                                   init_acl_subquery->data,
3223                                                   init_racl_subquery->data);
3224
3225                 destroyPQExpBuffer(acl_subquery);
3226                 destroyPQExpBuffer(racl_subquery);
3227                 destroyPQExpBuffer(init_acl_subquery);
3228                 destroyPQExpBuffer(init_racl_subquery);
3229         }
3230         else if (fout->remoteVersion >= 90000)
3231                 appendPQExpBuffer(blobQry,
3232                                                   "SELECT oid, (%s lomowner) AS rolname, lomacl, "
3233                                                   "NULL AS rlomacl, NULL AS initlomacl, "
3234                                                   "NULL AS initrlomacl "
3235                                                   " FROM pg_largeobject_metadata",
3236                                                   username_subquery);
3237         else
3238                 appendPQExpBufferStr(blobQry,
3239                                                          "SELECT DISTINCT loid AS oid, "
3240                                                          "NULL::name AS rolname, NULL::oid AS lomacl, "
3241                                                          "NULL::oid AS rlomacl, NULL::oid AS initlomacl, "
3242                                                          "NULL::oid AS initrlomacl "
3243                                                          " FROM pg_largeobject");
3244
3245         res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
3246
3247         i_oid = PQfnumber(res, "oid");
3248         i_lomowner = PQfnumber(res, "rolname");
3249         i_lomacl = PQfnumber(res, "lomacl");
3250         i_rlomacl = PQfnumber(res, "rlomacl");
3251         i_initlomacl = PQfnumber(res, "initlomacl");
3252         i_initrlomacl = PQfnumber(res, "initrlomacl");
3253
3254         ntups = PQntuples(res);
3255
3256         /*
3257          * Each large object has its own BLOB archive entry.
3258          */
3259         binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
3260
3261         for (i = 0; i < ntups; i++)
3262         {
3263                 binfo[i].dobj.objType = DO_BLOB;
3264                 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
3265                 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3266                 AssignDumpId(&binfo[i].dobj);
3267
3268                 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oid));
3269                 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_lomowner));
3270                 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, i_lomacl));
3271                 binfo[i].rblobacl = pg_strdup(PQgetvalue(res, i, i_rlomacl));
3272                 binfo[i].initblobacl = pg_strdup(PQgetvalue(res, i, i_initlomacl));
3273                 binfo[i].initrblobacl = pg_strdup(PQgetvalue(res, i, i_initrlomacl));
3274
3275                 if (PQgetisnull(res, i, i_lomacl) &&
3276                         PQgetisnull(res, i, i_rlomacl) &&
3277                         PQgetisnull(res, i, i_initlomacl) &&
3278                         PQgetisnull(res, i, i_initrlomacl))
3279                         binfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
3280
3281                 /*
3282                  * In binary-upgrade mode for blobs, we do *not* dump out the data or
3283                  * the ACLs, should any exist.  The data and ACL (if any) will be
3284                  * copied by pg_upgrade, which simply copies the pg_largeobject and
3285                  * pg_largeobject_metadata tables.
3286                  *
3287                  * We *do* dump out the definition of the blob because we need that to
3288                  * make the restoration of the comments, and anything else, work since
3289                  * pg_upgrade copies the files behind pg_largeobject and
3290                  * pg_largeobject_metadata after the dump is restored.
3291                  */
3292                 if (dopt->binary_upgrade)
3293                         binfo[i].dobj.dump &= ~(DUMP_COMPONENT_DATA | DUMP_COMPONENT_ACL);
3294         }
3295
3296         /*
3297          * If we have any large objects, a "BLOBS" archive entry is needed. This
3298          * is just a placeholder for sorting; it carries no data now.
3299          */
3300         if (ntups > 0)
3301         {
3302                 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
3303                 bdata->objType = DO_BLOB_DATA;
3304                 bdata->catId = nilCatalogId;
3305                 AssignDumpId(bdata);
3306                 bdata->name = pg_strdup("BLOBS");
3307         }
3308
3309         PQclear(res);
3310         destroyPQExpBuffer(blobQry);
3311 }
3312
3313 /*
3314  * dumpBlob
3315  *
3316  * dump the definition (metadata) of the given large object
3317  */
3318 static void
3319 dumpBlob(Archive *fout, BlobInfo *binfo)
3320 {
3321         PQExpBuffer cquery = createPQExpBuffer();
3322         PQExpBuffer dquery = createPQExpBuffer();
3323
3324         appendPQExpBuffer(cquery,
3325                                           "SELECT pg_catalog.lo_create('%s');\n",
3326                                           binfo->dobj.name);
3327
3328         appendPQExpBuffer(dquery,
3329                                           "SELECT pg_catalog.lo_unlink('%s');\n",
3330                                           binfo->dobj.name);
3331
3332         if (binfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
3333                 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
3334                                          binfo->dobj.name,
3335                                          NULL, NULL,
3336                                          binfo->rolname, false,
3337                                          "BLOB", SECTION_PRE_DATA,
3338                                          cquery->data, dquery->data, NULL,
3339                                          NULL, 0,
3340                                          NULL, NULL);
3341
3342         /* Dump comment if any */
3343         if (binfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3344                 dumpComment(fout, "LARGE OBJECT", binfo->dobj.name,
3345                                         NULL, binfo->rolname,
3346                                         binfo->dobj.catId, 0, binfo->dobj.dumpId);
3347
3348         /* Dump security label if any */
3349         if (binfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3350                 dumpSecLabel(fout, "LARGE OBJECT", binfo->dobj.name,
3351                                          NULL, binfo->rolname,
3352                                          binfo->dobj.catId, 0, binfo->dobj.dumpId);
3353
3354         /* Dump ACL if any */
3355         if (binfo->blobacl && (binfo->dobj.dump & DUMP_COMPONENT_ACL))
3356                 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
3357                                 binfo->dobj.name, NULL,
3358                                 NULL, binfo->rolname, binfo->blobacl, binfo->rblobacl,
3359                                 binfo->initblobacl, binfo->initrblobacl);
3360
3361         destroyPQExpBuffer(cquery);
3362         destroyPQExpBuffer(dquery);
3363 }
3364
3365 /*
3366  * dumpBlobs:
3367  *      dump the data contents of all large objects
3368  */
3369 static int
3370 dumpBlobs(Archive *fout, void *arg)
3371 {
3372         const char *blobQry;
3373         const char *blobFetchQry;
3374         PGconn     *conn = GetConnection(fout);
3375         PGresult   *res;
3376         char            buf[LOBBUFSIZE];
3377         int                     ntups;
3378         int                     i;
3379         int                     cnt;
3380
3381         if (g_verbose)
3382                 write_msg(NULL, "saving large objects\n");
3383
3384         /*
3385          * Currently, we re-fetch all BLOB OIDs using a cursor.  Consider scanning
3386          * the already-in-memory dumpable objects instead...
3387          */
3388         if (fout->remoteVersion >= 90000)
3389                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
3390         else
3391                 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
3392
3393         ExecuteSqlStatement(fout, blobQry);
3394
3395         /* Command to fetch from cursor */
3396         blobFetchQry = "FETCH 1000 IN bloboid";
3397
3398         do
3399         {
3400                 /* Do a fetch */
3401                 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
3402
3403                 /* Process the tuples, if any */
3404                 ntups = PQntuples(res);
3405                 for (i = 0; i < ntups; i++)
3406                 {
3407                         Oid                     blobOid;
3408                         int                     loFd;
3409
3410                         blobOid = atooid(PQgetvalue(res, i, 0));
3411                         /* Open the BLOB */
3412                         loFd = lo_open(conn, blobOid, INV_READ);
3413                         if (loFd == -1)
3414                                 exit_horribly(NULL, "could not open large object %u: %s",
3415                                                           blobOid, PQerrorMessage(conn));
3416
3417                         StartBlob(fout, blobOid);
3418
3419                         /* Now read it in chunks, sending data to archive */
3420                         do
3421                         {
3422                                 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
3423                                 if (cnt < 0)
3424                                         exit_horribly(NULL, "error reading large object %u: %s",
3425                                                                   blobOid, PQerrorMessage(conn));
3426
3427                                 WriteData(fout, buf, cnt);
3428                         } while (cnt > 0);
3429
3430                         lo_close(conn, loFd);
3431
3432                         EndBlob(fout, blobOid);
3433                 }
3434
3435                 PQclear(res);
3436         } while (ntups > 0);
3437
3438         return 1;
3439 }
3440
3441 /*
3442  * getPolicies
3443  *        get information about policies on a dumpable table.
3444  */
3445 void
3446 getPolicies(Archive *fout, TableInfo tblinfo[], int numTables)
3447 {
3448         PQExpBuffer query;
3449         PGresult   *res;
3450         PolicyInfo *polinfo;
3451         int                     i_oid;
3452         int                     i_tableoid;
3453         int                     i_polname;
3454         int                     i_polcmd;
3455         int                     i_polpermissive;
3456         int                     i_polroles;
3457         int                     i_polqual;
3458         int                     i_polwithcheck;
3459         int                     i,
3460                                 j,
3461                                 ntups;
3462
3463         if (fout->remoteVersion < 90500)
3464                 return;
3465
3466         query = createPQExpBuffer();
3467
3468         for (i = 0; i < numTables; i++)
3469         {
3470                 TableInfo  *tbinfo = &tblinfo[i];
3471
3472                 /* Ignore row security on tables not to be dumped */
3473                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_POLICY))
3474                         continue;
3475
3476                 if (g_verbose)
3477                         write_msg(NULL, "reading row security enabled for table \"%s.%s\"\n",
3478                                           tbinfo->dobj.namespace->dobj.name,
3479                                           tbinfo->dobj.name);
3480
3481                 /*
3482                  * Get row security enabled information for the table. We represent
3483                  * RLS enabled on a table by creating PolicyInfo object with an empty
3484                  * policy.
3485                  */
3486                 if (tbinfo->rowsec)
3487                 {
3488                         /*
3489                          * Note: use tableoid 0 so that this object won't be mistaken for
3490                          * something that pg_depend entries apply to.
3491                          */
3492                         polinfo = pg_malloc(sizeof(PolicyInfo));
3493                         polinfo->dobj.objType = DO_POLICY;
3494                         polinfo->dobj.catId.tableoid = 0;
3495                         polinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
3496                         AssignDumpId(&polinfo->dobj);
3497                         polinfo->dobj.namespace = tbinfo->dobj.namespace;
3498                         polinfo->dobj.name = pg_strdup(tbinfo->dobj.name);
3499                         polinfo->poltable = tbinfo;
3500                         polinfo->polname = NULL;
3501                         polinfo->polcmd = '\0';
3502                         polinfo->polpermissive = 0;
3503                         polinfo->polroles = NULL;
3504                         polinfo->polqual = NULL;
3505                         polinfo->polwithcheck = NULL;
3506                 }
3507
3508                 if (g_verbose)
3509                         write_msg(NULL, "reading policies for table \"%s.%s\"\n",
3510                                           tbinfo->dobj.namespace->dobj.name,
3511                                           tbinfo->dobj.name);
3512
3513                 resetPQExpBuffer(query);
3514
3515                 /* Get the policies for the table. */
3516                 if (fout->remoteVersion >= 100000)
3517                         appendPQExpBuffer(query,
3518                                                           "SELECT oid, tableoid, pol.polname, pol.polcmd, pol.polpermissive, "
3519                                                           "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3520                                                           "   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, "
3521                                                           "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3522                                                           "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3523                                                           "FROM pg_catalog.pg_policy pol "
3524                                                           "WHERE polrelid = '%u'",
3525                                                           tbinfo->dobj.catId.oid);
3526                 else
3527                         appendPQExpBuffer(query,
3528                                                           "SELECT oid, tableoid, pol.polname, pol.polcmd, 't' as polpermissive, "
3529                                                           "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3530                                                           "   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, "
3531                                                           "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3532                                                           "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3533                                                           "FROM pg_catalog.pg_policy pol "
3534                                                           "WHERE polrelid = '%u'",
3535                                                           tbinfo->dobj.catId.oid);
3536                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3537
3538                 ntups = PQntuples(res);
3539
3540                 if (ntups == 0)
3541                 {
3542                         /*
3543                          * No explicit policies to handle (only the default-deny policy,
3544                          * which is handled as part of the table definition).  Clean up
3545                          * and return.
3546                          */
3547                         PQclear(res);
3548                         continue;
3549                 }
3550
3551                 i_oid = PQfnumber(res, "oid");
3552                 i_tableoid = PQfnumber(res, "tableoid");
3553                 i_polname = PQfnumber(res, "polname");
3554                 i_polcmd = PQfnumber(res, "polcmd");
3555                 i_polpermissive = PQfnumber(res, "polpermissive");
3556                 i_polroles = PQfnumber(res, "polroles");
3557                 i_polqual = PQfnumber(res, "polqual");
3558                 i_polwithcheck = PQfnumber(res, "polwithcheck");
3559
3560                 polinfo = pg_malloc(ntups * sizeof(PolicyInfo));
3561
3562                 for (j = 0; j < ntups; j++)
3563                 {
3564                         polinfo[j].dobj.objType = DO_POLICY;
3565                         polinfo[j].dobj.catId.tableoid =
3566                                 atooid(PQgetvalue(res, j, i_tableoid));
3567                         polinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3568                         AssignDumpId(&polinfo[j].dobj);
3569                         polinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3570                         polinfo[j].poltable = tbinfo;
3571                         polinfo[j].polname = pg_strdup(PQgetvalue(res, j, i_polname));
3572                         polinfo[j].dobj.name = pg_strdup(polinfo[j].polname);
3573
3574                         polinfo[j].polcmd = *(PQgetvalue(res, j, i_polcmd));
3575                         polinfo[j].polpermissive = *(PQgetvalue(res, j, i_polpermissive)) == 't';
3576
3577                         if (PQgetisnull(res, j, i_polroles))
3578                                 polinfo[j].polroles = NULL;
3579                         else
3580                                 polinfo[j].polroles = pg_strdup(PQgetvalue(res, j, i_polroles));
3581
3582                         if (PQgetisnull(res, j, i_polqual))
3583                                 polinfo[j].polqual = NULL;
3584                         else
3585                                 polinfo[j].polqual = pg_strdup(PQgetvalue(res, j, i_polqual));
3586
3587                         if (PQgetisnull(res, j, i_polwithcheck))
3588                                 polinfo[j].polwithcheck = NULL;
3589                         else
3590                                 polinfo[j].polwithcheck
3591                                         = pg_strdup(PQgetvalue(res, j, i_polwithcheck));
3592                 }
3593                 PQclear(res);
3594         }
3595         destroyPQExpBuffer(query);
3596 }
3597
3598 /*
3599  * dumpPolicy
3600  *        dump the definition of the given policy
3601  */
3602 static void
3603 dumpPolicy(Archive *fout, PolicyInfo *polinfo)
3604 {
3605         DumpOptions *dopt = fout->dopt;
3606         TableInfo  *tbinfo = polinfo->poltable;
3607         PQExpBuffer query;
3608         PQExpBuffer delqry;
3609         const char *cmd;
3610         char       *tag;
3611
3612         if (dopt->dataOnly)
3613                 return;
3614
3615         /*
3616          * If polname is NULL, then this record is just indicating that ROW LEVEL
3617          * SECURITY is enabled for the table. Dump as ALTER TABLE <table> ENABLE
3618          * ROW LEVEL SECURITY.
3619          */
3620         if (polinfo->polname == NULL)
3621         {
3622                 query = createPQExpBuffer();
3623
3624                 appendPQExpBuffer(query, "ALTER TABLE %s ENABLE ROW LEVEL SECURITY;",
3625                                                   fmtQualifiedDumpable(polinfo));
3626
3627                 if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3628                         ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3629                                                  polinfo->dobj.name,
3630                                                  polinfo->dobj.namespace->dobj.name,
3631                                                  NULL,
3632                                                  tbinfo->rolname, false,
3633                                                  "ROW SECURITY", SECTION_POST_DATA,
3634                                                  query->data, "", NULL,
3635                                                  NULL, 0,
3636                                                  NULL, NULL);
3637
3638                 destroyPQExpBuffer(query);
3639                 return;
3640         }
3641
3642         if (polinfo->polcmd == '*')
3643                 cmd = "";
3644         else if (polinfo->polcmd == 'r')
3645                 cmd = " FOR SELECT";
3646         else if (polinfo->polcmd == 'a')
3647                 cmd = " FOR INSERT";
3648         else if (polinfo->polcmd == 'w')
3649                 cmd = " FOR UPDATE";
3650         else if (polinfo->polcmd == 'd')
3651                 cmd = " FOR DELETE";
3652         else
3653         {
3654                 write_msg(NULL, "unexpected policy command type: %c\n",
3655                                   polinfo->polcmd);
3656                 exit_nicely(1);
3657         }
3658
3659         query = createPQExpBuffer();
3660         delqry = createPQExpBuffer();
3661
3662         appendPQExpBuffer(query, "CREATE POLICY %s", fmtId(polinfo->polname));
3663
3664         appendPQExpBuffer(query, " ON %s%s%s", fmtQualifiedDumpable(tbinfo),
3665                                           !polinfo->polpermissive ? " AS RESTRICTIVE" : "", cmd);
3666
3667         if (polinfo->polroles != NULL)
3668                 appendPQExpBuffer(query, " TO %s", polinfo->polroles);
3669
3670         if (polinfo->polqual != NULL)
3671                 appendPQExpBuffer(query, " USING (%s)", polinfo->polqual);
3672
3673         if (polinfo->polwithcheck != NULL)
3674                 appendPQExpBuffer(query, " WITH CHECK (%s)", polinfo->polwithcheck);
3675
3676         appendPQExpBuffer(query, ";\n");
3677
3678         appendPQExpBuffer(delqry, "DROP POLICY %s", fmtId(polinfo->polname));
3679         appendPQExpBuffer(delqry, " ON %s;\n", fmtQualifiedDumpable(tbinfo));
3680
3681         tag = psprintf("%s %s", tbinfo->dobj.name, polinfo->dobj.name);
3682
3683         if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3684                 ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3685                                          tag,
3686                                          polinfo->dobj.namespace->dobj.name,
3687                                          NULL,
3688                                          tbinfo->rolname, false,
3689                                          "POLICY", SECTION_POST_DATA,
3690                                          query->data, delqry->data, NULL,
3691                                          NULL, 0,
3692                                          NULL, NULL);
3693
3694         free(tag);
3695         destroyPQExpBuffer(query);
3696         destroyPQExpBuffer(delqry);
3697 }
3698
3699 /*
3700  * getPublications
3701  *        get information about publications
3702  */
3703 void
3704 getPublications(Archive *fout)
3705 {
3706         DumpOptions *dopt = fout->dopt;
3707         PQExpBuffer query;
3708         PGresult   *res;
3709         PublicationInfo *pubinfo;
3710         int                     i_tableoid;
3711         int                     i_oid;
3712         int                     i_pubname;
3713         int                     i_rolname;
3714         int                     i_puballtables;
3715         int                     i_pubinsert;
3716         int                     i_pubupdate;
3717         int                     i_pubdelete;
3718         int                     i_pubtruncate;
3719         int                     i,
3720                                 ntups;
3721
3722         if (dopt->no_publications || fout->remoteVersion < 100000)
3723                 return;
3724
3725         query = createPQExpBuffer();
3726
3727         resetPQExpBuffer(query);
3728
3729         /* Get the publications. */
3730         if (fout->remoteVersion >= 110000)
3731                 appendPQExpBuffer(query,
3732                                                   "SELECT p.tableoid, p.oid, p.pubname, "
3733                                                   "(%s p.pubowner) AS rolname, "
3734                                                   "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete, p.pubtruncate "
3735                                                   "FROM pg_publication p",
3736                                                   username_subquery);
3737         else
3738                 appendPQExpBuffer(query,
3739                                                   "SELECT p.tableoid, p.oid, p.pubname, "
3740                                                   "(%s p.pubowner) AS rolname, "
3741                                                   "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete, false AS pubtruncate "
3742                                                   "FROM pg_publication p",
3743                                                   username_subquery);
3744
3745         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3746
3747         ntups = PQntuples(res);
3748
3749         i_tableoid = PQfnumber(res, "tableoid");
3750         i_oid = PQfnumber(res, "oid");
3751         i_pubname = PQfnumber(res, "pubname");
3752         i_rolname = PQfnumber(res, "rolname");
3753         i_puballtables = PQfnumber(res, "puballtables");
3754         i_pubinsert = PQfnumber(res, "pubinsert");
3755         i_pubupdate = PQfnumber(res, "pubupdate");
3756         i_pubdelete = PQfnumber(res, "pubdelete");
3757         i_pubtruncate = PQfnumber(res, "pubtruncate");
3758
3759         pubinfo = pg_malloc(ntups * sizeof(PublicationInfo));
3760
3761         for (i = 0; i < ntups; i++)
3762         {
3763                 pubinfo[i].dobj.objType = DO_PUBLICATION;
3764                 pubinfo[i].dobj.catId.tableoid =
3765                         atooid(PQgetvalue(res, i, i_tableoid));
3766                 pubinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3767                 AssignDumpId(&pubinfo[i].dobj);
3768                 pubinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_pubname));
3769                 pubinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3770                 pubinfo[i].puballtables =
3771                         (strcmp(PQgetvalue(res, i, i_puballtables), "t") == 0);
3772                 pubinfo[i].pubinsert =
3773                         (strcmp(PQgetvalue(res, i, i_pubinsert), "t") == 0);
3774                 pubinfo[i].pubupdate =
3775                         (strcmp(PQgetvalue(res, i, i_pubupdate), "t") == 0);
3776                 pubinfo[i].pubdelete =
3777                         (strcmp(PQgetvalue(res, i, i_pubdelete), "t") == 0);
3778                 pubinfo[i].pubtruncate =
3779                         (strcmp(PQgetvalue(res, i, i_pubtruncate), "t") == 0);
3780
3781                 if (strlen(pubinfo[i].rolname) == 0)
3782                         write_msg(NULL, "WARNING: owner of publication \"%s\" appears to be invalid\n",
3783                                           pubinfo[i].dobj.name);
3784
3785                 /* Decide whether we want to dump it */
3786                 selectDumpableObject(&(pubinfo[i].dobj), fout);
3787         }
3788         PQclear(res);
3789
3790         destroyPQExpBuffer(query);
3791 }
3792
3793 /*
3794  * dumpPublication
3795  *        dump the definition of the given publication
3796  */
3797 static void
3798 dumpPublication(Archive *fout, PublicationInfo *pubinfo)
3799 {
3800         PQExpBuffer delq;
3801         PQExpBuffer query;
3802         char       *qpubname;
3803         bool            first = true;
3804
3805         if (!(pubinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3806                 return;
3807
3808         delq = createPQExpBuffer();
3809         query = createPQExpBuffer();
3810
3811         qpubname = pg_strdup(fmtId(pubinfo->dobj.name));
3812
3813         appendPQExpBuffer(delq, "DROP PUBLICATION %s;\n",
3814                                           qpubname);
3815
3816         appendPQExpBuffer(query, "CREATE PUBLICATION %s",
3817                                           qpubname);
3818
3819         if (pubinfo->puballtables)
3820                 appendPQExpBufferStr(query, " FOR ALL TABLES");
3821
3822         appendPQExpBufferStr(query, " WITH (publish = '");
3823         if (pubinfo->pubinsert)
3824         {
3825                 appendPQExpBufferStr(query, "insert");
3826                 first = false;
3827         }
3828
3829         if (pubinfo->pubupdate)
3830         {
3831                 if (!first)
3832                         appendPQExpBufferStr(query, ", ");
3833
3834                 appendPQExpBufferStr(query, "update");
3835                 first = false;
3836         }
3837
3838         if (pubinfo->pubdelete)
3839         {
3840                 if (!first)
3841                         appendPQExpBufferStr(query, ", ");
3842
3843                 appendPQExpBufferStr(query, "delete");
3844                 first = false;
3845         }
3846
3847         if (pubinfo->pubtruncate)
3848         {
3849                 if (!first)
3850                         appendPQExpBufferStr(query, ", ");
3851
3852                 appendPQExpBufferStr(query, "truncate");
3853                 first = false;
3854         }
3855
3856         appendPQExpBufferStr(query, "');\n");
3857
3858         ArchiveEntry(fout, pubinfo->dobj.catId, pubinfo->dobj.dumpId,
3859                                  pubinfo->dobj.name,
3860                                  NULL,
3861                                  NULL,
3862                                  pubinfo->rolname, false,
3863                                  "PUBLICATION", SECTION_POST_DATA,
3864                                  query->data, delq->data, NULL,
3865                                  NULL, 0,
3866                                  NULL, NULL);
3867
3868         if (pubinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3869                 dumpComment(fout, "PUBLICATION", qpubname,
3870                                         NULL, pubinfo->rolname,
3871                                         pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3872
3873         if (pubinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3874                 dumpSecLabel(fout, "PUBLICATION", qpubname,
3875                                          NULL, pubinfo->rolname,
3876                                          pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3877
3878         destroyPQExpBuffer(delq);
3879         destroyPQExpBuffer(query);
3880         free(qpubname);
3881 }
3882
3883 /*
3884  * getPublicationTables
3885  *        get information about publication membership for dumpable tables.
3886  */
3887 void
3888 getPublicationTables(Archive *fout, TableInfo tblinfo[], int numTables)
3889 {
3890         PQExpBuffer query;
3891         PGresult   *res;
3892         PublicationRelInfo *pubrinfo;
3893         int                     i_tableoid;
3894         int                     i_oid;
3895         int                     i_pubname;
3896         int                     i,
3897                                 j,
3898                                 ntups;
3899
3900         if (fout->remoteVersion < 100000)
3901                 return;
3902
3903         query = createPQExpBuffer();
3904
3905         for (i = 0; i < numTables; i++)
3906         {
3907                 TableInfo  *tbinfo = &tblinfo[i];
3908
3909                 /* Only plain tables can be aded to publications. */
3910                 if (tbinfo->relkind != RELKIND_RELATION)
3911                         continue;
3912
3913                 /*
3914                  * Ignore publication membership of tables whose definitions are not
3915                  * to be dumped.
3916                  */
3917                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3918                         continue;
3919
3920                 if (g_verbose)
3921                         write_msg(NULL, "reading publication membership for table \"%s.%s\"\n",
3922                                           tbinfo->dobj.namespace->dobj.name,
3923                                           tbinfo->dobj.name);
3924
3925                 resetPQExpBuffer(query);
3926
3927                 /* Get the publication membership for the table. */
3928                 appendPQExpBuffer(query,
3929                                                   "SELECT pr.tableoid, pr.oid, p.pubname "
3930                                                   "FROM pg_publication_rel pr, pg_publication p "
3931                                                   "WHERE pr.prrelid = '%u'"
3932                                                   "  AND p.oid = pr.prpubid",
3933                                                   tbinfo->dobj.catId.oid);
3934                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3935
3936                 ntups = PQntuples(res);
3937
3938                 if (ntups == 0)
3939                 {
3940                         /*
3941                          * Table is not member of any publications. Clean up and return.
3942                          */
3943                         PQclear(res);
3944                         continue;
3945                 }
3946
3947                 i_tableoid = PQfnumber(res, "tableoid");
3948                 i_oid = PQfnumber(res, "oid");
3949                 i_pubname = PQfnumber(res, "pubname");
3950
3951                 pubrinfo = pg_malloc(ntups * sizeof(PublicationRelInfo));
3952
3953                 for (j = 0; j < ntups; j++)
3954                 {
3955                         pubrinfo[j].dobj.objType = DO_PUBLICATION_REL;
3956                         pubrinfo[j].dobj.catId.tableoid =
3957                                 atooid(PQgetvalue(res, j, i_tableoid));
3958                         pubrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3959                         AssignDumpId(&pubrinfo[j].dobj);
3960                         pubrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3961                         pubrinfo[j].dobj.name = tbinfo->dobj.name;
3962                         pubrinfo[j].pubname = pg_strdup(PQgetvalue(res, j, i_pubname));
3963                         pubrinfo[j].pubtable = tbinfo;
3964
3965                         /* Decide whether we want to dump it */
3966                         selectDumpablePublicationTable(&(pubrinfo[j].dobj), fout);
3967                 }
3968                 PQclear(res);
3969         }
3970         destroyPQExpBuffer(query);
3971 }
3972
3973 /*
3974  * dumpPublicationTable
3975  *        dump the definition of the given publication table mapping
3976  */
3977 static void
3978 dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo)
3979 {
3980         TableInfo  *tbinfo = pubrinfo->pubtable;
3981         PQExpBuffer query;
3982         char       *tag;
3983
3984         if (!(pubrinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3985                 return;
3986
3987         tag = psprintf("%s %s", pubrinfo->pubname, tbinfo->dobj.name);
3988
3989         query = createPQExpBuffer();
3990
3991         appendPQExpBuffer(query, "ALTER PUBLICATION %s ADD TABLE ONLY",
3992                                           fmtId(pubrinfo->pubname));
3993         appendPQExpBuffer(query, " %s;\n",
3994                                           fmtQualifiedDumpable(tbinfo));
3995
3996         /*
3997          * There is no point in creating drop query as drop query as the drop is
3998          * done by table drop.
3999          */
4000         ArchiveEntry(fout, pubrinfo->dobj.catId, pubrinfo->dobj.dumpId,
4001                                  tag,
4002                                  tbinfo->dobj.namespace->dobj.name,
4003                                  NULL,
4004                                  "", false,
4005                                  "PUBLICATION TABLE", SECTION_POST_DATA,
4006                                  query->data, "", NULL,
4007                                  NULL, 0,
4008                                  NULL, NULL);
4009
4010         free(tag);
4011         destroyPQExpBuffer(query);
4012 }
4013
4014 /*
4015  * Is the currently connected user a superuser?
4016  */
4017 static bool
4018 is_superuser(Archive *fout)
4019 {
4020         ArchiveHandle *AH = (ArchiveHandle *) fout;
4021         const char *val;
4022
4023         val = PQparameterStatus(AH->connection, "is_superuser");
4024
4025         if (val && strcmp(val, "on") == 0)
4026                 return true;
4027
4028         return false;
4029 }
4030
4031 /*
4032  * getSubscriptions
4033  *        get information about subscriptions
4034  */
4035 void
4036 getSubscriptions(Archive *fout)
4037 {
4038         DumpOptions *dopt = fout->dopt;
4039         PQExpBuffer query;
4040         PGresult   *res;
4041         SubscriptionInfo *subinfo;
4042         int                     i_tableoid;
4043         int                     i_oid;
4044         int                     i_subname;
4045         int                     i_rolname;
4046         int                     i_subconninfo;
4047         int                     i_subslotname;
4048         int                     i_subsynccommit;
4049         int                     i_subpublications;
4050         int                     i,
4051                                 ntups;
4052
4053         if (dopt->no_subscriptions || fout->remoteVersion < 100000)
4054                 return;
4055
4056         if (!is_superuser(fout))
4057         {
4058                 int                     n;
4059
4060                 res = ExecuteSqlQuery(fout,
4061                                                           "SELECT count(*) FROM pg_subscription "
4062                                                           "WHERE subdbid = (SELECT oid FROM pg_database"
4063                                                           "                 WHERE datname = current_database())",
4064                                                           PGRES_TUPLES_OK);
4065                 n = atoi(PQgetvalue(res, 0, 0));
4066                 if (n > 0)
4067                         write_msg(NULL, "WARNING: subscriptions not dumped because current user is not a superuser\n");
4068                 PQclear(res);
4069                 return;
4070         }
4071
4072         query = createPQExpBuffer();
4073
4074         resetPQExpBuffer(query);
4075
4076         /* Get the subscriptions in current database. */
4077         appendPQExpBuffer(query,
4078                                           "SELECT s.tableoid, s.oid, s.subname,"
4079                                           "(%s s.subowner) AS rolname, "
4080                                           " s.subconninfo, s.subslotname, s.subsynccommit, "
4081                                           " s.subpublications "
4082                                           "FROM pg_subscription s "
4083                                           "WHERE s.subdbid = (SELECT oid FROM pg_database"
4084                                           "                   WHERE datname = current_database())",
4085                                           username_subquery);
4086         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4087
4088         ntups = PQntuples(res);
4089
4090         i_tableoid = PQfnumber(res, "tableoid");
4091         i_oid = PQfnumber(res, "oid");
4092         i_subname = PQfnumber(res, "subname");
4093         i_rolname = PQfnumber(res, "rolname");
4094         i_subconninfo = PQfnumber(res, "subconninfo");
4095         i_subslotname = PQfnumber(res, "subslotname");
4096         i_subsynccommit = PQfnumber(res, "subsynccommit");
4097         i_subpublications = PQfnumber(res, "subpublications");
4098
4099         subinfo = pg_malloc(ntups * sizeof(SubscriptionInfo));
4100
4101         for (i = 0; i < ntups; i++)
4102         {
4103                 subinfo[i].dobj.objType = DO_SUBSCRIPTION;
4104                 subinfo[i].dobj.catId.tableoid =
4105                         atooid(PQgetvalue(res, i, i_tableoid));
4106                 subinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4107                 AssignDumpId(&subinfo[i].dobj);
4108                 subinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_subname));
4109                 subinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4110                 subinfo[i].subconninfo = pg_strdup(PQgetvalue(res, i, i_subconninfo));
4111                 if (PQgetisnull(res, i, i_subslotname))
4112                         subinfo[i].subslotname = NULL;
4113                 else
4114                         subinfo[i].subslotname = pg_strdup(PQgetvalue(res, i, i_subslotname));
4115                 subinfo[i].subsynccommit =
4116                         pg_strdup(PQgetvalue(res, i, i_subsynccommit));
4117                 subinfo[i].subpublications =
4118                         pg_strdup(PQgetvalue(res, i, i_subpublications));
4119
4120                 if (strlen(subinfo[i].rolname) == 0)
4121                         write_msg(NULL, "WARNING: owner of subscription \"%s\" appears to be invalid\n",
4122                                           subinfo[i].dobj.name);
4123
4124                 /* Decide whether we want to dump it */
4125                 selectDumpableObject(&(subinfo[i].dobj), fout);
4126         }
4127         PQclear(res);
4128
4129         destroyPQExpBuffer(query);
4130 }
4131
4132 /*
4133  * dumpSubscription
4134  *        dump the definition of the given subscription
4135  */
4136 static void
4137 dumpSubscription(Archive *fout, SubscriptionInfo *subinfo)
4138 {
4139         PQExpBuffer delq;
4140         PQExpBuffer query;
4141         PQExpBuffer publications;
4142         char       *qsubname;
4143         char      **pubnames = NULL;
4144         int                     npubnames = 0;
4145         int                     i;
4146
4147         if (!(subinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
4148                 return;
4149
4150         delq = createPQExpBuffer();
4151         query = createPQExpBuffer();
4152
4153         qsubname = pg_strdup(fmtId(subinfo->dobj.name));
4154
4155         appendPQExpBuffer(delq, "DROP SUBSCRIPTION %s;\n",
4156                                           qsubname);
4157
4158         appendPQExpBuffer(query, "CREATE SUBSCRIPTION %s CONNECTION ",
4159                                           qsubname);
4160         appendStringLiteralAH(query, subinfo->subconninfo, fout);
4161
4162         /* Build list of quoted publications and append them to query. */
4163         if (!parsePGArray(subinfo->subpublications, &pubnames, &npubnames))
4164         {
4165                 write_msg(NULL,
4166                                   "WARNING: could not parse subpublications array\n");
4167                 if (pubnames)
4168                         free(pubnames);
4169                 pubnames = NULL;
4170                 npubnames = 0;
4171         }
4172
4173         publications = createPQExpBuffer();
4174         for (i = 0; i < npubnames; i++)
4175         {
4176                 if (i > 0)
4177                         appendPQExpBufferStr(publications, ", ");
4178
4179                 appendPQExpBufferStr(publications, fmtId(pubnames[i]));
4180         }
4181
4182         appendPQExpBuffer(query, " PUBLICATION %s WITH (connect = false, slot_name = ", publications->data);
4183         if (subinfo->subslotname)
4184                 appendStringLiteralAH(query, subinfo->subslotname, fout);
4185         else
4186                 appendPQExpBufferStr(query, "NONE");
4187
4188         if (strcmp(subinfo->subsynccommit, "off") != 0)
4189                 appendPQExpBuffer(query, ", synchronous_commit = %s", fmtId(subinfo->subsynccommit));
4190
4191         appendPQExpBufferStr(query, ");\n");
4192
4193         ArchiveEntry(fout, subinfo->dobj.catId, subinfo->dobj.dumpId,
4194                                  subinfo->dobj.name,
4195                                  NULL,
4196                                  NULL,
4197                                  subinfo->rolname, false,
4198                                  "SUBSCRIPTION", SECTION_POST_DATA,
4199                                  query->data, delq->data, NULL,
4200                                  NULL, 0,
4201                                  NULL, NULL);
4202
4203         if (subinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
4204                 dumpComment(fout, "SUBSCRIPTION", qsubname,
4205                                         NULL, subinfo->rolname,
4206                                         subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
4207
4208         if (subinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
4209                 dumpSecLabel(fout, "SUBSCRIPTION", qsubname,
4210                                          NULL, subinfo->rolname,
4211                                          subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
4212
4213         destroyPQExpBuffer(publications);
4214         if (pubnames)
4215                 free(pubnames);
4216
4217         destroyPQExpBuffer(delq);
4218         destroyPQExpBuffer(query);
4219         free(qsubname);
4220 }
4221
4222 static void
4223 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
4224                                                                                  PQExpBuffer upgrade_buffer,
4225                                                                                  Oid pg_type_oid,
4226                                                                                  bool force_array_type)
4227 {
4228         PQExpBuffer upgrade_query = createPQExpBuffer();
4229         PGresult   *res;
4230         Oid                     pg_type_array_oid;
4231
4232         appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
4233         appendPQExpBuffer(upgrade_buffer,
4234                                           "SELECT pg_catalog.binary_upgrade_set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4235                                           pg_type_oid);
4236
4237         /* we only support old >= 8.3 for binary upgrades */
4238         appendPQExpBuffer(upgrade_query,
4239                                           "SELECT typarray "
4240                                           "FROM pg_catalog.pg_type "
4241                                           "WHERE oid = '%u'::pg_catalog.oid;",
4242                                           pg_type_oid);
4243
4244         res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4245
4246         pg_type_array_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typarray")));
4247
4248         PQclear(res);
4249
4250         if (!OidIsValid(pg_type_array_oid) && force_array_type)
4251         {
4252                 /*
4253                  * If the old version didn't assign an array type, but the new version
4254                  * does, we must select an unused type OID to assign.  This currently
4255                  * only happens for domains, when upgrading pre-v11 to v11 and up.
4256                  *
4257                  * Note: local state here is kind of ugly, but we must have some,
4258                  * since we mustn't choose the same unused OID more than once.
4259                  */
4260                 static Oid      next_possible_free_oid = FirstNormalObjectId;
4261                 bool            is_dup;
4262
4263                 do
4264                 {
4265                         ++next_possible_free_oid;
4266                         printfPQExpBuffer(upgrade_query,
4267                                                           "SELECT EXISTS(SELECT 1 "
4268                                                           "FROM pg_catalog.pg_type "
4269                                                           "WHERE oid = '%u'::pg_catalog.oid);",
4270                                                           next_possible_free_oid);
4271                         res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4272                         is_dup = (PQgetvalue(res, 0, 0)[0] == 't');
4273                         PQclear(res);
4274                 } while (is_dup);
4275
4276                 pg_type_array_oid = next_possible_free_oid;
4277         }
4278
4279         if (OidIsValid(pg_type_array_oid))
4280         {
4281                 appendPQExpBufferStr(upgrade_buffer,
4282                                                          "\n-- For binary upgrade, must preserve pg_type array oid\n");
4283                 appendPQExpBuffer(upgrade_buffer,
4284                                                   "SELECT pg_catalog.binary_upgrade_set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4285                                                   pg_type_array_oid);
4286         }
4287
4288         destroyPQExpBuffer(upgrade_query);
4289 }
4290
4291 static bool
4292 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
4293                                                                                 PQExpBuffer upgrade_buffer,
4294                                                                                 Oid pg_rel_oid)
4295 {
4296         PQExpBuffer upgrade_query = createPQExpBuffer();
4297         PGresult   *upgrade_res;
4298         Oid                     pg_type_oid;
4299         bool            toast_set = false;
4300
4301         /* we only support old >= 8.3 for binary upgrades */
4302         appendPQExpBuffer(upgrade_query,
4303                                           "SELECT c.reltype AS crel, t.reltype AS trel "
4304                                           "FROM pg_catalog.pg_class c "
4305                                           "LEFT JOIN pg_catalog.pg_class t ON "
4306                                           "  (c.reltoastrelid = t.oid) "
4307                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
4308                                           pg_rel_oid);
4309
4310         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4311
4312         pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
4313
4314         binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
4315                                                                                          pg_type_oid, false);
4316
4317         if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
4318         {
4319                 /* Toast tables do not have pg_type array rows */
4320                 Oid                     pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
4321                                                                                                                   PQfnumber(upgrade_res, "trel")));
4322
4323                 appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
4324                 appendPQExpBuffer(upgrade_buffer,
4325                                                   "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4326                                                   pg_type_toast_oid);
4327
4328                 toast_set = true;
4329         }
4330
4331         PQclear(upgrade_res);
4332         destroyPQExpBuffer(upgrade_query);
4333
4334         return toast_set;
4335 }
4336
4337 static void
4338 binary_upgrade_set_pg_class_oids(Archive *fout,
4339                                                                  PQExpBuffer upgrade_buffer, Oid pg_class_oid,
4340                                                                  bool is_index)
4341 {
4342         PQExpBuffer upgrade_query = createPQExpBuffer();
4343         PGresult   *upgrade_res;
4344         Oid                     pg_class_reltoastrelid;
4345         Oid                     pg_index_indexrelid;
4346
4347         appendPQExpBuffer(upgrade_query,
4348                                           "SELECT c.reltoastrelid, i.indexrelid "
4349                                           "FROM pg_catalog.pg_class c LEFT JOIN "
4350                                           "pg_catalog.pg_index i ON (c.reltoastrelid = i.indrelid AND i.indisvalid) "
4351                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
4352                                           pg_class_oid);
4353
4354         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4355
4356         pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
4357         pg_index_indexrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "indexrelid")));
4358
4359         appendPQExpBufferStr(upgrade_buffer,
4360                                                  "\n-- For binary upgrade, must preserve pg_class oids\n");
4361
4362         if (!is_index)
4363         {
4364                 appendPQExpBuffer(upgrade_buffer,
4365                                                   "SELECT pg_catalog.binary_upgrade_set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
4366                                                   pg_class_oid);
4367                 /* only tables have toast tables, not indexes */
4368                 if (OidIsValid(pg_class_reltoastrelid))
4369                 {
4370                         /*
4371                          * One complexity is that the table definition might not require
4372                          * the creation of a TOAST table, and the TOAST table might have
4373                          * been created long after table creation, when the table was
4374                          * loaded with wide data.  By setting the TOAST oid we force
4375                          * creation of the TOAST heap and TOAST index by the backend so we
4376                          * can cleanly copy the files during binary upgrade.
4377                          */
4378
4379                         appendPQExpBuffer(upgrade_buffer,
4380                                                           "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
4381                                                           pg_class_reltoastrelid);
4382
4383                         /* every toast table has an index */
4384                         appendPQExpBuffer(upgrade_buffer,
4385                                                           "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4386                                                           pg_index_indexrelid);
4387                 }
4388         }
4389         else
4390                 appendPQExpBuffer(upgrade_buffer,
4391                                                   "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4392                                                   pg_class_oid);
4393
4394         appendPQExpBufferChar(upgrade_buffer, '\n');
4395
4396         PQclear(upgrade_res);
4397         destroyPQExpBuffer(upgrade_query);
4398 }
4399
4400 /*
4401  * If the DumpableObject is a member of an extension, add a suitable
4402  * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
4403  *
4404  * For somewhat historical reasons, objname should already be quoted,
4405  * but not objnamespace (if any).
4406  */
4407 static void
4408 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
4409                                                                 DumpableObject *dobj,
4410                                                                 const char *objtype,
4411                                                                 const char *objname,
4412                                                                 const char *objnamespace)
4413 {
4414         DumpableObject *extobj = NULL;
4415         int                     i;
4416
4417         if (!dobj->ext_member)
4418                 return;
4419
4420         /*
4421          * Find the parent extension.  We could avoid this search if we wanted to
4422          * add a link field to DumpableObject, but the space costs of that would
4423          * be considerable.  We assume that member objects could only have a
4424          * direct dependency on their own extension, not any others.
4425          */
4426         for (i = 0; i < dobj->nDeps; i++)
4427         {
4428                 extobj = findObjectByDumpId(dobj->dependencies[i]);
4429                 if (extobj && extobj->objType == DO_EXTENSION)
4430                         break;
4431                 extobj = NULL;
4432         }
4433         if (extobj == NULL)
4434                 exit_horribly(NULL, "could not find parent extension for %s %s\n",
4435                                           objtype, objname);
4436
4437         appendPQExpBufferStr(upgrade_buffer,
4438                                                  "\n-- For binary upgrade, handle extension membership the hard way\n");
4439         appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s ",
4440                                           fmtId(extobj->name),
4441                                           objtype);
4442         if (objnamespace && *objnamespace)
4443                 appendPQExpBuffer(upgrade_buffer, "%s.", fmtId(objnamespace));
4444         appendPQExpBuffer(upgrade_buffer, "%s;\n", objname);
4445 }
4446
4447 /*
4448  * getNamespaces:
4449  *        read all namespaces in the system catalogs and return them in the
4450  * NamespaceInfo* structure
4451  *
4452  *      numNamespaces is set to the number of namespaces read in
4453  */
4454 NamespaceInfo *
4455 getNamespaces(Archive *fout, int *numNamespaces)
4456 {
4457         DumpOptions *dopt = fout->dopt;
4458         PGresult   *res;
4459         int                     ntups;
4460         int                     i;
4461         PQExpBuffer query;
4462         NamespaceInfo *nsinfo;
4463         int                     i_tableoid;
4464         int                     i_oid;
4465         int                     i_nspname;
4466         int                     i_rolname;
4467         int                     i_nspacl;
4468         int                     i_rnspacl;
4469         int                     i_initnspacl;
4470         int                     i_initrnspacl;
4471
4472         query = createPQExpBuffer();
4473
4474         /*
4475          * we fetch all namespaces including system ones, so that every object we
4476          * read in can be linked to a containing namespace.
4477          */
4478         if (fout->remoteVersion >= 90600)
4479         {
4480                 PQExpBuffer acl_subquery = createPQExpBuffer();
4481                 PQExpBuffer racl_subquery = createPQExpBuffer();
4482                 PQExpBuffer init_acl_subquery = createPQExpBuffer();
4483                 PQExpBuffer init_racl_subquery = createPQExpBuffer();
4484
4485                 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
4486                                                 init_racl_subquery, "n.nspacl", "n.nspowner", "'n'",
4487                                                 dopt->binary_upgrade);
4488
4489                 appendPQExpBuffer(query, "SELECT n.tableoid, n.oid, n.nspname, "
4490                                                   "(%s nspowner) AS rolname, "
4491                                                   "%s as nspacl, "
4492                                                   "%s as rnspacl, "
4493                                                   "%s as initnspacl, "
4494                                                   "%s as initrnspacl "
4495                                                   "FROM pg_namespace n "
4496                                                   "LEFT JOIN pg_init_privs pip "
4497                                                   "ON (n.oid = pip.objoid "
4498                                                   "AND pip.classoid = 'pg_namespace'::regclass "
4499                                                   "AND pip.objsubid = 0",
4500                                                   username_subquery,
4501                                                   acl_subquery->data,
4502                                                   racl_subquery->data,
4503                                                   init_acl_subquery->data,
4504                                                   init_racl_subquery->data);
4505
4506                 appendPQExpBuffer(query, ") ");
4507
4508                 destroyPQExpBuffer(acl_subquery);
4509                 destroyPQExpBuffer(racl_subquery);
4510                 destroyPQExpBuffer(init_acl_subquery);
4511                 destroyPQExpBuffer(init_racl_subquery);
4512         }
4513         else
4514                 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
4515                                                   "(%s nspowner) AS rolname, "
4516                                                   "nspacl, NULL as rnspacl, "
4517                                                   "NULL AS initnspacl, NULL as initrnspacl "
4518                                                   "FROM pg_namespace",
4519                                                   username_subquery);
4520
4521         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4522
4523         ntups = PQntuples(res);
4524
4525         nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
4526
4527         i_tableoid = PQfnumber(res, "tableoid");
4528         i_oid = PQfnumber(res, "oid");
4529         i_nspname = PQfnumber(res, "nspname");
4530         i_rolname = PQfnumber(res, "rolname");
4531         i_nspacl = PQfnumber(res, "nspacl");
4532         i_rnspacl = PQfnumber(res, "rnspacl");
4533         i_initnspacl = PQfnumber(res, "initnspacl");
4534         i_initrnspacl = PQfnumber(res, "initrnspacl");
4535
4536         for (i = 0; i < ntups; i++)
4537         {
4538                 nsinfo[i].dobj.objType = DO_NAMESPACE;
4539                 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4540                 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4541                 AssignDumpId(&nsinfo[i].dobj);
4542                 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
4543                 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4544                 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
4545                 nsinfo[i].rnspacl = pg_strdup(PQgetvalue(res, i, i_rnspacl));
4546                 nsinfo[i].initnspacl = pg_strdup(PQgetvalue(res, i, i_initnspacl));
4547                 nsinfo[i].initrnspacl = pg_strdup(PQgetvalue(res, i, i_initrnspacl));
4548
4549                 /* Decide whether to dump this namespace */
4550                 selectDumpableNamespace(&nsinfo[i], fout);
4551
4552                 /*
4553                  * Do not try to dump ACL if the ACL is empty or the default.
4554                  *
4555                  * This is useful because, for some schemas/objects, the only
4556                  * component we are going to try and dump is the ACL and if we can
4557                  * remove that then 'dump' goes to zero/false and we don't consider
4558                  * this object for dumping at all later on.
4559                  */
4560                 if (PQgetisnull(res, i, i_nspacl) && PQgetisnull(res, i, i_rnspacl) &&
4561                         PQgetisnull(res, i, i_initnspacl) &&
4562                         PQgetisnull(res, i, i_initrnspacl))
4563                         nsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4564
4565                 if (strlen(nsinfo[i].rolname) == 0)
4566                         write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
4567                                           nsinfo[i].dobj.name);
4568         }
4569
4570         PQclear(res);
4571         destroyPQExpBuffer(query);
4572
4573         *numNamespaces = ntups;
4574
4575         return nsinfo;
4576 }
4577
4578 /*
4579  * findNamespace:
4580  *              given a namespace OID, look up the info read by getNamespaces
4581  */
4582 static NamespaceInfo *
4583 findNamespace(Archive *fout, Oid nsoid)
4584 {
4585         NamespaceInfo *nsinfo;
4586
4587         nsinfo = findNamespaceByOid(nsoid);
4588         if (nsinfo == NULL)
4589                 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
4590         return nsinfo;
4591 }
4592
4593 /*
4594  * getExtensions:
4595  *        read all extensions in the system catalogs and return them in the
4596  * ExtensionInfo* structure
4597  *
4598  *      numExtensions is set to the number of extensions read in
4599  */
4600 ExtensionInfo *
4601 getExtensions(Archive *fout, int *numExtensions)
4602 {
4603         DumpOptions *dopt = fout->dopt;
4604         PGresult   *res;
4605         int                     ntups;
4606         int                     i;
4607         PQExpBuffer query;
4608         ExtensionInfo *extinfo;
4609         int                     i_tableoid;
4610         int                     i_oid;
4611         int                     i_extname;
4612         int                     i_nspname;
4613         int                     i_extrelocatable;
4614         int                     i_extversion;
4615         int                     i_extconfig;
4616         int                     i_extcondition;
4617
4618         /*
4619          * Before 9.1, there are no extensions.
4620          */
4621         if (fout->remoteVersion < 90100)
4622         {
4623                 *numExtensions = 0;
4624                 return NULL;
4625         }
4626
4627         query = createPQExpBuffer();
4628
4629         appendPQExpBufferStr(query, "SELECT x.tableoid, x.oid, "
4630                                                  "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
4631                                                  "FROM pg_extension x "
4632                                                  "JOIN pg_namespace n ON n.oid = x.extnamespace");
4633
4634         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4635
4636         ntups = PQntuples(res);
4637
4638         extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
4639
4640         i_tableoid = PQfnumber(res, "tableoid");
4641         i_oid = PQfnumber(res, "oid");
4642         i_extname = PQfnumber(res, "extname");
4643         i_nspname = PQfnumber(res, "nspname");
4644         i_extrelocatable = PQfnumber(res, "extrelocatable");
4645         i_extversion = PQfnumber(res, "extversion");
4646         i_extconfig = PQfnumber(res, "extconfig");
4647         i_extcondition = PQfnumber(res, "extcondition");
4648
4649         for (i = 0; i < ntups; i++)
4650         {
4651                 extinfo[i].dobj.objType = DO_EXTENSION;
4652                 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4653                 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4654                 AssignDumpId(&extinfo[i].dobj);
4655                 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
4656                 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
4657                 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
4658                 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
4659                 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
4660                 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
4661
4662                 /* Decide whether we want to dump it */
4663                 selectDumpableExtension(&(extinfo[i]), dopt);
4664         }
4665
4666         PQclear(res);
4667         destroyPQExpBuffer(query);
4668
4669         *numExtensions = ntups;
4670
4671         return extinfo;
4672 }
4673
4674 /*
4675  * getTypes:
4676  *        read all types in the system catalogs and return them in the
4677  * TypeInfo* structure
4678  *
4679  *      numTypes is set to the number of types read in
4680  *
4681  * NB: this must run after getFuncs() because we assume we can do
4682  * findFuncByOid().
4683  */
4684 TypeInfo *
4685 getTypes(Archive *fout, int *numTypes)
4686 {
4687         DumpOptions *dopt = fout->dopt;
4688         PGresult   *res;
4689         int                     ntups;
4690         int                     i;
4691         PQExpBuffer query = createPQExpBuffer();
4692         TypeInfo   *tyinfo;
4693         ShellTypeInfo *stinfo;
4694         int                     i_tableoid;
4695         int                     i_oid;
4696         int                     i_typname;
4697         int                     i_typnamespace;
4698         int                     i_typacl;
4699         int                     i_rtypacl;
4700         int                     i_inittypacl;
4701         int                     i_initrtypacl;
4702         int                     i_rolname;
4703         int                     i_typelem;
4704         int                     i_typrelid;
4705         int                     i_typrelkind;
4706         int                     i_typtype;
4707         int                     i_typisdefined;
4708         int                     i_isarray;
4709
4710         /*
4711          * we include even the built-in types because those may be used as array
4712          * elements by user-defined types
4713          *
4714          * we filter out the built-in types when we dump out the types
4715          *
4716          * same approach for undefined (shell) types and array types
4717          *
4718          * Note: as of 8.3 we can reliably detect whether a type is an
4719          * auto-generated array type by checking the element type's typarray.
4720          * (Before that the test is capable of generating false positives.) We
4721          * still check for name beginning with '_', though, so as to avoid the
4722          * cost of the subselect probe for all standard types.  This would have to
4723          * be revisited if the backend ever allows renaming of array types.
4724          */
4725
4726         if (fout->remoteVersion >= 90600)
4727         {
4728                 PQExpBuffer acl_subquery = createPQExpBuffer();
4729                 PQExpBuffer racl_subquery = createPQExpBuffer();
4730                 PQExpBuffer initacl_subquery = createPQExpBuffer();
4731                 PQExpBuffer initracl_subquery = createPQExpBuffer();
4732
4733                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
4734                                                 initracl_subquery, "t.typacl", "t.typowner", "'T'",
4735                                                 dopt->binary_upgrade);
4736
4737                 appendPQExpBuffer(query, "SELECT t.tableoid, t.oid, t.typname, "
4738                                                   "t.typnamespace, "
4739                                                   "%s AS typacl, "
4740                                                   "%s AS rtypacl, "
4741                                                   "%s AS inittypacl, "
4742                                                   "%s AS initrtypacl, "
4743                                                   "(%s t.typowner) AS rolname, "
4744                                                   "t.typelem, t.typrelid, "
4745                                                   "CASE WHEN t.typrelid = 0 THEN ' '::\"char\" "
4746                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = t.typrelid) END AS typrelkind, "
4747                                                   "t.typtype, t.typisdefined, "
4748                                                   "t.typname[0] = '_' AND t.typelem != 0 AND "
4749                                                   "(SELECT typarray FROM pg_type te WHERE oid = t.typelem) = t.oid AS isarray "
4750                                                   "FROM pg_type t "
4751                                                   "LEFT JOIN pg_init_privs pip ON "
4752                                                   "(t.oid = pip.objoid "
4753                                                   "AND pip.classoid = 'pg_type'::regclass "
4754                                                   "AND pip.objsubid = 0) ",
4755                                                   acl_subquery->data,
4756                                                   racl_subquery->data,
4757                                                   initacl_subquery->data,
4758                                                   initracl_subquery->data,
4759                                                   username_subquery);
4760
4761                 destroyPQExpBuffer(acl_subquery);
4762                 destroyPQExpBuffer(racl_subquery);
4763                 destroyPQExpBuffer(initacl_subquery);
4764                 destroyPQExpBuffer(initracl_subquery);
4765         }
4766         else if (fout->remoteVersion >= 90200)
4767         {
4768                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4769                                                   "typnamespace, typacl, NULL as rtypacl, "
4770                                                   "NULL AS inittypacl, NULL AS initrtypacl, "
4771                                                   "(%s typowner) AS rolname, "
4772                                                   "typelem, typrelid, "
4773                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4774                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4775                                                   "typtype, typisdefined, "
4776                                                   "typname[0] = '_' AND typelem != 0 AND "
4777                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4778                                                   "FROM pg_type",
4779                                                   username_subquery);
4780         }
4781         else if (fout->remoteVersion >= 80300)
4782         {
4783                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4784                                                   "typnamespace, NULL AS typacl, NULL as rtypacl, "
4785                                                   "NULL AS inittypacl, NULL AS initrtypacl, "
4786                                                   "(%s typowner) AS rolname, "
4787                                                   "typelem, typrelid, "
4788                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4789                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4790                                                   "typtype, typisdefined, "
4791                                                   "typname[0] = '_' AND typelem != 0 AND "
4792                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4793                                                   "FROM pg_type",
4794                                                   username_subquery);
4795         }
4796         else
4797         {
4798                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4799                                                   "typnamespace, NULL AS typacl, NULL as rtypacl, "
4800                                                   "NULL AS inittypacl, NULL AS initrtypacl, "
4801                                                   "(%s typowner) AS rolname, "
4802                                                   "typelem, typrelid, "
4803                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4804                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4805                                                   "typtype, typisdefined, "
4806                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
4807                                                   "FROM pg_type",
4808                                                   username_subquery);
4809         }
4810
4811         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4812
4813         ntups = PQntuples(res);
4814
4815         tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
4816
4817         i_tableoid = PQfnumber(res, "tableoid");
4818         i_oid = PQfnumber(res, "oid");
4819         i_typname = PQfnumber(res, "typname");
4820         i_typnamespace = PQfnumber(res, "typnamespace");
4821         i_typacl = PQfnumber(res, "typacl");
4822         i_rtypacl = PQfnumber(res, "rtypacl");
4823         i_inittypacl = PQfnumber(res, "inittypacl");
4824         i_initrtypacl = PQfnumber(res, "initrtypacl");
4825         i_rolname = PQfnumber(res, "rolname");
4826         i_typelem = PQfnumber(res, "typelem");
4827         i_typrelid = PQfnumber(res, "typrelid");
4828         i_typrelkind = PQfnumber(res, "typrelkind");
4829         i_typtype = PQfnumber(res, "typtype");
4830         i_typisdefined = PQfnumber(res, "typisdefined");
4831         i_isarray = PQfnumber(res, "isarray");
4832
4833         for (i = 0; i < ntups; i++)
4834         {
4835                 tyinfo[i].dobj.objType = DO_TYPE;
4836                 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4837                 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4838                 AssignDumpId(&tyinfo[i].dobj);
4839                 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
4840                 tyinfo[i].dobj.namespace =
4841                         findNamespace(fout,
4842                                                   atooid(PQgetvalue(res, i, i_typnamespace)));
4843                 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4844                 tyinfo[i].typacl = pg_strdup(PQgetvalue(res, i, i_typacl));
4845                 tyinfo[i].rtypacl = pg_strdup(PQgetvalue(res, i, i_rtypacl));
4846                 tyinfo[i].inittypacl = pg_strdup(PQgetvalue(res, i, i_inittypacl));
4847                 tyinfo[i].initrtypacl = pg_strdup(PQgetvalue(res, i, i_initrtypacl));
4848                 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
4849                 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
4850                 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
4851                 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
4852                 tyinfo[i].shellType = NULL;
4853
4854                 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
4855                         tyinfo[i].isDefined = true;
4856                 else
4857                         tyinfo[i].isDefined = false;
4858
4859                 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
4860                         tyinfo[i].isArray = true;
4861                 else
4862                         tyinfo[i].isArray = false;
4863
4864                 /* Decide whether we want to dump it */
4865                 selectDumpableType(&tyinfo[i], fout);
4866
4867                 /* Do not try to dump ACL if no ACL exists. */
4868                 if (PQgetisnull(res, i, i_typacl) && PQgetisnull(res, i, i_rtypacl) &&
4869                         PQgetisnull(res, i, i_inittypacl) &&
4870                         PQgetisnull(res, i, i_initrtypacl))
4871                         tyinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4872
4873                 /*
4874                  * If it's a domain, fetch info about its constraints, if any
4875                  */
4876                 tyinfo[i].nDomChecks = 0;
4877                 tyinfo[i].domChecks = NULL;
4878                 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4879                         tyinfo[i].typtype == TYPTYPE_DOMAIN)
4880                         getDomainConstraints(fout, &(tyinfo[i]));
4881
4882                 /*
4883                  * If it's a base type, make a DumpableObject representing a shell
4884                  * definition of the type.  We will need to dump that ahead of the I/O
4885                  * functions for the type.  Similarly, range types need a shell
4886                  * definition in case they have a canonicalize function.
4887                  *
4888                  * Note: the shell type doesn't have a catId.  You might think it
4889                  * should copy the base type's catId, but then it might capture the
4890                  * pg_depend entries for the type, which we don't want.
4891                  */
4892                 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4893                         (tyinfo[i].typtype == TYPTYPE_BASE ||
4894                          tyinfo[i].typtype == TYPTYPE_RANGE))
4895                 {
4896                         stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
4897                         stinfo->dobj.objType = DO_SHELL_TYPE;
4898                         stinfo->dobj.catId = nilCatalogId;
4899                         AssignDumpId(&stinfo->dobj);
4900                         stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
4901                         stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
4902                         stinfo->baseType = &(tyinfo[i]);
4903                         tyinfo[i].shellType = stinfo;
4904
4905                         /*
4906                          * Initially mark the shell type as not to be dumped.  We'll only
4907                          * dump it if the I/O or canonicalize functions need to be dumped;
4908                          * this is taken care of while sorting dependencies.
4909                          */
4910                         stinfo->dobj.dump = DUMP_COMPONENT_NONE;
4911                 }
4912
4913                 if (strlen(tyinfo[i].rolname) == 0)
4914                         write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
4915                                           tyinfo[i].dobj.name);
4916         }
4917
4918         *numTypes = ntups;
4919
4920         PQclear(res);
4921
4922         destroyPQExpBuffer(query);
4923
4924         return tyinfo;
4925 }
4926
4927 /*
4928  * getOperators:
4929  *        read all operators in the system catalogs and return them in the
4930  * OprInfo* structure
4931  *
4932  *      numOprs is set to the number of operators read in
4933  */
4934 OprInfo *
4935 getOperators(Archive *fout, int *numOprs)
4936 {
4937         PGresult   *res;
4938         int                     ntups;
4939         int                     i;
4940         PQExpBuffer query = createPQExpBuffer();
4941         OprInfo    *oprinfo;
4942         int                     i_tableoid;
4943         int                     i_oid;
4944         int                     i_oprname;
4945         int                     i_oprnamespace;
4946         int                     i_rolname;
4947         int                     i_oprkind;
4948         int                     i_oprcode;
4949
4950         /*
4951          * find all operators, including builtin operators; we filter out
4952          * system-defined operators at dump-out time.
4953          */
4954
4955         appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
4956                                           "oprnamespace, "
4957                                           "(%s oprowner) AS rolname, "
4958                                           "oprkind, "
4959                                           "oprcode::oid AS oprcode "
4960                                           "FROM pg_operator",
4961                                           username_subquery);
4962
4963         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4964
4965         ntups = PQntuples(res);
4966         *numOprs = ntups;
4967
4968         oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
4969
4970         i_tableoid = PQfnumber(res, "tableoid");
4971         i_oid = PQfnumber(res, "oid");
4972         i_oprname = PQfnumber(res, "oprname");
4973         i_oprnamespace = PQfnumber(res, "oprnamespace");
4974         i_rolname = PQfnumber(res, "rolname");
4975         i_oprkind = PQfnumber(res, "oprkind");
4976         i_oprcode = PQfnumber(res, "oprcode");
4977
4978         for (i = 0; i < ntups; i++)
4979         {
4980                 oprinfo[i].dobj.objType = DO_OPERATOR;
4981                 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4982                 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4983                 AssignDumpId(&oprinfo[i].dobj);
4984                 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
4985                 oprinfo[i].dobj.namespace =
4986                         findNamespace(fout,
4987                                                   atooid(PQgetvalue(res, i, i_oprnamespace)));
4988                 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4989                 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
4990                 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
4991
4992                 /* Decide whether we want to dump it */
4993                 selectDumpableObject(&(oprinfo[i].dobj), fout);
4994
4995                 /* Operators do not currently have ACLs. */
4996                 oprinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4997
4998                 if (strlen(oprinfo[i].rolname) == 0)
4999                         write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
5000                                           oprinfo[i].dobj.name);
5001         }
5002
5003         PQclear(res);
5004
5005         destroyPQExpBuffer(query);
5006
5007         return oprinfo;
5008 }
5009
5010 /*
5011  * getCollations:
5012  *        read all collations in the system catalogs and return them in the
5013  * CollInfo* structure
5014  *
5015  *      numCollations is set to the number of collations read in
5016  */
5017 CollInfo *
5018 getCollations(Archive *fout, int *numCollations)
5019 {
5020         PGresult   *res;
5021         int                     ntups;
5022         int                     i;
5023         PQExpBuffer query;
5024         CollInfo   *collinfo;
5025         int                     i_tableoid;
5026         int                     i_oid;
5027         int                     i_collname;
5028         int                     i_collnamespace;
5029         int                     i_rolname;
5030
5031         /* Collations didn't exist pre-9.1 */
5032         if (fout->remoteVersion < 90100)
5033         {
5034                 *numCollations = 0;
5035                 return NULL;
5036         }
5037
5038         query = createPQExpBuffer();
5039
5040         /*
5041          * find all collations, including builtin collations; we filter out
5042          * system-defined collations at dump-out time.
5043          */
5044
5045         appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
5046                                           "collnamespace, "
5047                                           "(%s collowner) AS rolname "
5048                                           "FROM pg_collation",
5049                                           username_subquery);
5050
5051         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5052
5053         ntups = PQntuples(res);
5054         *numCollations = ntups;
5055
5056         collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
5057
5058         i_tableoid = PQfnumber(res, "tableoid");
5059         i_oid = PQfnumber(res, "oid");
5060         i_collname = PQfnumber(res, "collname");
5061         i_collnamespace = PQfnumber(res, "collnamespace");
5062         i_rolname = PQfnumber(res, "rolname");
5063
5064         for (i = 0; i < ntups; i++)
5065         {
5066                 collinfo[i].dobj.objType = DO_COLLATION;
5067                 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5068                 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5069                 AssignDumpId(&collinfo[i].dobj);
5070                 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
5071                 collinfo[i].dobj.namespace =
5072                         findNamespace(fout,
5073                                                   atooid(PQgetvalue(res, i, i_collnamespace)));
5074                 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5075
5076                 /* Decide whether we want to dump it */
5077                 selectDumpableObject(&(collinfo[i].dobj), fout);
5078
5079                 /* Collations do not currently have ACLs. */
5080                 collinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5081         }
5082
5083         PQclear(res);
5084
5085         destroyPQExpBuffer(query);
5086
5087         return collinfo;
5088 }
5089
5090 /*
5091  * getConversions:
5092  *        read all conversions in the system catalogs and return them in the
5093  * ConvInfo* structure
5094  *
5095  *      numConversions is set to the number of conversions read in
5096  */
5097 ConvInfo *
5098 getConversions(Archive *fout, int *numConversions)
5099 {
5100         PGresult   *res;
5101         int                     ntups;
5102         int                     i;
5103         PQExpBuffer query;
5104         ConvInfo   *convinfo;
5105         int                     i_tableoid;
5106         int                     i_oid;
5107         int                     i_conname;
5108         int                     i_connamespace;
5109         int                     i_rolname;
5110
5111         query = createPQExpBuffer();
5112
5113         /*
5114          * find all conversions, including builtin conversions; we filter out
5115          * system-defined conversions at dump-out time.
5116          */
5117
5118         appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5119                                           "connamespace, "
5120                                           "(%s conowner) AS rolname "
5121                                           "FROM pg_conversion",
5122                                           username_subquery);
5123
5124         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5125
5126         ntups = PQntuples(res);
5127         *numConversions = ntups;
5128
5129         convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
5130
5131         i_tableoid = PQfnumber(res, "tableoid");
5132         i_oid = PQfnumber(res, "oid");
5133         i_conname = PQfnumber(res, "conname");
5134         i_connamespace = PQfnumber(res, "connamespace");
5135         i_rolname = PQfnumber(res, "rolname");
5136
5137         for (i = 0; i < ntups; i++)
5138         {
5139                 convinfo[i].dobj.objType = DO_CONVERSION;
5140                 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5141                 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5142                 AssignDumpId(&convinfo[i].dobj);
5143                 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5144                 convinfo[i].dobj.namespace =
5145                         findNamespace(fout,
5146                                                   atooid(PQgetvalue(res, i, i_connamespace)));
5147                 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5148
5149                 /* Decide whether we want to dump it */
5150                 selectDumpableObject(&(convinfo[i].dobj), fout);
5151
5152                 /* Conversions do not currently have ACLs. */
5153                 convinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5154         }
5155
5156         PQclear(res);
5157
5158         destroyPQExpBuffer(query);
5159
5160         return convinfo;
5161 }
5162
5163 /*
5164  * getAccessMethods:
5165  *        read all user-defined access methods in the system catalogs and return
5166  *        them in the AccessMethodInfo* structure
5167  *
5168  *      numAccessMethods is set to the number of access methods read in
5169  */
5170 AccessMethodInfo *
5171 getAccessMethods(Archive *fout, int *numAccessMethods)
5172 {
5173         PGresult   *res;
5174         int                     ntups;
5175         int                     i;
5176         PQExpBuffer query;
5177         AccessMethodInfo *aminfo;
5178         int                     i_tableoid;
5179         int                     i_oid;
5180         int                     i_amname;
5181         int                     i_amhandler;
5182         int                     i_amtype;
5183
5184         /* Before 9.6, there are no user-defined access methods */
5185         if (fout->remoteVersion < 90600)
5186         {
5187                 *numAccessMethods = 0;
5188                 return NULL;
5189         }
5190
5191         query = createPQExpBuffer();
5192
5193         /* Select all access methods from pg_am table */
5194         appendPQExpBuffer(query, "SELECT tableoid, oid, amname, amtype, "
5195                                           "amhandler::pg_catalog.regproc AS amhandler "
5196                                           "FROM pg_am");
5197
5198         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5199
5200         ntups = PQntuples(res);
5201         *numAccessMethods = ntups;
5202
5203         aminfo = (AccessMethodInfo *) pg_malloc(ntups * sizeof(AccessMethodInfo));
5204
5205         i_tableoid = PQfnumber(res, "tableoid");
5206         i_oid = PQfnumber(res, "oid");
5207         i_amname = PQfnumber(res, "amname");
5208         i_amhandler = PQfnumber(res, "amhandler");
5209         i_amtype = PQfnumber(res, "amtype");
5210
5211         for (i = 0; i < ntups; i++)
5212         {
5213                 aminfo[i].dobj.objType = DO_ACCESS_METHOD;
5214                 aminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5215                 aminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5216                 AssignDumpId(&aminfo[i].dobj);
5217                 aminfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_amname));
5218                 aminfo[i].dobj.namespace = NULL;
5219                 aminfo[i].amhandler = pg_strdup(PQgetvalue(res, i, i_amhandler));
5220                 aminfo[i].amtype = *(PQgetvalue(res, i, i_amtype));
5221
5222                 /* Decide whether we want to dump it */
5223                 selectDumpableAccessMethod(&(aminfo[i]), fout);
5224
5225                 /* Access methods do not currently have ACLs. */
5226                 aminfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5227         }
5228
5229         PQclear(res);
5230
5231         destroyPQExpBuffer(query);
5232
5233         return aminfo;
5234 }
5235
5236
5237 /*
5238  * getOpclasses:
5239  *        read all opclasses in the system catalogs and return them in the
5240  * OpclassInfo* structure
5241  *
5242  *      numOpclasses is set to the number of opclasses read in
5243  */
5244 OpclassInfo *
5245 getOpclasses(Archive *fout, int *numOpclasses)
5246 {
5247         PGresult   *res;
5248         int                     ntups;
5249         int                     i;
5250         PQExpBuffer query = createPQExpBuffer();
5251         OpclassInfo *opcinfo;
5252         int                     i_tableoid;
5253         int                     i_oid;
5254         int                     i_opcname;
5255         int                     i_opcnamespace;
5256         int                     i_rolname;
5257
5258         /*
5259          * find all opclasses, including builtin opclasses; we filter out
5260          * system-defined opclasses at dump-out time.
5261          */
5262
5263         appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
5264                                           "opcnamespace, "
5265                                           "(%s opcowner) AS rolname "
5266                                           "FROM pg_opclass",
5267                                           username_subquery);
5268
5269         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5270
5271         ntups = PQntuples(res);
5272         *numOpclasses = ntups;
5273
5274         opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
5275
5276         i_tableoid = PQfnumber(res, "tableoid");
5277         i_oid = PQfnumber(res, "oid");
5278         i_opcname = PQfnumber(res, "opcname");
5279         i_opcnamespace = PQfnumber(res, "opcnamespace");
5280         i_rolname = PQfnumber(res, "rolname");
5281
5282         for (i = 0; i < ntups; i++)
5283         {
5284                 opcinfo[i].dobj.objType = DO_OPCLASS;
5285                 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5286                 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5287                 AssignDumpId(&opcinfo[i].dobj);
5288                 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
5289                 opcinfo[i].dobj.namespace =
5290                         findNamespace(fout,
5291                                                   atooid(PQgetvalue(res, i, i_opcnamespace)));
5292                 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5293
5294                 /* Decide whether we want to dump it */
5295                 selectDumpableObject(&(opcinfo[i].dobj), fout);
5296
5297                 /* Op Classes do not currently have ACLs. */
5298                 opcinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5299
5300                 if (strlen(opcinfo[i].rolname) == 0)
5301                         write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
5302                                           opcinfo[i].dobj.name);
5303         }
5304
5305         PQclear(res);
5306
5307         destroyPQExpBuffer(query);
5308
5309         return opcinfo;
5310 }
5311
5312 /*
5313  * getOpfamilies:
5314  *        read all opfamilies in the system catalogs and return them in the
5315  * OpfamilyInfo* structure
5316  *
5317  *      numOpfamilies is set to the number of opfamilies read in
5318  */
5319 OpfamilyInfo *
5320 getOpfamilies(Archive *fout, int *numOpfamilies)
5321 {
5322         PGresult   *res;
5323         int                     ntups;
5324         int                     i;
5325         PQExpBuffer query;
5326         OpfamilyInfo *opfinfo;
5327         int                     i_tableoid;
5328         int                     i_oid;
5329         int                     i_opfname;
5330         int                     i_opfnamespace;
5331         int                     i_rolname;
5332
5333         /* Before 8.3, there is no separate concept of opfamilies */
5334         if (fout->remoteVersion < 80300)
5335         {
5336                 *numOpfamilies = 0;
5337                 return NULL;
5338         }
5339
5340         query = createPQExpBuffer();
5341
5342         /*
5343          * find all opfamilies, including builtin opfamilies; we filter out
5344          * system-defined opfamilies at dump-out time.
5345          */
5346
5347         appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
5348                                           "opfnamespace, "
5349                                           "(%s opfowner) AS rolname "
5350                                           "FROM pg_opfamily",
5351                                           username_subquery);
5352
5353         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5354
5355         ntups = PQntuples(res);
5356         *numOpfamilies = ntups;
5357
5358         opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
5359
5360         i_tableoid = PQfnumber(res, "tableoid");
5361         i_oid = PQfnumber(res, "oid");
5362         i_opfname = PQfnumber(res, "opfname");
5363         i_opfnamespace = PQfnumber(res, "opfnamespace");
5364         i_rolname = PQfnumber(res, "rolname");
5365
5366         for (i = 0; i < ntups; i++)
5367         {
5368                 opfinfo[i].dobj.objType = DO_OPFAMILY;
5369                 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5370                 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5371                 AssignDumpId(&opfinfo[i].dobj);
5372                 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
5373                 opfinfo[i].dobj.namespace =
5374                         findNamespace(fout,
5375                                                   atooid(PQgetvalue(res, i, i_opfnamespace)));
5376                 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5377
5378                 /* Decide whether we want to dump it */
5379                 selectDumpableObject(&(opfinfo[i].dobj), fout);
5380
5381                 /* Extensions do not currently have ACLs. */
5382                 opfinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5383
5384                 if (strlen(opfinfo[i].rolname) == 0)
5385                         write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
5386                                           opfinfo[i].dobj.name);
5387         }
5388
5389         PQclear(res);
5390
5391         destroyPQExpBuffer(query);
5392
5393         return opfinfo;
5394 }
5395
5396 /*
5397  * getAggregates:
5398  *        read all the user-defined aggregates in the system catalogs and
5399  * return them in the AggInfo* structure
5400  *
5401  * numAggs is set to the number of aggregates read in
5402  */
5403 AggInfo *
5404 getAggregates(Archive *fout, int *numAggs)
5405 {
5406         DumpOptions *dopt = fout->dopt;
5407         PGresult   *res;
5408         int                     ntups;
5409         int                     i;
5410         PQExpBuffer query = createPQExpBuffer();
5411         AggInfo    *agginfo;
5412         int                     i_tableoid;
5413         int                     i_oid;
5414         int                     i_aggname;
5415         int                     i_aggnamespace;
5416         int                     i_pronargs;
5417         int                     i_proargtypes;
5418         int                     i_rolname;
5419         int                     i_aggacl;
5420         int                     i_raggacl;
5421         int                     i_initaggacl;
5422         int                     i_initraggacl;
5423
5424         /*
5425          * Find all interesting aggregates.  See comment in getFuncs() for the
5426          * rationale behind the filtering logic.
5427          */
5428         if (fout->remoteVersion >= 90600)
5429         {
5430                 PQExpBuffer acl_subquery = createPQExpBuffer();
5431                 PQExpBuffer racl_subquery = createPQExpBuffer();
5432                 PQExpBuffer initacl_subquery = createPQExpBuffer();
5433                 PQExpBuffer initracl_subquery = createPQExpBuffer();
5434                 const char *agg_check;
5435
5436                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5437                                                 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5438                                                 dopt->binary_upgrade);
5439
5440                 agg_check = (fout->remoteVersion >= 110000 ? "p.prokind = 'a'"
5441                                          : "p.proisagg");
5442
5443                 appendPQExpBuffer(query, "SELECT p.tableoid, p.oid, "
5444                                                   "p.proname AS aggname, "
5445                                                   "p.pronamespace AS aggnamespace, "
5446                                                   "p.pronargs, p.proargtypes, "
5447                                                   "(%s p.proowner) AS rolname, "
5448                                                   "%s AS aggacl, "
5449                                                   "%s AS raggacl, "
5450                                                   "%s AS initaggacl, "
5451                                                   "%s AS initraggacl "
5452                                                   "FROM pg_proc p "
5453                                                   "LEFT JOIN pg_init_privs pip ON "
5454                                                   "(p.oid = pip.objoid "
5455                                                   "AND pip.classoid = 'pg_proc'::regclass "
5456                                                   "AND pip.objsubid = 0) "
5457                                                   "WHERE %s AND ("
5458                                                   "p.pronamespace != "
5459                                                   "(SELECT oid FROM pg_namespace "
5460                                                   "WHERE nspname = 'pg_catalog') OR "
5461                                                   "p.proacl IS DISTINCT FROM pip.initprivs",
5462                                                   username_subquery,
5463                                                   acl_subquery->data,
5464                                                   racl_subquery->data,
5465                                                   initacl_subquery->data,
5466                                                   initracl_subquery->data,
5467                                                   agg_check);
5468                 if (dopt->binary_upgrade)
5469                         appendPQExpBufferStr(query,
5470                                                                  " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5471                                                                  "classid = 'pg_proc'::regclass AND "
5472                                                                  "objid = p.oid AND "
5473                                                                  "refclassid = 'pg_extension'::regclass AND "
5474                                                                  "deptype = 'e')");
5475                 appendPQExpBufferChar(query, ')');
5476
5477                 destroyPQExpBuffer(acl_subquery);
5478                 destroyPQExpBuffer(racl_subquery);
5479                 destroyPQExpBuffer(initacl_subquery);
5480                 destroyPQExpBuffer(initracl_subquery);
5481         }
5482         else if (fout->remoteVersion >= 80200)
5483         {
5484                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5485                                                   "pronamespace AS aggnamespace, "
5486                                                   "pronargs, proargtypes, "
5487                                                   "(%s proowner) AS rolname, "
5488                                                   "proacl AS aggacl, "
5489                                                   "NULL AS raggacl, "
5490                                                   "NULL AS initaggacl, NULL AS initraggacl "
5491                                                   "FROM pg_proc p "
5492                                                   "WHERE proisagg AND ("
5493                                                   "pronamespace != "
5494                                                   "(SELECT oid FROM pg_namespace "
5495                                                   "WHERE nspname = 'pg_catalog')",
5496                                                   username_subquery);
5497                 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5498                         appendPQExpBufferStr(query,
5499                                                                  " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5500                                                                  "classid = 'pg_proc'::regclass AND "
5501                                                                  "objid = p.oid AND "
5502                                                                  "refclassid = 'pg_extension'::regclass AND "
5503                                                                  "deptype = 'e')");
5504                 appendPQExpBufferChar(query, ')');
5505         }
5506         else
5507         {
5508                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5509                                                   "pronamespace AS aggnamespace, "
5510                                                   "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
5511                                                   "proargtypes, "
5512                                                   "(%s proowner) AS rolname, "
5513                                                   "proacl AS aggacl, "
5514                                                   "NULL AS raggacl, "
5515                                                   "NULL AS initaggacl, NULL AS initraggacl "
5516                                                   "FROM pg_proc "
5517                                                   "WHERE proisagg "
5518                                                   "AND pronamespace != "
5519                                                   "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
5520                                                   username_subquery);
5521         }
5522
5523         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5524
5525         ntups = PQntuples(res);
5526         *numAggs = ntups;
5527
5528         agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
5529
5530         i_tableoid = PQfnumber(res, "tableoid");
5531         i_oid = PQfnumber(res, "oid");
5532         i_aggname = PQfnumber(res, "aggname");
5533         i_aggnamespace = PQfnumber(res, "aggnamespace");
5534         i_pronargs = PQfnumber(res, "pronargs");
5535         i_proargtypes = PQfnumber(res, "proargtypes");
5536         i_rolname = PQfnumber(res, "rolname");
5537         i_aggacl = PQfnumber(res, "aggacl");
5538         i_raggacl = PQfnumber(res, "raggacl");
5539         i_initaggacl = PQfnumber(res, "initaggacl");
5540         i_initraggacl = PQfnumber(res, "initraggacl");
5541
5542         for (i = 0; i < ntups; i++)
5543         {
5544                 agginfo[i].aggfn.dobj.objType = DO_AGG;
5545                 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5546                 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5547                 AssignDumpId(&agginfo[i].aggfn.dobj);
5548                 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
5549                 agginfo[i].aggfn.dobj.namespace =
5550                         findNamespace(fout,
5551                                                   atooid(PQgetvalue(res, i, i_aggnamespace)));
5552                 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5553                 if (strlen(agginfo[i].aggfn.rolname) == 0)
5554                         write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
5555                                           agginfo[i].aggfn.dobj.name);
5556                 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
5557                 agginfo[i].aggfn.prorettype = InvalidOid;       /* not saved */
5558                 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
5559                 agginfo[i].aggfn.rproacl = pg_strdup(PQgetvalue(res, i, i_raggacl));
5560                 agginfo[i].aggfn.initproacl = pg_strdup(PQgetvalue(res, i, i_initaggacl));
5561                 agginfo[i].aggfn.initrproacl = pg_strdup(PQgetvalue(res, i, i_initraggacl));
5562                 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
5563                 if (agginfo[i].aggfn.nargs == 0)
5564                         agginfo[i].aggfn.argtypes = NULL;
5565                 else
5566                 {
5567                         agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
5568                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
5569                                                   agginfo[i].aggfn.argtypes,
5570                                                   agginfo[i].aggfn.nargs);
5571                 }
5572
5573                 /* Decide whether we want to dump it */
5574                 selectDumpableObject(&(agginfo[i].aggfn.dobj), fout);
5575
5576                 /* Do not try to dump ACL if no ACL exists. */
5577                 if (PQgetisnull(res, i, i_aggacl) && PQgetisnull(res, i, i_raggacl) &&
5578                         PQgetisnull(res, i, i_initaggacl) &&
5579                         PQgetisnull(res, i, i_initraggacl))
5580                         agginfo[i].aggfn.dobj.dump &= ~DUMP_COMPONENT_ACL;
5581         }
5582
5583         PQclear(res);
5584
5585         destroyPQExpBuffer(query);
5586
5587         return agginfo;
5588 }
5589
5590 /*
5591  * getFuncs:
5592  *        read all the user-defined functions in the system catalogs and
5593  * return them in the FuncInfo* structure
5594  *
5595  * numFuncs is set to the number of functions read in
5596  */
5597 FuncInfo *
5598 getFuncs(Archive *fout, int *numFuncs)
5599 {
5600         DumpOptions *dopt = fout->dopt;
5601         PGresult   *res;
5602         int                     ntups;
5603         int                     i;
5604         PQExpBuffer query = createPQExpBuffer();
5605         FuncInfo   *finfo;
5606         int                     i_tableoid;
5607         int                     i_oid;
5608         int                     i_proname;
5609         int                     i_pronamespace;
5610         int                     i_rolname;
5611         int                     i_prolang;
5612         int                     i_pronargs;
5613         int                     i_proargtypes;
5614         int                     i_prorettype;
5615         int                     i_proacl;
5616         int                     i_rproacl;
5617         int                     i_initproacl;
5618         int                     i_initrproacl;
5619
5620         /*
5621          * Find all interesting functions.  This is a bit complicated:
5622          *
5623          * 1. Always exclude aggregates; those are handled elsewhere.
5624          *
5625          * 2. Always exclude functions that are internally dependent on something
5626          * else, since presumably those will be created as a result of creating
5627          * the something else.  This currently acts only to suppress constructor
5628          * functions for range types (so we only need it in 9.2 and up).  Note
5629          * this is OK only because the constructors don't have any dependencies
5630          * the range type doesn't have; otherwise we might not get creation
5631          * ordering correct.
5632          *
5633          * 3. Otherwise, we normally exclude functions in pg_catalog.  However, if
5634          * they're members of extensions and we are in binary-upgrade mode then
5635          * include them, since we want to dump extension members individually in
5636          * that mode.  Also, if they are used by casts or transforms then we need
5637          * to gather the information about them, though they won't be dumped if
5638          * they are built-in.  Also, in 9.6 and up, include functions in
5639          * pg_catalog if they have an ACL different from what's shown in
5640          * pg_init_privs.
5641          */
5642         if (fout->remoteVersion >= 90600)
5643         {
5644                 PQExpBuffer acl_subquery = createPQExpBuffer();
5645                 PQExpBuffer racl_subquery = createPQExpBuffer();
5646                 PQExpBuffer initacl_subquery = createPQExpBuffer();
5647                 PQExpBuffer initracl_subquery = createPQExpBuffer();
5648                 const char *not_agg_check;
5649
5650                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5651                                                 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5652                                                 dopt->binary_upgrade);
5653
5654                 not_agg_check = (fout->remoteVersion >= 110000 ? "p.prokind <> 'a'"
5655                                                  : "NOT p.proisagg");
5656
5657                 appendPQExpBuffer(query,
5658                                                   "SELECT p.tableoid, p.oid, p.proname, p.prolang, "
5659                                                   "p.pronargs, p.proargtypes, p.prorettype, "
5660                                                   "%s AS proacl, "
5661                                                   "%s AS rproacl, "
5662                                                   "%s AS initproacl, "
5663                                                   "%s AS initrproacl, "
5664                                                   "p.pronamespace, "
5665                                                   "(%s p.proowner) AS rolname "
5666                                                   "FROM pg_proc p "
5667                                                   "LEFT JOIN pg_init_privs pip ON "
5668                                                   "(p.oid = pip.objoid "
5669                                                   "AND pip.classoid = 'pg_proc'::regclass "
5670                                                   "AND pip.objsubid = 0) "
5671                                                   "WHERE %s"
5672                                                   "\n  AND NOT EXISTS (SELECT 1 FROM pg_depend "
5673                                                   "WHERE classid = 'pg_proc'::regclass AND "
5674                                                   "objid = p.oid AND deptype = 'i')"
5675                                                   "\n  AND ("
5676                                                   "\n  pronamespace != "
5677                                                   "(SELECT oid FROM pg_namespace "
5678                                                   "WHERE nspname = 'pg_catalog')"
5679                                                   "\n  OR EXISTS (SELECT 1 FROM pg_cast"
5680                                                   "\n  WHERE pg_cast.oid > %u "
5681                                                   "\n  AND p.oid = pg_cast.castfunc)"
5682                                                   "\n  OR EXISTS (SELECT 1 FROM pg_transform"
5683                                                   "\n  WHERE pg_transform.oid > %u AND "
5684                                                   "\n  (p.oid = pg_transform.trffromsql"
5685                                                   "\n  OR p.oid = pg_transform.trftosql))",
5686                                                   acl_subquery->data,
5687                                                   racl_subquery->data,
5688                                                   initacl_subquery->data,
5689                                                   initracl_subquery->data,
5690                                                   username_subquery,
5691                                                   not_agg_check,
5692                                                   g_last_builtin_oid,
5693                                                   g_last_builtin_oid);
5694                 if (dopt->binary_upgrade)
5695                         appendPQExpBufferStr(query,
5696                                                                  "\n  OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5697                                                                  "classid = 'pg_proc'::regclass AND "
5698                                                                  "objid = p.oid AND "
5699                                                                  "refclassid = 'pg_extension'::regclass AND "
5700                                                                  "deptype = 'e')");
5701                 appendPQExpBufferStr(query,
5702                                                          "\n  OR p.proacl IS DISTINCT FROM pip.initprivs");
5703                 appendPQExpBufferChar(query, ')');
5704
5705                 destroyPQExpBuffer(acl_subquery);
5706                 destroyPQExpBuffer(racl_subquery);
5707                 destroyPQExpBuffer(initacl_subquery);
5708                 destroyPQExpBuffer(initracl_subquery);
5709         }
5710         else
5711         {
5712                 appendPQExpBuffer(query,
5713                                                   "SELECT tableoid, oid, proname, prolang, "
5714                                                   "pronargs, proargtypes, prorettype, proacl, "
5715                                                   "NULL as rproacl, "
5716                                                   "NULL as initproacl, NULL AS initrproacl, "
5717                                                   "pronamespace, "
5718                                                   "(%s proowner) AS rolname "
5719                                                   "FROM pg_proc p "
5720                                                   "WHERE NOT proisagg",
5721                                                   username_subquery);
5722                 if (fout->remoteVersion >= 90200)
5723                         appendPQExpBufferStr(query,
5724                                                                  "\n  AND NOT EXISTS (SELECT 1 FROM pg_depend "
5725                                                                  "WHERE classid = 'pg_proc'::regclass AND "
5726                                                                  "objid = p.oid AND deptype = 'i')");
5727                 appendPQExpBuffer(query,
5728                                                   "\n  AND ("
5729                                                   "\n  pronamespace != "
5730                                                   "(SELECT oid FROM pg_namespace "
5731                                                   "WHERE nspname = 'pg_catalog')"
5732                                                   "\n  OR EXISTS (SELECT 1 FROM pg_cast"
5733                                                   "\n  WHERE pg_cast.oid > '%u'::oid"
5734                                                   "\n  AND p.oid = pg_cast.castfunc)",
5735                                                   g_last_builtin_oid);
5736
5737                 if (fout->remoteVersion >= 90500)
5738                         appendPQExpBuffer(query,
5739                                                           "\n  OR EXISTS (SELECT 1 FROM pg_transform"
5740                                                           "\n  WHERE pg_transform.oid > '%u'::oid"
5741                                                           "\n  AND (p.oid = pg_transform.trffromsql"
5742                                                           "\n  OR p.oid = pg_transform.trftosql))",
5743                                                           g_last_builtin_oid);
5744
5745                 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5746                         appendPQExpBufferStr(query,
5747                                                                  "\n  OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5748                                                                  "classid = 'pg_proc'::regclass AND "
5749                                                                  "objid = p.oid AND "
5750                                                                  "refclassid = 'pg_extension'::regclass AND "
5751                                                                  "deptype = 'e')");
5752                 appendPQExpBufferChar(query, ')');
5753         }
5754
5755         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5756
5757         ntups = PQntuples(res);
5758
5759         *numFuncs = ntups;
5760
5761         finfo = (FuncInfo *) pg_malloc0(ntups * sizeof(FuncInfo));
5762
5763         i_tableoid = PQfnumber(res, "tableoid");
5764         i_oid = PQfnumber(res, "oid");
5765         i_proname = PQfnumber(res, "proname");
5766         i_pronamespace = PQfnumber(res, "pronamespace");
5767         i_rolname = PQfnumber(res, "rolname");
5768         i_prolang = PQfnumber(res, "prolang");
5769         i_pronargs = PQfnumber(res, "pronargs");
5770         i_proargtypes = PQfnumber(res, "proargtypes");
5771         i_prorettype = PQfnumber(res, "prorettype");
5772         i_proacl = PQfnumber(res, "proacl");
5773         i_rproacl = PQfnumber(res, "rproacl");
5774         i_initproacl = PQfnumber(res, "initproacl");
5775         i_initrproacl = PQfnumber(res, "initrproacl");
5776
5777         for (i = 0; i < ntups; i++)
5778         {
5779                 finfo[i].dobj.objType = DO_FUNC;
5780                 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5781                 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5782                 AssignDumpId(&finfo[i].dobj);
5783                 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
5784                 finfo[i].dobj.namespace =
5785                         findNamespace(fout,
5786                                                   atooid(PQgetvalue(res, i, i_pronamespace)));
5787                 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5788                 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
5789                 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
5790                 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
5791                 finfo[i].rproacl = pg_strdup(PQgetvalue(res, i, i_rproacl));
5792                 finfo[i].initproacl = pg_strdup(PQgetvalue(res, i, i_initproacl));
5793                 finfo[i].initrproacl = pg_strdup(PQgetvalue(res, i, i_initrproacl));
5794                 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
5795                 if (finfo[i].nargs == 0)
5796                         finfo[i].argtypes = NULL;
5797                 else
5798                 {
5799                         finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
5800                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
5801                                                   finfo[i].argtypes, finfo[i].nargs);
5802                 }
5803
5804                 /* Decide whether we want to dump it */
5805                 selectDumpableObject(&(finfo[i].dobj), fout);
5806
5807                 /* Do not try to dump ACL if no ACL exists. */
5808                 if (PQgetisnull(res, i, i_proacl) && PQgetisnull(res, i, i_rproacl) &&
5809                         PQgetisnull(res, i, i_initproacl) &&
5810                         PQgetisnull(res, i, i_initrproacl))
5811                         finfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5812
5813                 if (strlen(finfo[i].rolname) == 0)
5814                         write_msg(NULL,
5815                                           "WARNING: owner of function \"%s\" appears to be invalid\n",
5816                                           finfo[i].dobj.name);
5817         }
5818
5819         PQclear(res);
5820
5821         destroyPQExpBuffer(query);
5822
5823         return finfo;
5824 }
5825
5826 /*
5827  * getTables
5828  *        read all the tables (no indexes)
5829  * in the system catalogs return them in the TableInfo* structure
5830  *
5831  * numTables is set to the number of tables read in
5832  */
5833 TableInfo *
5834 getTables(Archive *fout, int *numTables)
5835 {
5836         DumpOptions *dopt = fout->dopt;
5837         PGresult   *res;
5838         int                     ntups;
5839         int                     i;
5840         PQExpBuffer query = createPQExpBuffer();
5841         TableInfo  *tblinfo;
5842         int                     i_reltableoid;
5843         int                     i_reloid;
5844         int                     i_relname;
5845         int                     i_relnamespace;
5846         int                     i_relkind;
5847         int                     i_relacl;
5848         int                     i_rrelacl;
5849         int                     i_initrelacl;
5850         int                     i_initrrelacl;
5851         int                     i_rolname;
5852         int                     i_relchecks;
5853         int                     i_relhastriggers;
5854         int                     i_relhasindex;
5855         int                     i_relhasrules;
5856         int                     i_relrowsec;
5857         int                     i_relforcerowsec;
5858         int                     i_relhasoids;
5859         int                     i_relfrozenxid;
5860         int                     i_relminmxid;
5861         int                     i_toastoid;
5862         int                     i_toastfrozenxid;
5863         int                     i_toastminmxid;
5864         int                     i_relpersistence;
5865         int                     i_relispopulated;
5866         int                     i_relreplident;
5867         int                     i_owning_tab;
5868         int                     i_owning_col;
5869         int                     i_reltablespace;
5870         int                     i_reloptions;
5871         int                     i_checkoption;
5872         int                     i_toastreloptions;
5873         int                     i_reloftype;
5874         int                     i_relpages;
5875         int                     i_is_identity_sequence;
5876         int                     i_changed_acl;
5877         int                     i_partkeydef;
5878         int                     i_ispartition;
5879         int                     i_partbound;
5880
5881         /*
5882          * Find all the tables and table-like objects.
5883          *
5884          * We include system catalogs, so that we can work if a user table is
5885          * defined to inherit from a system catalog (pretty weird, but...)
5886          *
5887          * We ignore relations that are not ordinary tables, sequences, views,
5888          * materialized views, composite types, or foreign tables.
5889          *
5890          * Composite-type table entries won't be dumped as such, but we have to
5891          * make a DumpableObject for them so that we can track dependencies of the
5892          * composite type (pg_depend entries for columns of the composite type
5893          * link to the pg_class entry not the pg_type entry).
5894          *
5895          * Note: in this phase we should collect only a minimal amount of
5896          * information about each table, basically just enough to decide if it is
5897          * interesting. We must fetch all tables in this phase because otherwise
5898          * we cannot correctly identify inherited columns, owned sequences, etc.
5899          */
5900
5901         if (fout->remoteVersion >= 90600)
5902         {
5903                 char       *partkeydef = "NULL";
5904                 char       *ispartition = "false";
5905                 char       *partbound = "NULL";
5906
5907                 PQExpBuffer acl_subquery = createPQExpBuffer();
5908                 PQExpBuffer racl_subquery = createPQExpBuffer();
5909                 PQExpBuffer initacl_subquery = createPQExpBuffer();
5910                 PQExpBuffer initracl_subquery = createPQExpBuffer();
5911
5912                 PQExpBuffer attacl_subquery = createPQExpBuffer();
5913                 PQExpBuffer attracl_subquery = createPQExpBuffer();
5914                 PQExpBuffer attinitacl_subquery = createPQExpBuffer();
5915                 PQExpBuffer attinitracl_subquery = createPQExpBuffer();
5916
5917                 /*
5918                  * Collect the information about any partitioned tables, which were
5919                  * added in PG10.
5920                  */
5921
5922                 if (fout->remoteVersion >= 100000)
5923                 {
5924                         partkeydef = "pg_get_partkeydef(c.oid)";
5925                         ispartition = "c.relispartition";
5926                         partbound = "pg_get_expr(c.relpartbound, c.oid)";
5927                 }
5928
5929                 /*
5930                  * Left join to pick up dependency info linking sequences to their
5931                  * owning column, if any (note this dependency is AUTO as of 8.2)
5932                  *
5933                  * Left join to detect if any privileges are still as-set-at-init, in
5934                  * which case we won't dump out ACL commands for those.
5935                  */
5936
5937                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5938                                                 initracl_subquery, "c.relacl", "c.relowner",
5939                                                 "CASE WHEN c.relkind = " CppAsString2(RELKIND_SEQUENCE)
5940                                                 " THEN 's' ELSE 'r' END::\"char\"",
5941                                                 dopt->binary_upgrade);
5942
5943                 buildACLQueries(attacl_subquery, attracl_subquery, attinitacl_subquery,
5944                                                 attinitracl_subquery, "at.attacl", "c.relowner", "'c'",
5945                                                 dopt->binary_upgrade);
5946
5947                 appendPQExpBuffer(query,
5948                                                   "SELECT c.tableoid, c.oid, c.relname, "
5949                                                   "%s AS relacl, %s as rrelacl, "
5950                                                   "%s AS initrelacl, %s as initrrelacl, "
5951                                                   "c.relkind, c.relnamespace, "
5952                                                   "(%s c.relowner) AS rolname, "
5953                                                   "c.relchecks, c.relhastriggers, "
5954                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
5955                                                   "c.relrowsecurity, c.relforcerowsecurity, "
5956                                                   "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
5957                                                   "tc.relfrozenxid AS tfrozenxid, "
5958                                                   "tc.relminmxid AS tminmxid, "
5959                                                   "c.relpersistence, c.relispopulated, "
5960                                                   "c.relreplident, c.relpages, "
5961                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
5962                                                   "d.refobjid AS owning_tab, "
5963                                                   "d.refobjsubid AS owning_col, "
5964                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5965                                                   "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
5966                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
5967                                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
5968                                                   "tc.reloptions AS toast_reloptions, "
5969                                                   "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, "
5970                                                   "EXISTS (SELECT 1 FROM pg_attribute at LEFT JOIN pg_init_privs pip ON "
5971                                                   "(c.oid = pip.objoid "
5972                                                   "AND pip.classoid = 'pg_class'::regclass "
5973                                                   "AND pip.objsubid = at.attnum)"
5974                                                   "WHERE at.attrelid = c.oid AND ("
5975                                                   "%s IS NOT NULL "
5976                                                   "OR %s IS NOT NULL "
5977                                                   "OR %s IS NOT NULL "
5978                                                   "OR %s IS NOT NULL"
5979                                                   "))"
5980                                                   "AS changed_acl, "
5981                                                   "%s AS partkeydef, "
5982                                                   "%s AS ispartition, "
5983                                                   "%s AS partbound "
5984                                                   "FROM pg_class c "
5985                                                   "LEFT JOIN pg_depend d ON "
5986                                                   "(c.relkind = '%c' AND "
5987                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
5988                                                   "d.objsubid = 0 AND "
5989                                                   "d.refclassid = c.tableoid AND d.deptype IN ('a', 'i')) "
5990                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5991                                                   "LEFT JOIN pg_init_privs pip ON "
5992                                                   "(c.oid = pip.objoid "
5993                                                   "AND pip.classoid = 'pg_class'::regclass "
5994                                                   "AND pip.objsubid = 0) "
5995                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c', '%c') "
5996                                                   "ORDER BY c.oid",
5997                                                   acl_subquery->data,
5998                                                   racl_subquery->data,
5999                                                   initacl_subquery->data,
6000                                                   initracl_subquery->data,
6001                                                   username_subquery,
6002                                                   RELKIND_SEQUENCE,
6003                                                   attacl_subquery->data,
6004                                                   attracl_subquery->data,
6005                                                   attinitacl_subquery->data,
6006                                                   attinitracl_subquery->data,
6007                                                   partkeydef,
6008                                                   ispartition,
6009                                                   partbound,
6010                                                   RELKIND_SEQUENCE,
6011                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6012                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6013                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
6014                                                   RELKIND_PARTITIONED_TABLE);
6015
6016                 destroyPQExpBuffer(acl_subquery);
6017                 destroyPQExpBuffer(racl_subquery);
6018                 destroyPQExpBuffer(initacl_subquery);
6019                 destroyPQExpBuffer(initracl_subquery);
6020
6021                 destroyPQExpBuffer(attacl_subquery);
6022                 destroyPQExpBuffer(attracl_subquery);
6023                 destroyPQExpBuffer(attinitacl_subquery);
6024                 destroyPQExpBuffer(attinitracl_subquery);
6025         }
6026         else if (fout->remoteVersion >= 90500)
6027         {
6028                 /*
6029                  * Left join to pick up dependency info linking sequences to their
6030                  * owning column, if any (note this dependency is AUTO as of 8.2)
6031                  */
6032                 appendPQExpBuffer(query,
6033                                                   "SELECT c.tableoid, c.oid, c.relname, "
6034                                                   "c.relacl, NULL as rrelacl, "
6035                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6036                                                   "c.relkind, "
6037                                                   "c.relnamespace, "
6038                                                   "(%s c.relowner) AS rolname, "
6039                                                   "c.relchecks, c.relhastriggers, "
6040                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6041                                                   "c.relrowsecurity, c.relforcerowsecurity, "
6042                                                   "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6043                                                   "tc.relfrozenxid AS tfrozenxid, "
6044                                                   "tc.relminmxid AS tminmxid, "
6045                                                   "c.relpersistence, c.relispopulated, "
6046                                                   "c.relreplident, c.relpages, "
6047                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6048                                                   "d.refobjid AS owning_tab, "
6049                                                   "d.refobjsubid AS owning_col, "
6050                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6051                                                   "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6052                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6053                                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6054                                                   "tc.reloptions AS toast_reloptions, "
6055                                                   "NULL AS changed_acl, "
6056                                                   "NULL AS partkeydef, "
6057                                                   "false AS ispartition, "
6058                                                   "NULL AS partbound "
6059                                                   "FROM pg_class c "
6060                                                   "LEFT JOIN pg_depend d ON "
6061                                                   "(c.relkind = '%c' AND "
6062                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6063                                                   "d.objsubid = 0 AND "
6064                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6065                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6066                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6067                                                   "ORDER BY c.oid",
6068                                                   username_subquery,
6069                                                   RELKIND_SEQUENCE,
6070                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6071                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6072                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6073         }
6074         else if (fout->remoteVersion >= 90400)
6075         {
6076                 /*
6077                  * Left join to pick up dependency info linking sequences to their
6078                  * owning column, if any (note this dependency is AUTO as of 8.2)
6079                  */
6080                 appendPQExpBuffer(query,
6081                                                   "SELECT c.tableoid, c.oid, c.relname, "
6082                                                   "c.relacl, NULL as rrelacl, "
6083                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6084                                                   "c.relkind, "
6085                                                   "c.relnamespace, "
6086                                                   "(%s c.relowner) AS rolname, "
6087                                                   "c.relchecks, c.relhastriggers, "
6088                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6089                                                   "'f'::bool AS relrowsecurity, "
6090                                                   "'f'::bool AS relforcerowsecurity, "
6091                                                   "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6092                                                   "tc.relfrozenxid AS tfrozenxid, "
6093                                                   "tc.relminmxid AS tminmxid, "
6094                                                   "c.relpersistence, c.relispopulated, "
6095                                                   "c.relreplident, c.relpages, "
6096                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6097                                                   "d.refobjid AS owning_tab, "
6098                                                   "d.refobjsubid AS owning_col, "
6099                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6100                                                   "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6101                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6102                                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6103                                                   "tc.reloptions AS toast_reloptions, "
6104                                                   "NULL AS changed_acl, "
6105                                                   "NULL AS partkeydef, "
6106                                                   "false AS ispartition, "
6107                                                   "NULL AS partbound "
6108                                                   "FROM pg_class c "
6109                                                   "LEFT JOIN pg_depend d ON "
6110                                                   "(c.relkind = '%c' AND "
6111                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6112                                                   "d.objsubid = 0 AND "
6113                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6114                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6115                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6116                                                   "ORDER BY c.oid",
6117                                                   username_subquery,
6118                                                   RELKIND_SEQUENCE,
6119                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6120                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6121                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6122         }
6123         else if (fout->remoteVersion >= 90300)
6124         {
6125                 /*
6126                  * Left join to pick up dependency info linking sequences to their
6127                  * owning column, if any (note this dependency is AUTO as of 8.2)
6128                  */
6129                 appendPQExpBuffer(query,
6130                                                   "SELECT c.tableoid, c.oid, c.relname, "
6131                                                   "c.relacl, NULL as rrelacl, "
6132                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6133                                                   "c.relkind, "
6134                                                   "c.relnamespace, "
6135                                                   "(%s c.relowner) AS rolname, "
6136                                                   "c.relchecks, c.relhastriggers, "
6137                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6138                                                   "'f'::bool AS relrowsecurity, "
6139                                                   "'f'::bool AS relforcerowsecurity, "
6140                                                   "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6141                                                   "tc.relfrozenxid AS tfrozenxid, "
6142                                                   "tc.relminmxid AS tminmxid, "
6143                                                   "c.relpersistence, c.relispopulated, "
6144                                                   "'d' AS relreplident, c.relpages, "
6145                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6146                                                   "d.refobjid AS owning_tab, "
6147                                                   "d.refobjsubid AS owning_col, "
6148                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6149                                                   "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6150                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6151                                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6152                                                   "tc.reloptions AS toast_reloptions, "
6153                                                   "NULL AS changed_acl, "
6154                                                   "NULL AS partkeydef, "
6155                                                   "false AS ispartition, "
6156                                                   "NULL AS partbound "
6157                                                   "FROM pg_class c "
6158                                                   "LEFT JOIN pg_depend d ON "
6159                                                   "(c.relkind = '%c' AND "
6160                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6161                                                   "d.objsubid = 0 AND "
6162                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6163                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6164                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6165                                                   "ORDER BY c.oid",
6166                                                   username_subquery,
6167                                                   RELKIND_SEQUENCE,
6168                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6169                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6170                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6171         }
6172         else if (fout->remoteVersion >= 90100)
6173         {
6174                 /*
6175                  * Left join to pick up dependency info linking sequences to their
6176                  * owning column, if any (note this dependency is AUTO as of 8.2)
6177                  */
6178                 appendPQExpBuffer(query,
6179                                                   "SELECT c.tableoid, c.oid, c.relname, "
6180                                                   "c.relacl, NULL as rrelacl, "
6181                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6182                                                   "c.relkind, "
6183                                                   "c.relnamespace, "
6184                                                   "(%s c.relowner) AS rolname, "
6185                                                   "c.relchecks, c.relhastriggers, "
6186                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6187                                                   "'f'::bool AS relrowsecurity, "
6188                                                   "'f'::bool AS relforcerowsecurity, "
6189                                                   "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6190                                                   "tc.relfrozenxid AS tfrozenxid, "
6191                                                   "0 AS tminmxid, "
6192                                                   "c.relpersistence, 't' as relispopulated, "
6193                                                   "'d' AS relreplident, c.relpages, "
6194                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6195                                                   "d.refobjid AS owning_tab, "
6196                                                   "d.refobjsubid AS owning_col, "
6197                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6198                                                   "c.reloptions AS reloptions, "
6199                                                   "tc.reloptions AS toast_reloptions, "
6200                                                   "NULL AS changed_acl, "
6201                                                   "NULL AS partkeydef, "
6202                                                   "false AS ispartition, "
6203                                                   "NULL AS partbound "
6204                                                   "FROM pg_class c "
6205                                                   "LEFT JOIN pg_depend d ON "
6206                                                   "(c.relkind = '%c' AND "
6207                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6208                                                   "d.objsubid = 0 AND "
6209                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6210                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6211                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6212                                                   "ORDER BY c.oid",
6213                                                   username_subquery,
6214                                                   RELKIND_SEQUENCE,
6215                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6216                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6217                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6218         }
6219         else if (fout->remoteVersion >= 90000)
6220         {
6221                 /*
6222                  * Left join to pick up dependency info linking sequences to their
6223                  * owning column, if any (note this dependency is AUTO as of 8.2)
6224                  */
6225                 appendPQExpBuffer(query,
6226                                                   "SELECT c.tableoid, c.oid, c.relname, "
6227                                                   "c.relacl, NULL as rrelacl, "
6228                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6229                                                   "c.relkind, "
6230                                                   "c.relnamespace, "
6231                                                   "(%s c.relowner) AS rolname, "
6232                                                   "c.relchecks, c.relhastriggers, "
6233                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6234                                                   "'f'::bool AS relrowsecurity, "
6235                                                   "'f'::bool AS relforcerowsecurity, "
6236                                                   "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6237                                                   "tc.relfrozenxid AS tfrozenxid, "
6238                                                   "0 AS tminmxid, "
6239                                                   "'p' AS relpersistence, 't' as relispopulated, "
6240                                                   "'d' AS relreplident, c.relpages, "
6241                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6242                                                   "d.refobjid AS owning_tab, "
6243                                                   "d.refobjsubid AS owning_col, "
6244                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6245                                                   "c.reloptions AS reloptions, "
6246                                                   "tc.reloptions AS toast_reloptions, "
6247                                                   "NULL AS changed_acl, "
6248                                                   "NULL AS partkeydef, "
6249                                                   "false AS ispartition, "
6250                                                   "NULL AS partbound "
6251                                                   "FROM pg_class c "
6252                                                   "LEFT JOIN pg_depend d ON "
6253                                                   "(c.relkind = '%c' AND "
6254                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6255                                                   "d.objsubid = 0 AND "
6256                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6257                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6258                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6259                                                   "ORDER BY c.oid",
6260                                                   username_subquery,
6261                                                   RELKIND_SEQUENCE,
6262                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6263                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6264         }
6265         else if (fout->remoteVersion >= 80400)
6266         {
6267                 /*
6268                  * Left join to pick up dependency info linking sequences to their
6269                  * owning column, if any (note this dependency is AUTO as of 8.2)
6270                  */
6271                 appendPQExpBuffer(query,
6272                                                   "SELECT c.tableoid, c.oid, c.relname, "
6273                                                   "c.relacl, NULL as rrelacl, "
6274                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6275                                                   "c.relkind, "
6276                                                   "c.relnamespace, "
6277                                                   "(%s c.relowner) AS rolname, "
6278                                                   "c.relchecks, c.relhastriggers, "
6279                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6280                                                   "'f'::bool AS relrowsecurity, "
6281                                                   "'f'::bool AS relforcerowsecurity, "
6282                                                   "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6283                                                   "tc.relfrozenxid AS tfrozenxid, "
6284                                                   "0 AS tminmxid, "
6285                                                   "'p' AS relpersistence, 't' as relispopulated, "
6286                                                   "'d' AS relreplident, c.relpages, "
6287                                                   "NULL AS reloftype, "
6288                                                   "d.refobjid AS owning_tab, "
6289                                                   "d.refobjsubid AS owning_col, "
6290                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6291                                                   "c.reloptions AS reloptions, "
6292                                                   "tc.reloptions AS toast_reloptions, "
6293                                                   "NULL AS changed_acl, "
6294                                                   "NULL AS partkeydef, "
6295                                                   "false AS ispartition, "
6296                                                   "NULL AS partbound "
6297                                                   "FROM pg_class c "
6298                                                   "LEFT JOIN pg_depend d ON "
6299                                                   "(c.relkind = '%c' AND "
6300                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6301                                                   "d.objsubid = 0 AND "
6302                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6303                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6304                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6305                                                   "ORDER BY c.oid",
6306                                                   username_subquery,
6307                                                   RELKIND_SEQUENCE,
6308                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6309                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6310         }
6311         else if (fout->remoteVersion >= 80200)
6312         {
6313                 /*
6314                  * Left join to pick up dependency info linking sequences to their
6315                  * owning column, if any (note this dependency is AUTO as of 8.2)
6316                  */
6317                 appendPQExpBuffer(query,
6318                                                   "SELECT c.tableoid, c.oid, c.relname, "
6319                                                   "c.relacl, NULL as rrelacl, "
6320                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6321                                                   "c.relkind, "
6322                                                   "c.relnamespace, "
6323                                                   "(%s c.relowner) AS rolname, "
6324                                                   "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
6325                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6326                                                   "'f'::bool AS relrowsecurity, "
6327                                                   "'f'::bool AS relforcerowsecurity, "
6328                                                   "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6329                                                   "tc.relfrozenxid AS tfrozenxid, "
6330                                                   "0 AS tminmxid, "
6331                                                   "'p' AS relpersistence, 't' as relispopulated, "
6332                                                   "'d' AS relreplident, c.relpages, "
6333                                                   "NULL AS reloftype, "
6334                                                   "d.refobjid AS owning_tab, "
6335                                                   "d.refobjsubid AS owning_col, "
6336                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6337                                                   "c.reloptions AS reloptions, "
6338                                                   "NULL AS toast_reloptions, "
6339                                                   "NULL AS changed_acl, "
6340                                                   "NULL AS partkeydef, "
6341                                                   "false AS ispartition, "
6342                                                   "NULL AS partbound "
6343                                                   "FROM pg_class c "
6344                                                   "LEFT JOIN pg_depend d ON "
6345                                                   "(c.relkind = '%c' AND "
6346                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6347                                                   "d.objsubid = 0 AND "
6348                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6349                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6350                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6351                                                   "ORDER BY c.oid",
6352                                                   username_subquery,
6353                                                   RELKIND_SEQUENCE,
6354                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6355                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6356         }
6357         else
6358         {
6359                 /*
6360                  * Left join to pick up dependency info linking sequences to their
6361                  * owning column, if any
6362                  */
6363                 appendPQExpBuffer(query,
6364                                                   "SELECT c.tableoid, c.oid, relname, "
6365                                                   "relacl, NULL as rrelacl, "
6366                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6367                                                   "relkind, relnamespace, "
6368                                                   "(%s relowner) AS rolname, "
6369                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
6370                                                   "relhasindex, relhasrules, relhasoids, "
6371                                                   "'f'::bool AS relrowsecurity, "
6372                                                   "'f'::bool AS relforcerowsecurity, "
6373                                                   "0 AS relfrozenxid, 0 AS relminmxid,"
6374                                                   "0 AS toid, "
6375                                                   "0 AS tfrozenxid, 0 AS tminmxid,"
6376                                                   "'p' AS relpersistence, 't' as relispopulated, "
6377                                                   "'d' AS relreplident, relpages, "
6378                                                   "NULL AS reloftype, "
6379                                                   "d.refobjid AS owning_tab, "
6380                                                   "d.refobjsubid AS owning_col, "
6381                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6382                                                   "NULL AS reloptions, "
6383                                                   "NULL AS toast_reloptions, "
6384                                                   "NULL AS changed_acl, "
6385                                                   "NULL AS partkeydef, "
6386                                                   "false AS ispartition, "
6387                                                   "NULL AS partbound "
6388                                                   "FROM pg_class c "
6389                                                   "LEFT JOIN pg_depend d ON "
6390                                                   "(c.relkind = '%c' AND "
6391                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6392                                                   "d.objsubid = 0 AND "
6393                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
6394                                                   "WHERE relkind in ('%c', '%c', '%c', '%c') "
6395                                                   "ORDER BY c.oid",
6396                                                   username_subquery,
6397                                                   RELKIND_SEQUENCE,
6398                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6399                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6400         }
6401
6402         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6403
6404         ntups = PQntuples(res);
6405
6406         *numTables = ntups;
6407
6408         /*
6409          * Extract data from result and lock dumpable tables.  We do the locking
6410          * before anything else, to minimize the window wherein a table could
6411          * disappear under us.
6412          *
6413          * Note that we have to save info about all tables here, even when dumping
6414          * only one, because we don't yet know which tables might be inheritance
6415          * ancestors of the target table.
6416          */
6417         tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
6418
6419         i_reltableoid = PQfnumber(res, "tableoid");
6420         i_reloid = PQfnumber(res, "oid");
6421         i_relname = PQfnumber(res, "relname");
6422         i_relnamespace = PQfnumber(res, "relnamespace");
6423         i_relacl = PQfnumber(res, "relacl");
6424         i_rrelacl = PQfnumber(res, "rrelacl");
6425         i_initrelacl = PQfnumber(res, "initrelacl");
6426         i_initrrelacl = PQfnumber(res, "initrrelacl");
6427         i_relkind = PQfnumber(res, "relkind");
6428         i_rolname = PQfnumber(res, "rolname");
6429         i_relchecks = PQfnumber(res, "relchecks");
6430         i_relhastriggers = PQfnumber(res, "relhastriggers");
6431         i_relhasindex = PQfnumber(res, "relhasindex");
6432         i_relhasrules = PQfnumber(res, "relhasrules");
6433         i_relrowsec = PQfnumber(res, "relrowsecurity");
6434         i_relforcerowsec = PQfnumber(res, "relforcerowsecurity");
6435         i_relhasoids = PQfnumber(res, "relhasoids");
6436         i_relfrozenxid = PQfnumber(res, "relfrozenxid");
6437         i_relminmxid = PQfnumber(res, "relminmxid");
6438         i_toastoid = PQfnumber(res, "toid");
6439         i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
6440         i_toastminmxid = PQfnumber(res, "tminmxid");
6441         i_relpersistence = PQfnumber(res, "relpersistence");
6442         i_relispopulated = PQfnumber(res, "relispopulated");
6443         i_relreplident = PQfnumber(res, "relreplident");
6444         i_relpages = PQfnumber(res, "relpages");
6445         i_owning_tab = PQfnumber(res, "owning_tab");
6446         i_owning_col = PQfnumber(res, "owning_col");
6447         i_reltablespace = PQfnumber(res, "reltablespace");
6448         i_reloptions = PQfnumber(res, "reloptions");
6449         i_checkoption = PQfnumber(res, "checkoption");
6450         i_toastreloptions = PQfnumber(res, "toast_reloptions");
6451         i_reloftype = PQfnumber(res, "reloftype");
6452         i_is_identity_sequence = PQfnumber(res, "is_identity_sequence");
6453         i_changed_acl = PQfnumber(res, "changed_acl");
6454         i_partkeydef = PQfnumber(res, "partkeydef");
6455         i_ispartition = PQfnumber(res, "ispartition");
6456         i_partbound = PQfnumber(res, "partbound");
6457
6458         if (dopt->lockWaitTimeout)
6459         {
6460                 /*
6461                  * Arrange to fail instead of waiting forever for a table lock.
6462                  *
6463                  * NB: this coding assumes that the only queries issued within the
6464                  * following loop are LOCK TABLEs; else the timeout may be undesirably
6465                  * applied to other things too.
6466                  */
6467                 resetPQExpBuffer(query);
6468                 appendPQExpBufferStr(query, "SET statement_timeout = ");
6469                 appendStringLiteralConn(query, dopt->lockWaitTimeout, GetConnection(fout));
6470                 ExecuteSqlStatement(fout, query->data);
6471         }
6472
6473         for (i = 0; i < ntups; i++)
6474         {
6475                 tblinfo[i].dobj.objType = DO_TABLE;
6476                 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
6477                 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
6478                 AssignDumpId(&tblinfo[i].dobj);
6479                 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
6480                 tblinfo[i].dobj.namespace =
6481                         findNamespace(fout,
6482                                                   atooid(PQgetvalue(res, i, i_relnamespace)));
6483                 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6484                 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
6485                 tblinfo[i].rrelacl = pg_strdup(PQgetvalue(res, i, i_rrelacl));
6486                 tblinfo[i].initrelacl = pg_strdup(PQgetvalue(res, i, i_initrelacl));
6487                 tblinfo[i].initrrelacl = pg_strdup(PQgetvalue(res, i, i_initrrelacl));
6488                 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
6489                 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
6490                 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
6491                 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
6492                 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
6493                 tblinfo[i].rowsec = (strcmp(PQgetvalue(res, i, i_relrowsec), "t") == 0);
6494                 tblinfo[i].forcerowsec = (strcmp(PQgetvalue(res, i, i_relforcerowsec), "t") == 0);
6495                 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
6496                 tblinfo[i].relispopulated = (strcmp(PQgetvalue(res, i, i_relispopulated), "t") == 0);
6497                 tblinfo[i].relreplident = *(PQgetvalue(res, i, i_relreplident));
6498                 tblinfo[i].relpages = atoi(PQgetvalue(res, i, i_relpages));
6499                 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
6500                 tblinfo[i].minmxid = atooid(PQgetvalue(res, i, i_relminmxid));
6501                 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
6502                 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
6503                 tblinfo[i].toast_minmxid = atooid(PQgetvalue(res, i, i_toastminmxid));
6504                 if (PQgetisnull(res, i, i_reloftype))
6505                         tblinfo[i].reloftype = NULL;
6506                 else
6507                         tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
6508                 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
6509                 if (PQgetisnull(res, i, i_owning_tab))
6510                 {
6511                         tblinfo[i].owning_tab = InvalidOid;
6512                         tblinfo[i].owning_col = 0;
6513                 }
6514                 else
6515                 {
6516                         tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
6517                         tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
6518                 }
6519                 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
6520                 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
6521                 if (i_checkoption == -1 || PQgetisnull(res, i, i_checkoption))
6522                         tblinfo[i].checkoption = NULL;
6523                 else
6524                         tblinfo[i].checkoption = pg_strdup(PQgetvalue(res, i, i_checkoption));
6525                 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
6526
6527                 /* other fields were zeroed above */
6528
6529                 /*
6530                  * Decide whether we want to dump this table.
6531                  */
6532                 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
6533                         tblinfo[i].dobj.dump = DUMP_COMPONENT_NONE;
6534                 else
6535                         selectDumpableTable(&tblinfo[i], fout);
6536
6537                 /*
6538                  * If the table-level and all column-level ACLs for this table are
6539                  * unchanged, then we don't need to worry about including the ACLs for
6540                  * this table.  If any column-level ACLs have been changed, the
6541                  * 'changed_acl' column from the query will indicate that.
6542                  *
6543                  * This can result in a significant performance improvement in cases
6544                  * where we are only looking to dump out the ACL (eg: pg_catalog).
6545                  */
6546                 if (PQgetisnull(res, i, i_relacl) && PQgetisnull(res, i, i_rrelacl) &&
6547                         PQgetisnull(res, i, i_initrelacl) &&
6548                         PQgetisnull(res, i, i_initrrelacl) &&
6549                         strcmp(PQgetvalue(res, i, i_changed_acl), "f") == 0)
6550                         tblinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
6551
6552                 tblinfo[i].interesting = tblinfo[i].dobj.dump ? true : false;
6553                 tblinfo[i].dummy_view = false;  /* might get set during sort */
6554                 tblinfo[i].postponed_def = false;       /* might get set during sort */
6555
6556                 tblinfo[i].is_identity_sequence = (i_is_identity_sequence >= 0 &&
6557                                                                                    strcmp(PQgetvalue(res, i, i_is_identity_sequence), "t") == 0);
6558
6559                 /* Partition key string or NULL */
6560                 tblinfo[i].partkeydef = pg_strdup(PQgetvalue(res, i, i_partkeydef));
6561                 tblinfo[i].ispartition = (strcmp(PQgetvalue(res, i, i_ispartition), "t") == 0);
6562                 tblinfo[i].partbound = pg_strdup(PQgetvalue(res, i, i_partbound));
6563
6564                 /*
6565                  * Read-lock target tables to make sure they aren't DROPPED or altered
6566                  * in schema before we get around to dumping them.
6567                  *
6568                  * Note that we don't explicitly lock parents of the target tables; we
6569                  * assume our lock on the child is enough to prevent schema
6570                  * alterations to parent tables.
6571                  *
6572                  * NOTE: it'd be kinda nice to lock other relations too, not only
6573                  * plain or partitioned tables, but the backend doesn't presently
6574                  * allow that.
6575                  *
6576                  * We only need to lock the table for certain components; see
6577                  * pg_dump.h
6578                  */
6579                 if (tblinfo[i].dobj.dump &&
6580                         (tblinfo[i].relkind == RELKIND_RELATION ||
6581                          tblinfo->relkind == RELKIND_PARTITIONED_TABLE) &&
6582                         (tblinfo[i].dobj.dump & DUMP_COMPONENTS_REQUIRING_LOCK))
6583                 {
6584                         resetPQExpBuffer(query);
6585                         appendPQExpBuffer(query,
6586                                                           "LOCK TABLE %s IN ACCESS SHARE MODE",
6587                                                           fmtQualifiedDumpable(&tblinfo[i]));
6588                         ExecuteSqlStatement(fout, query->data);
6589                 }
6590
6591                 /* Emit notice if join for owner failed */
6592                 if (strlen(tblinfo[i].rolname) == 0)
6593                         write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
6594                                           tblinfo[i].dobj.name);
6595         }
6596
6597         if (dopt->lockWaitTimeout)
6598         {
6599                 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
6600         }
6601
6602         PQclear(res);
6603
6604         destroyPQExpBuffer(query);
6605
6606         return tblinfo;
6607 }
6608
6609 /*
6610  * getOwnedSeqs
6611  *        identify owned sequences and mark them as dumpable if owning table is
6612  *
6613  * We used to do this in getTables(), but it's better to do it after the
6614  * index used by findTableByOid() has been set up.
6615  */
6616 void
6617 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
6618 {
6619         int                     i;
6620
6621         /*
6622          * Force sequences that are "owned" by table columns to be dumped whenever
6623          * their owning table is being dumped.
6624          */
6625         for (i = 0; i < numTables; i++)
6626         {
6627                 TableInfo  *seqinfo = &tblinfo[i];
6628                 TableInfo  *owning_tab;
6629
6630                 if (!OidIsValid(seqinfo->owning_tab))
6631                         continue;                       /* not an owned sequence */
6632
6633                 owning_tab = findTableByOid(seqinfo->owning_tab);
6634                 if (owning_tab == NULL)
6635                         exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
6636                                                   seqinfo->owning_tab, seqinfo->dobj.catId.oid);
6637
6638                 /*
6639                  * We need to dump the components that are being dumped for the table
6640                  * and any components which the sequence is explicitly marked with.
6641                  *
6642                  * We can't simply use the set of components which are being dumped
6643                  * for the table as the table might be in an extension (and only the
6644                  * non-extension components, eg: ACLs if changed, security labels, and
6645                  * policies, are being dumped) while the sequence is not (and
6646                  * therefore the definition and other components should also be
6647                  * dumped).
6648                  *
6649                  * If the sequence is part of the extension then it should be properly
6650                  * marked by checkExtensionMembership() and this will be a no-op as
6651                  * the table will be equivalently marked.
6652                  */
6653                 seqinfo->dobj.dump = seqinfo->dobj.dump | owning_tab->dobj.dump;
6654
6655                 if (seqinfo->dobj.dump != DUMP_COMPONENT_NONE)
6656                         seqinfo->interesting = true;
6657         }
6658 }
6659
6660 /*
6661  * getInherits
6662  *        read all the inheritance information
6663  * from the system catalogs return them in the InhInfo* structure
6664  *
6665  * numInherits is set to the number of pairs read in
6666  */
6667 InhInfo *
6668 getInherits(Archive *fout, int *numInherits)
6669 {
6670         PGresult   *res;
6671         int                     ntups;
6672         int                     i;
6673         PQExpBuffer query = createPQExpBuffer();
6674         InhInfo    *inhinfo;
6675
6676         int                     i_inhrelid;
6677         int                     i_inhparent;
6678
6679         /*
6680          * Find all the inheritance information, excluding implicit inheritance
6681          * via partitioning.  We handle that case using getPartitions(), because
6682          * we want more information about partitions than just the parent-child
6683          * relationship.
6684          */
6685         appendPQExpBufferStr(query, "SELECT inhrelid, inhparent FROM pg_inherits");
6686
6687         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6688
6689         ntups = PQntuples(res);
6690
6691         *numInherits = ntups;
6692
6693         inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
6694
6695         i_inhrelid = PQfnumber(res, "inhrelid");
6696         i_inhparent = PQfnumber(res, "inhparent");
6697
6698         for (i = 0; i < ntups; i++)
6699         {
6700                 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
6701                 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
6702         }
6703
6704         PQclear(res);
6705
6706         destroyPQExpBuffer(query);
6707
6708         return inhinfo;
6709 }
6710
6711 /*
6712  * getIndexes
6713  *        get information about every index on a dumpable table
6714  *
6715  * Note: index data is not returned directly to the caller, but it
6716  * does get entered into the DumpableObject tables.
6717  */
6718 void
6719 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
6720 {
6721         int                     i,
6722                                 j;
6723         PQExpBuffer query = createPQExpBuffer();
6724         PGresult   *res;
6725         IndxInfo   *indxinfo;
6726         ConstraintInfo *constrinfo;
6727         int                     i_tableoid,
6728                                 i_oid,
6729                                 i_indexname,
6730                                 i_parentidx,
6731                                 i_indexdef,
6732                                 i_indnkeyatts,
6733                                 i_indnatts,
6734                                 i_indkey,
6735                                 i_indisclustered,
6736                                 i_indisreplident,
6737                                 i_contype,
6738                                 i_conname,
6739                                 i_condeferrable,
6740                                 i_condeferred,
6741                                 i_contableoid,
6742                                 i_conoid,
6743                                 i_condef,
6744                                 i_tablespace,
6745                                 i_indreloptions,
6746                                 i_relpages;
6747         int                     ntups;
6748
6749         for (i = 0; i < numTables; i++)
6750         {
6751                 TableInfo  *tbinfo = &tblinfo[i];
6752
6753                 if (!tbinfo->hasindex)
6754                         continue;
6755
6756                 /*
6757                  * Ignore indexes of tables whose definitions are not to be dumped.
6758                  *
6759                  * We also need indexes on partitioned tables which have partitions to
6760                  * be dumped, in order to dump the indexes on the partitions.
6761                  */
6762                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION) &&
6763                         !tbinfo->interesting)
6764                         continue;
6765
6766                 if (g_verbose)
6767                         write_msg(NULL, "reading indexes for table \"%s.%s\"\n",
6768                                           tbinfo->dobj.namespace->dobj.name,
6769                                           tbinfo->dobj.name);
6770
6771                 /*
6772                  * The point of the messy-looking outer join is to find a constraint
6773                  * that is related by an internal dependency link to the index. If we
6774                  * find one, create a CONSTRAINT entry linked to the INDEX entry.  We
6775                  * assume an index won't have more than one internal dependency.
6776                  *
6777                  * As of 9.0 we don't need to look at pg_depend but can check for a
6778                  * match to pg_constraint.conindid.  The check on conrelid is
6779                  * redundant but useful because that column is indexed while conindid
6780                  * is not.
6781                  */
6782                 resetPQExpBuffer(query);
6783                 if (fout->remoteVersion >= 110000)
6784                 {
6785                         appendPQExpBuffer(query,
6786                                                           "SELECT t.tableoid, t.oid, "
6787                                                           "t.relname AS indexname, "
6788                                                           "inh.inhparent AS parentidx, "
6789                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6790                                                           "i.indnkeyatts AS indnkeyatts, "
6791                                                           "i.indnatts AS indnatts, "
6792                                                           "i.indkey, i.indisclustered, "
6793                                                           "i.indisreplident, t.relpages, "
6794                                                           "c.contype, c.conname, "
6795                                                           "c.condeferrable, c.condeferred, "
6796                                                           "c.tableoid AS contableoid, "
6797                                                           "c.oid AS conoid, "
6798                                                           "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6799                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6800                                                           "t.reloptions AS indreloptions "
6801                                                           "FROM pg_catalog.pg_index i "
6802                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6803                                                           "JOIN pg_catalog.pg_class t2 ON (t2.oid = i.indrelid) "
6804                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6805                                                           "ON (i.indrelid = c.conrelid AND "
6806                                                           "i.indexrelid = c.conindid AND "
6807                                                           "c.contype IN ('p','u','x')) "
6808                                                           "LEFT JOIN pg_catalog.pg_inherits inh "
6809                                                           "ON (inh.inhrelid = indexrelid) "
6810                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6811                                                           "AND (i.indisvalid OR t2.relkind = 'p') "
6812                                                           "AND i.indisready "
6813                                                           "ORDER BY indexname",
6814                                                           tbinfo->dobj.catId.oid);
6815                 }
6816                 else if (fout->remoteVersion >= 90400)
6817                 {
6818                         /*
6819                          * the test on indisready is necessary in 9.2, and harmless in
6820                          * earlier/later versions
6821                          */
6822                         appendPQExpBuffer(query,
6823                                                           "SELECT t.tableoid, t.oid, "
6824                                                           "t.relname AS indexname, "
6825                                                           "0 AS parentidx, "
6826                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6827                                                           "i.indnatts AS indnkeyatts, "
6828                                                           "i.indnatts AS indnatts, "
6829                                                           "i.indkey, i.indisclustered, "
6830                                                           "i.indisreplident, t.relpages, "
6831                                                           "c.contype, c.conname, "
6832                                                           "c.condeferrable, c.condeferred, "
6833                                                           "c.tableoid AS contableoid, "
6834                                                           "c.oid AS conoid, "
6835                                                           "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6836                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6837                                                           "t.reloptions AS indreloptions "
6838                                                           "FROM pg_catalog.pg_index i "
6839                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6840                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6841                                                           "ON (i.indrelid = c.conrelid AND "
6842                                                           "i.indexrelid = c.conindid AND "
6843                                                           "c.contype IN ('p','u','x')) "
6844                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6845                                                           "AND i.indisvalid AND i.indisready "
6846                                                           "ORDER BY indexname",
6847                                                           tbinfo->dobj.catId.oid);
6848                 }
6849                 else if (fout->remoteVersion >= 90000)
6850                 {
6851                         /*
6852                          * the test on indisready is necessary in 9.2, and harmless in
6853                          * earlier/later versions
6854                          */
6855                         appendPQExpBuffer(query,
6856                                                           "SELECT t.tableoid, t.oid, "
6857                                                           "t.relname AS indexname, "
6858                                                           "0 AS parentidx, "
6859                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6860                                                           "i.indnatts AS indnkeyatts, "
6861                                                           "i.indnatts AS indnatts, "
6862                                                           "i.indkey, i.indisclustered, "
6863                                                           "false AS indisreplident, t.relpages, "
6864                                                           "c.contype, c.conname, "
6865                                                           "c.condeferrable, c.condeferred, "
6866                                                           "c.tableoid AS contableoid, "
6867                                                           "c.oid AS conoid, "
6868                                                           "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6869                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6870                                                           "t.reloptions AS indreloptions "
6871                                                           "FROM pg_catalog.pg_index i "
6872                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6873                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6874                                                           "ON (i.indrelid = c.conrelid AND "
6875                                                           "i.indexrelid = c.conindid AND "
6876                                                           "c.contype IN ('p','u','x')) "
6877                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6878                                                           "AND i.indisvalid AND i.indisready "
6879                                                           "ORDER BY indexname",
6880                                                           tbinfo->dobj.catId.oid);
6881                 }
6882                 else if (fout->remoteVersion >= 80200)
6883                 {
6884                         appendPQExpBuffer(query,
6885                                                           "SELECT t.tableoid, t.oid, "
6886                                                           "t.relname AS indexname, "
6887                                                           "0 AS parentidx, "
6888                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6889                                                           "i.indnatts AS indnkeyatts, "
6890                                                           "i.indnatts AS indnatts, "
6891                                                           "i.indkey, i.indisclustered, "
6892                                                           "false AS indisreplident, t.relpages, "
6893                                                           "c.contype, c.conname, "
6894                                                           "c.condeferrable, c.condeferred, "
6895                                                           "c.tableoid AS contableoid, "
6896                                                           "c.oid AS conoid, "
6897                                                           "null AS condef, "
6898                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6899                                                           "t.reloptions AS indreloptions "
6900                                                           "FROM pg_catalog.pg_index i "
6901                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6902                                                           "LEFT JOIN pg_catalog.pg_depend d "
6903                                                           "ON (d.classid = t.tableoid "
6904                                                           "AND d.objid = t.oid "
6905                                                           "AND d.deptype = 'i') "
6906                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6907                                                           "ON (d.refclassid = c.tableoid "
6908                                                           "AND d.refobjid = c.oid) "
6909                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6910                                                           "AND i.indisvalid "
6911                                                           "ORDER BY indexname",
6912                                                           tbinfo->dobj.catId.oid);
6913                 }
6914                 else
6915                 {
6916                         appendPQExpBuffer(query,
6917                                                           "SELECT t.tableoid, t.oid, "
6918                                                           "t.relname AS indexname, "
6919                                                           "0 AS parentidx, "
6920                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6921                                                           "t.relnatts AS indnkeyatts, "
6922                                                           "t.relnatts AS indnatts, "
6923                                                           "i.indkey, i.indisclustered, "
6924                                                           "false AS indisreplident, t.relpages, "
6925                                                           "c.contype, c.conname, "
6926                                                           "c.condeferrable, c.condeferred, "
6927                                                           "c.tableoid AS contableoid, "
6928                                                           "c.oid AS conoid, "
6929                                                           "null AS condef, "
6930                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6931                                                           "null AS indreloptions "
6932                                                           "FROM pg_catalog.pg_index i "
6933                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6934                                                           "LEFT JOIN pg_catalog.pg_depend d "
6935                                                           "ON (d.classid = t.tableoid "
6936                                                           "AND d.objid = t.oid "
6937                                                           "AND d.deptype = 'i') "
6938                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6939                                                           "ON (d.refclassid = c.tableoid "
6940                                                           "AND d.refobjid = c.oid) "
6941                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6942                                                           "ORDER BY indexname",
6943                                                           tbinfo->dobj.catId.oid);
6944                 }
6945
6946                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6947
6948                 ntups = PQntuples(res);
6949
6950                 i_tableoid = PQfnumber(res, "tableoid");
6951                 i_oid = PQfnumber(res, "oid");
6952                 i_indexname = PQfnumber(res, "indexname");
6953                 i_parentidx = PQfnumber(res, "parentidx");
6954                 i_indexdef = PQfnumber(res, "indexdef");
6955                 i_indnkeyatts = PQfnumber(res, "indnkeyatts");
6956                 i_indnatts = PQfnumber(res, "indnatts");
6957                 i_indkey = PQfnumber(res, "indkey");
6958                 i_indisclustered = PQfnumber(res, "indisclustered");
6959                 i_indisreplident = PQfnumber(res, "indisreplident");
6960                 i_relpages = PQfnumber(res, "relpages");
6961                 i_contype = PQfnumber(res, "contype");
6962                 i_conname = PQfnumber(res, "conname");
6963                 i_condeferrable = PQfnumber(res, "condeferrable");
6964                 i_condeferred = PQfnumber(res, "condeferred");
6965                 i_contableoid = PQfnumber(res, "contableoid");
6966                 i_conoid = PQfnumber(res, "conoid");
6967                 i_condef = PQfnumber(res, "condef");
6968                 i_tablespace = PQfnumber(res, "tablespace");
6969                 i_indreloptions = PQfnumber(res, "indreloptions");
6970
6971                 tbinfo->indexes = indxinfo =
6972                         (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
6973                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
6974                 tbinfo->numIndexes = ntups;
6975
6976                 for (j = 0; j < ntups; j++)
6977                 {
6978                         char            contype;
6979
6980                         indxinfo[j].dobj.objType = DO_INDEX;
6981                         indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
6982                         indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
6983                         AssignDumpId(&indxinfo[j].dobj);
6984                         indxinfo[j].dobj.dump = tbinfo->dobj.dump;
6985                         indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
6986                         indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6987                         indxinfo[j].indextable = tbinfo;
6988                         indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
6989                         indxinfo[j].indnkeyattrs = atoi(PQgetvalue(res, j, i_indnkeyatts));
6990                         indxinfo[j].indnattrs = atoi(PQgetvalue(res, j, i_indnatts));
6991                         indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
6992                         indxinfo[j].indreloptions = pg_strdup(PQgetvalue(res, j, i_indreloptions));
6993                         indxinfo[j].indkeys = (Oid *) pg_malloc(indxinfo[j].indnattrs * sizeof(Oid));
6994                         parseOidArray(PQgetvalue(res, j, i_indkey),
6995                                                   indxinfo[j].indkeys, indxinfo[j].indnattrs);
6996                         indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
6997                         indxinfo[j].indisreplident = (PQgetvalue(res, j, i_indisreplident)[0] == 't');
6998                         indxinfo[j].parentidx = atooid(PQgetvalue(res, j, i_parentidx));
6999                         indxinfo[j].relpages = atoi(PQgetvalue(res, j, i_relpages));
7000                         contype = *(PQgetvalue(res, j, i_contype));
7001
7002                         if (contype == 'p' || contype == 'u' || contype == 'x')
7003                         {
7004                                 /*
7005                                  * If we found a constraint matching the index, create an
7006                                  * entry for it.
7007                                  */
7008                                 constrinfo[j].dobj.objType = DO_CONSTRAINT;
7009                                 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
7010                                 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7011                                 AssignDumpId(&constrinfo[j].dobj);
7012                                 constrinfo[j].dobj.dump = tbinfo->dobj.dump;
7013                                 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7014                                 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7015                                 constrinfo[j].contable = tbinfo;
7016                                 constrinfo[j].condomain = NULL;
7017                                 constrinfo[j].contype = contype;
7018                                 if (contype == 'x')
7019                                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
7020                                 else
7021                                         constrinfo[j].condef = NULL;
7022                                 constrinfo[j].confrelid = InvalidOid;
7023                                 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
7024                                 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
7025                                 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
7026                                 constrinfo[j].conislocal = true;
7027                                 constrinfo[j].separate = true;
7028
7029                                 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
7030                         }
7031                         else
7032                         {
7033                                 /* Plain secondary index */
7034                                 indxinfo[j].indexconstraint = 0;
7035                         }
7036                 }
7037
7038                 PQclear(res);
7039         }
7040
7041         destroyPQExpBuffer(query);
7042 }
7043
7044 /*
7045  * getExtendedStatistics
7046  *        get information about extended-statistics objects.
7047  *
7048  * Note: extended statistics data is not returned directly to the caller, but
7049  * it does get entered into the DumpableObject tables.
7050  */
7051 void
7052 getExtendedStatistics(Archive *fout)
7053 {
7054         PQExpBuffer query;
7055         PGresult   *res;
7056         StatsExtInfo *statsextinfo;
7057         int                     ntups;
7058         int                     i_tableoid;
7059         int                     i_oid;
7060         int                     i_stxname;
7061         int                     i_stxnamespace;
7062         int                     i_rolname;
7063         int                     i;
7064
7065         /* Extended statistics were new in v10 */
7066         if (fout->remoteVersion < 100000)
7067                 return;
7068
7069         query = createPQExpBuffer();
7070
7071         appendPQExpBuffer(query, "SELECT tableoid, oid, stxname, "
7072                                           "stxnamespace, (%s stxowner) AS rolname "
7073                                           "FROM pg_catalog.pg_statistic_ext",
7074                                           username_subquery);
7075
7076         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7077
7078         ntups = PQntuples(res);
7079
7080         i_tableoid = PQfnumber(res, "tableoid");
7081         i_oid = PQfnumber(res, "oid");
7082         i_stxname = PQfnumber(res, "stxname");
7083         i_stxnamespace = PQfnumber(res, "stxnamespace");
7084         i_rolname = PQfnumber(res, "rolname");
7085
7086         statsextinfo = (StatsExtInfo *) pg_malloc(ntups * sizeof(StatsExtInfo));
7087
7088         for (i = 0; i < ntups; i++)
7089         {
7090                 statsextinfo[i].dobj.objType = DO_STATSEXT;
7091                 statsextinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7092                 statsextinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7093                 AssignDumpId(&statsextinfo[i].dobj);
7094                 statsextinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_stxname));
7095                 statsextinfo[i].dobj.namespace =
7096                         findNamespace(fout,
7097                                                   atooid(PQgetvalue(res, i, i_stxnamespace)));
7098                 statsextinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7099
7100                 /* Decide whether we want to dump it */
7101                 selectDumpableObject(&(statsextinfo[i].dobj), fout);
7102
7103                 /* Stats objects do not currently have ACLs. */
7104                 statsextinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7105         }
7106
7107         PQclear(res);
7108         destroyPQExpBuffer(query);
7109 }
7110
7111 /*
7112  * getConstraints
7113  *
7114  * Get info about constraints on dumpable tables.
7115  *
7116  * Currently handles foreign keys only.
7117  * Unique and primary key constraints are handled with indexes,
7118  * while check constraints are processed in getTableAttrs().
7119  */
7120 void
7121 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
7122 {
7123         int                     i,
7124                                 j;
7125         ConstraintInfo *constrinfo;
7126         PQExpBuffer query;
7127         PGresult   *res;
7128         int                     i_contableoid,
7129                                 i_conoid,
7130                                 i_conname,
7131                                 i_confrelid,
7132                                 i_condef;
7133         int                     ntups;
7134
7135         query = createPQExpBuffer();
7136
7137         for (i = 0; i < numTables; i++)
7138         {
7139                 TableInfo  *tbinfo = &tblinfo[i];
7140
7141                 /*
7142                  * For partitioned tables, foreign keys have no triggers so they must
7143                  * be included anyway in case some foreign keys are defined.
7144                  */
7145                 if ((!tbinfo->hastriggers &&
7146                          tbinfo->relkind != RELKIND_PARTITIONED_TABLE) ||
7147                         !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7148                         continue;
7149
7150                 if (g_verbose)
7151                         write_msg(NULL, "reading foreign key constraints for table \"%s.%s\"\n",
7152                                           tbinfo->dobj.namespace->dobj.name,
7153                                           tbinfo->dobj.name);
7154
7155                 resetPQExpBuffer(query);
7156                 if (fout->remoteVersion >= 110000)
7157                         appendPQExpBuffer(query,
7158                                                           "SELECT tableoid, oid, conname, confrelid, "
7159                                                           "pg_catalog.pg_get_constraintdef(oid) AS condef "
7160                                                           "FROM pg_catalog.pg_constraint "
7161                                                           "WHERE conrelid = '%u'::pg_catalog.oid "
7162                                                           "AND conparentid = 0 "
7163                                                           "AND contype = 'f'",
7164                                                           tbinfo->dobj.catId.oid);
7165                 else
7166                         appendPQExpBuffer(query,
7167                                                           "SELECT tableoid, oid, conname, confrelid, "
7168                                                           "pg_catalog.pg_get_constraintdef(oid) AS condef "
7169                                                           "FROM pg_catalog.pg_constraint "
7170                                                           "WHERE conrelid = '%u'::pg_catalog.oid "
7171                                                           "AND contype = 'f'",
7172                                                           tbinfo->dobj.catId.oid);
7173                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7174
7175                 ntups = PQntuples(res);
7176
7177                 i_contableoid = PQfnumber(res, "tableoid");
7178                 i_conoid = PQfnumber(res, "oid");
7179                 i_conname = PQfnumber(res, "conname");
7180                 i_confrelid = PQfnumber(res, "confrelid");
7181                 i_condef = PQfnumber(res, "condef");
7182
7183                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7184
7185                 for (j = 0; j < ntups; j++)
7186                 {
7187                         constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
7188                         constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
7189                         constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7190                         AssignDumpId(&constrinfo[j].dobj);
7191                         constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7192                         constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7193                         constrinfo[j].contable = tbinfo;
7194                         constrinfo[j].condomain = NULL;
7195                         constrinfo[j].contype = 'f';
7196                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
7197                         constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
7198                         constrinfo[j].conindex = 0;
7199                         constrinfo[j].condeferrable = false;
7200                         constrinfo[j].condeferred = false;
7201                         constrinfo[j].conislocal = true;
7202                         constrinfo[j].separate = true;
7203                 }
7204
7205                 PQclear(res);
7206         }
7207
7208         destroyPQExpBuffer(query);
7209 }
7210
7211 /*
7212  * getDomainConstraints
7213  *
7214  * Get info about constraints on a domain.
7215  */
7216 static void
7217 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
7218 {
7219         int                     i;
7220         ConstraintInfo *constrinfo;
7221         PQExpBuffer query;
7222         PGresult   *res;
7223         int                     i_tableoid,
7224                                 i_oid,
7225                                 i_conname,
7226                                 i_consrc;
7227         int                     ntups;
7228
7229         query = createPQExpBuffer();
7230
7231         if (fout->remoteVersion >= 90100)
7232                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7233                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7234                                                   "convalidated "
7235                                                   "FROM pg_catalog.pg_constraint "
7236                                                   "WHERE contypid = '%u'::pg_catalog.oid "
7237                                                   "ORDER BY conname",
7238                                                   tyinfo->dobj.catId.oid);
7239
7240         else
7241                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7242                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7243                                                   "true as convalidated "
7244                                                   "FROM pg_catalog.pg_constraint "
7245                                                   "WHERE contypid = '%u'::pg_catalog.oid "
7246                                                   "ORDER BY conname",
7247                                                   tyinfo->dobj.catId.oid);
7248
7249         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7250
7251         ntups = PQntuples(res);
7252
7253         i_tableoid = PQfnumber(res, "tableoid");
7254         i_oid = PQfnumber(res, "oid");
7255         i_conname = PQfnumber(res, "conname");
7256         i_consrc = PQfnumber(res, "consrc");
7257
7258         constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7259
7260         tyinfo->nDomChecks = ntups;
7261         tyinfo->domChecks = constrinfo;
7262
7263         for (i = 0; i < ntups; i++)
7264         {
7265                 bool            validated = PQgetvalue(res, i, 4)[0] == 't';
7266
7267                 constrinfo[i].dobj.objType = DO_CONSTRAINT;
7268                 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7269                 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7270                 AssignDumpId(&constrinfo[i].dobj);
7271                 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
7272                 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
7273                 constrinfo[i].contable = NULL;
7274                 constrinfo[i].condomain = tyinfo;
7275                 constrinfo[i].contype = 'c';
7276                 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
7277                 constrinfo[i].confrelid = InvalidOid;
7278                 constrinfo[i].conindex = 0;
7279                 constrinfo[i].condeferrable = false;
7280                 constrinfo[i].condeferred = false;
7281                 constrinfo[i].conislocal = true;
7282
7283                 constrinfo[i].separate = !validated;
7284
7285                 /*
7286                  * Make the domain depend on the constraint, ensuring it won't be
7287                  * output till any constraint dependencies are OK.  If the constraint
7288                  * has not been validated, it's going to be dumped after the domain
7289                  * anyway, so this doesn't matter.
7290                  */
7291                 if (validated)
7292                         addObjectDependency(&tyinfo->dobj,
7293                                                                 constrinfo[i].dobj.dumpId);
7294         }
7295
7296         PQclear(res);
7297
7298         destroyPQExpBuffer(query);
7299 }
7300
7301 /*
7302  * getRules
7303  *        get basic information about every rule in the system
7304  *
7305  * numRules is set to the number of rules read in
7306  */
7307 RuleInfo *
7308 getRules(Archive *fout, int *numRules)
7309 {
7310         PGresult   *res;
7311         int                     ntups;
7312         int                     i;
7313         PQExpBuffer query = createPQExpBuffer();
7314         RuleInfo   *ruleinfo;
7315         int                     i_tableoid;
7316         int                     i_oid;
7317         int                     i_rulename;
7318         int                     i_ruletable;
7319         int                     i_ev_type;
7320         int                     i_is_instead;
7321         int                     i_ev_enabled;
7322
7323         if (fout->remoteVersion >= 80300)
7324         {
7325                 appendPQExpBufferStr(query, "SELECT "
7326                                                          "tableoid, oid, rulename, "
7327                                                          "ev_class AS ruletable, ev_type, is_instead, "
7328                                                          "ev_enabled "
7329                                                          "FROM pg_rewrite "
7330                                                          "ORDER BY oid");
7331         }
7332         else
7333         {
7334                 appendPQExpBufferStr(query, "SELECT "
7335                                                          "tableoid, oid, rulename, "
7336                                                          "ev_class AS ruletable, ev_type, is_instead, "
7337                                                          "'O'::char AS ev_enabled "
7338                                                          "FROM pg_rewrite "
7339                                                          "ORDER BY oid");
7340         }
7341
7342         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7343
7344         ntups = PQntuples(res);
7345
7346         *numRules = ntups;
7347
7348         ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
7349
7350         i_tableoid = PQfnumber(res, "tableoid");
7351         i_oid = PQfnumber(res, "oid");
7352         i_rulename = PQfnumber(res, "rulename");
7353         i_ruletable = PQfnumber(res, "ruletable");
7354         i_ev_type = PQfnumber(res, "ev_type");
7355         i_is_instead = PQfnumber(res, "is_instead");
7356         i_ev_enabled = PQfnumber(res, "ev_enabled");
7357
7358         for (i = 0; i < ntups; i++)
7359         {
7360                 Oid                     ruletableoid;
7361
7362                 ruleinfo[i].dobj.objType = DO_RULE;
7363                 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7364                 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7365                 AssignDumpId(&ruleinfo[i].dobj);
7366                 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
7367                 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
7368                 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
7369                 if (ruleinfo[i].ruletable == NULL)
7370                         exit_horribly(NULL, "failed sanity check, parent table with OID %u of pg_rewrite entry with OID %u not found\n",
7371                                                   ruletableoid, ruleinfo[i].dobj.catId.oid);
7372                 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
7373                 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
7374                 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
7375                 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
7376                 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
7377                 if (ruleinfo[i].ruletable)
7378                 {
7379                         /*
7380                          * If the table is a view or materialized view, force its ON
7381                          * SELECT rule to be sorted before the view itself --- this
7382                          * ensures that any dependencies for the rule affect the table's
7383                          * positioning. Other rules are forced to appear after their
7384                          * table.
7385                          */
7386                         if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
7387                                  ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
7388                                 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
7389                         {
7390                                 addObjectDependency(&ruleinfo[i].ruletable->dobj,
7391                                                                         ruleinfo[i].dobj.dumpId);
7392                                 /* We'll merge the rule into CREATE VIEW, if possible */
7393                                 ruleinfo[i].separate = false;
7394                         }
7395                         else
7396                         {
7397                                 addObjectDependency(&ruleinfo[i].dobj,
7398                                                                         ruleinfo[i].ruletable->dobj.dumpId);
7399                                 ruleinfo[i].separate = true;
7400                         }
7401                 }
7402                 else
7403                         ruleinfo[i].separate = true;
7404         }
7405
7406         PQclear(res);
7407
7408         destroyPQExpBuffer(query);
7409
7410         return ruleinfo;
7411 }
7412
7413 /*
7414  * getTriggers
7415  *        get information about every trigger on a dumpable table
7416  *
7417  * Note: trigger data is not returned directly to the caller, but it
7418  * does get entered into the DumpableObject tables.
7419  */
7420 void
7421 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
7422 {
7423         int                     i,
7424                                 j;
7425         PQExpBuffer query = createPQExpBuffer();
7426         PGresult   *res;
7427         TriggerInfo *tginfo;
7428         int                     i_tableoid,
7429                                 i_oid,
7430                                 i_tgname,
7431                                 i_tgfname,
7432                                 i_tgtype,
7433                                 i_tgnargs,
7434                                 i_tgargs,
7435                                 i_tgisconstraint,
7436                                 i_tgconstrname,
7437                                 i_tgconstrrelid,
7438                                 i_tgconstrrelname,
7439                                 i_tgenabled,
7440                                 i_tgdeferrable,
7441                                 i_tginitdeferred,
7442                                 i_tgdef;
7443         int                     ntups;
7444
7445         for (i = 0; i < numTables; i++)
7446         {
7447                 TableInfo  *tbinfo = &tblinfo[i];
7448
7449                 if (!tbinfo->hastriggers ||
7450                         !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7451                         continue;
7452
7453                 if (g_verbose)
7454                         write_msg(NULL, "reading triggers for table \"%s.%s\"\n",
7455                                           tbinfo->dobj.namespace->dobj.name,
7456                                           tbinfo->dobj.name);
7457
7458                 resetPQExpBuffer(query);
7459                 if (fout->remoteVersion >= 90000)
7460                 {
7461                         /*
7462                          * NB: think not to use pretty=true in pg_get_triggerdef.  It
7463                          * could result in non-forward-compatible dumps of WHEN clauses
7464                          * due to under-parenthesization.
7465                          */
7466                         appendPQExpBuffer(query,
7467                                                           "SELECT tgname, "
7468                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
7469                                                           "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
7470                                                           "tgenabled, tableoid, oid "
7471                                                           "FROM pg_catalog.pg_trigger t "
7472                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
7473                                                           "AND NOT tgisinternal",
7474                                                           tbinfo->dobj.catId.oid);
7475                 }
7476                 else if (fout->remoteVersion >= 80300)
7477                 {
7478                         /*
7479                          * We ignore triggers that are tied to a foreign-key constraint
7480                          */
7481                         appendPQExpBuffer(query,
7482                                                           "SELECT tgname, "
7483                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
7484                                                           "tgtype, tgnargs, tgargs, tgenabled, "
7485                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
7486                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
7487                                                           "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7488                                                           "FROM pg_catalog.pg_trigger t "
7489                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
7490                                                           "AND tgconstraint = 0",
7491                                                           tbinfo->dobj.catId.oid);
7492                 }
7493                 else
7494                 {
7495                         /*
7496                          * We ignore triggers that are tied to a foreign-key constraint,
7497                          * but in these versions we have to grovel through pg_constraint
7498                          * to find out
7499                          */
7500                         appendPQExpBuffer(query,
7501                                                           "SELECT tgname, "
7502                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
7503                                                           "tgtype, tgnargs, tgargs, tgenabled, "
7504                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
7505                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
7506                                                           "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7507                                                           "FROM pg_catalog.pg_trigger t "
7508                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
7509                                                           "AND (NOT tgisconstraint "
7510                                                           " OR NOT EXISTS"
7511                                                           "  (SELECT 1 FROM pg_catalog.pg_depend d "
7512                                                           "   JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
7513                                                           "   WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
7514                                                           tbinfo->dobj.catId.oid);
7515                 }
7516
7517                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7518
7519                 ntups = PQntuples(res);
7520
7521                 i_tableoid = PQfnumber(res, "tableoid");
7522                 i_oid = PQfnumber(res, "oid");
7523                 i_tgname = PQfnumber(res, "tgname");
7524                 i_tgfname = PQfnumber(res, "tgfname");
7525                 i_tgtype = PQfnumber(res, "tgtype");
7526                 i_tgnargs = PQfnumber(res, "tgnargs");
7527                 i_tgargs = PQfnumber(res, "tgargs");
7528                 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
7529                 i_tgconstrname = PQfnumber(res, "tgconstrname");
7530                 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
7531                 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
7532                 i_tgenabled = PQfnumber(res, "tgenabled");
7533                 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
7534                 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
7535                 i_tgdef = PQfnumber(res, "tgdef");
7536
7537                 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
7538
7539                 tbinfo->numTriggers = ntups;
7540                 tbinfo->triggers = tginfo;
7541
7542                 for (j = 0; j < ntups; j++)
7543                 {
7544                         tginfo[j].dobj.objType = DO_TRIGGER;
7545                         tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
7546                         tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
7547                         AssignDumpId(&tginfo[j].dobj);
7548                         tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
7549                         tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
7550                         tginfo[j].tgtable = tbinfo;
7551                         tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
7552                         if (i_tgdef >= 0)
7553                         {
7554                                 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
7555
7556                                 /* remaining fields are not valid if we have tgdef */
7557                                 tginfo[j].tgfname = NULL;
7558                                 tginfo[j].tgtype = 0;
7559                                 tginfo[j].tgnargs = 0;
7560                                 tginfo[j].tgargs = NULL;
7561                                 tginfo[j].tgisconstraint = false;
7562                                 tginfo[j].tgdeferrable = false;
7563                                 tginfo[j].tginitdeferred = false;
7564                                 tginfo[j].tgconstrname = NULL;
7565                                 tginfo[j].tgconstrrelid = InvalidOid;
7566                                 tginfo[j].tgconstrrelname = NULL;
7567                         }
7568                         else
7569                         {
7570                                 tginfo[j].tgdef = NULL;
7571
7572                                 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
7573                                 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
7574                                 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
7575                                 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
7576                                 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
7577                                 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
7578                                 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
7579
7580                                 if (tginfo[j].tgisconstraint)
7581                                 {
7582                                         tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
7583                                         tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
7584                                         if (OidIsValid(tginfo[j].tgconstrrelid))
7585                                         {
7586                                                 if (PQgetisnull(res, j, i_tgconstrrelname))
7587                                                         exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
7588                                                                                   tginfo[j].dobj.name,
7589                                                                                   tbinfo->dobj.name,
7590                                                                                   tginfo[j].tgconstrrelid);
7591                                                 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
7592                                         }
7593                                         else
7594                                                 tginfo[j].tgconstrrelname = NULL;
7595                                 }
7596                                 else
7597                                 {
7598                                         tginfo[j].tgconstrname = NULL;
7599                                         tginfo[j].tgconstrrelid = InvalidOid;
7600                                         tginfo[j].tgconstrrelname = NULL;
7601                                 }
7602                         }
7603                 }
7604
7605                 PQclear(res);
7606         }
7607
7608         destroyPQExpBuffer(query);
7609 }
7610
7611 /*
7612  * getEventTriggers
7613  *        get information about event triggers
7614  */
7615 EventTriggerInfo *
7616 getEventTriggers(Archive *fout, int *numEventTriggers)
7617 {
7618         int                     i;
7619         PQExpBuffer query;
7620         PGresult   *res;
7621         EventTriggerInfo *evtinfo;
7622         int                     i_tableoid,
7623                                 i_oid,
7624                                 i_evtname,
7625                                 i_evtevent,
7626                                 i_evtowner,
7627                                 i_evttags,
7628                                 i_evtfname,
7629                                 i_evtenabled;
7630         int                     ntups;
7631
7632         /* Before 9.3, there are no event triggers */
7633         if (fout->remoteVersion < 90300)
7634         {
7635                 *numEventTriggers = 0;
7636                 return NULL;
7637         }
7638
7639         query = createPQExpBuffer();
7640
7641         appendPQExpBuffer(query,
7642                                           "SELECT e.tableoid, e.oid, evtname, evtenabled, "
7643                                           "evtevent, (%s evtowner) AS evtowner, "
7644                                           "array_to_string(array("
7645                                           "select quote_literal(x) "
7646                                           " from unnest(evttags) as t(x)), ', ') as evttags, "
7647                                           "e.evtfoid::regproc as evtfname "
7648                                           "FROM pg_event_trigger e "
7649                                           "ORDER BY e.oid",
7650                                           username_subquery);
7651
7652         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7653
7654         ntups = PQntuples(res);
7655
7656         *numEventTriggers = ntups;
7657
7658         evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
7659
7660         i_tableoid = PQfnumber(res, "tableoid");
7661         i_oid = PQfnumber(res, "oid");
7662         i_evtname = PQfnumber(res, "evtname");
7663         i_evtevent = PQfnumber(res, "evtevent");
7664         i_evtowner = PQfnumber(res, "evtowner");
7665         i_evttags = PQfnumber(res, "evttags");
7666         i_evtfname = PQfnumber(res, "evtfname");
7667         i_evtenabled = PQfnumber(res, "evtenabled");
7668
7669         for (i = 0; i < ntups; i++)
7670         {
7671                 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
7672                 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7673                 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7674                 AssignDumpId(&evtinfo[i].dobj);
7675                 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
7676                 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
7677                 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
7678                 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
7679                 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
7680                 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
7681                 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
7682
7683                 /* Decide whether we want to dump it */
7684                 selectDumpableObject(&(evtinfo[i].dobj), fout);
7685
7686                 /* Event Triggers do not currently have ACLs. */
7687                 evtinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7688         }
7689
7690         PQclear(res);
7691
7692         destroyPQExpBuffer(query);
7693
7694         return evtinfo;
7695 }
7696
7697 /*
7698  * getProcLangs
7699  *        get basic information about every procedural language in the system
7700  *
7701  * numProcLangs is set to the number of langs read in
7702  *
7703  * NB: this must run after getFuncs() because we assume we can do
7704  * findFuncByOid().
7705  */
7706 ProcLangInfo *
7707 getProcLangs(Archive *fout, int *numProcLangs)
7708 {
7709         DumpOptions *dopt = fout->dopt;
7710         PGresult   *res;
7711         int                     ntups;
7712         int                     i;
7713         PQExpBuffer query = createPQExpBuffer();
7714         ProcLangInfo *planginfo;
7715         int                     i_tableoid;
7716         int                     i_oid;
7717         int                     i_lanname;
7718         int                     i_lanpltrusted;
7719         int                     i_lanplcallfoid;
7720         int                     i_laninline;
7721         int                     i_lanvalidator;
7722         int                     i_lanacl;
7723         int                     i_rlanacl;
7724         int                     i_initlanacl;
7725         int                     i_initrlanacl;
7726         int                     i_lanowner;
7727
7728         if (fout->remoteVersion >= 90600)
7729         {
7730                 PQExpBuffer acl_subquery = createPQExpBuffer();
7731                 PQExpBuffer racl_subquery = createPQExpBuffer();
7732                 PQExpBuffer initacl_subquery = createPQExpBuffer();
7733                 PQExpBuffer initracl_subquery = createPQExpBuffer();
7734
7735                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
7736                                                 initracl_subquery, "l.lanacl", "l.lanowner", "'l'",
7737                                                 dopt->binary_upgrade);
7738
7739                 /* pg_language has a laninline column */
7740                 appendPQExpBuffer(query, "SELECT l.tableoid, l.oid, "
7741                                                   "l.lanname, l.lanpltrusted, l.lanplcallfoid, "
7742                                                   "l.laninline, l.lanvalidator, "
7743                                                   "%s AS lanacl, "
7744                                                   "%s AS rlanacl, "
7745                                                   "%s AS initlanacl, "
7746                                                   "%s AS initrlanacl, "
7747                                                   "(%s l.lanowner) AS lanowner "
7748                                                   "FROM pg_language l "
7749                                                   "LEFT JOIN pg_init_privs pip ON "
7750                                                   "(l.oid = pip.objoid "
7751                                                   "AND pip.classoid = 'pg_language'::regclass "
7752                                                   "AND pip.objsubid = 0) "
7753                                                   "WHERE l.lanispl "
7754                                                   "ORDER BY l.oid",
7755                                                   acl_subquery->data,
7756                                                   racl_subquery->data,
7757                                                   initacl_subquery->data,
7758                                                   initracl_subquery->data,
7759                                                   username_subquery);
7760
7761                 destroyPQExpBuffer(acl_subquery);
7762                 destroyPQExpBuffer(racl_subquery);
7763                 destroyPQExpBuffer(initacl_subquery);
7764                 destroyPQExpBuffer(initracl_subquery);
7765         }
7766         else if (fout->remoteVersion >= 90000)
7767         {
7768                 /* pg_language has a laninline column */
7769                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7770                                                   "lanname, lanpltrusted, lanplcallfoid, "
7771                                                   "laninline, lanvalidator, lanacl, NULL AS rlanacl, "
7772                                                   "NULL AS initlanacl, NULL AS initrlanacl, "
7773                                                   "(%s lanowner) AS lanowner "
7774                                                   "FROM pg_language "
7775                                                   "WHERE lanispl "
7776                                                   "ORDER BY oid",
7777                                                   username_subquery);
7778         }
7779         else if (fout->remoteVersion >= 80300)
7780         {
7781                 /* pg_language has a lanowner column */
7782                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7783                                                   "lanname, lanpltrusted, lanplcallfoid, "
7784                                                   "0 AS laninline, lanvalidator, lanacl, "
7785                                                   "NULL AS rlanacl, "
7786                                                   "NULL AS initlanacl, NULL AS initrlanacl, "
7787                                                   "(%s lanowner) AS lanowner "
7788                                                   "FROM pg_language "
7789                                                   "WHERE lanispl "
7790                                                   "ORDER BY oid",
7791                                                   username_subquery);
7792         }
7793         else if (fout->remoteVersion >= 80100)
7794         {
7795                 /* Languages are owned by the bootstrap superuser, OID 10 */
7796                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7797                                                   "lanname, lanpltrusted, lanplcallfoid, "
7798                                                   "0 AS laninline, lanvalidator, lanacl, "
7799                                                   "NULL AS rlanacl, "
7800                                                   "NULL AS initlanacl, NULL AS initrlanacl, "
7801                                                   "(%s '10') AS lanowner "
7802                                                   "FROM pg_language "
7803                                                   "WHERE lanispl "
7804                                                   "ORDER BY oid",
7805                                                   username_subquery);
7806         }
7807         else
7808         {
7809                 /* Languages are owned by the bootstrap superuser, sysid 1 */
7810                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7811                                                   "lanname, lanpltrusted, lanplcallfoid, "
7812                                                   "0 AS laninline, lanvalidator, lanacl, "
7813                                                   "NULL AS rlanacl, "
7814                                                   "NULL AS initlanacl, NULL AS initrlanacl, "
7815                                                   "(%s '1') AS lanowner "
7816                                                   "FROM pg_language "
7817                                                   "WHERE lanispl "
7818                                                   "ORDER BY oid",
7819                                                   username_subquery);
7820         }
7821
7822         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7823
7824         ntups = PQntuples(res);
7825
7826         *numProcLangs = ntups;
7827
7828         planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
7829
7830         i_tableoid = PQfnumber(res, "tableoid");
7831         i_oid = PQfnumber(res, "oid");
7832         i_lanname = PQfnumber(res, "lanname");
7833         i_lanpltrusted = PQfnumber(res, "lanpltrusted");
7834         i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
7835         i_laninline = PQfnumber(res, "laninline");
7836         i_lanvalidator = PQfnumber(res, "lanvalidator");
7837         i_lanacl = PQfnumber(res, "lanacl");
7838         i_rlanacl = PQfnumber(res, "rlanacl");
7839         i_initlanacl = PQfnumber(res, "initlanacl");
7840         i_initrlanacl = PQfnumber(res, "initrlanacl");
7841         i_lanowner = PQfnumber(res, "lanowner");
7842
7843         for (i = 0; i < ntups; i++)
7844         {
7845                 planginfo[i].dobj.objType = DO_PROCLANG;
7846                 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7847                 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7848                 AssignDumpId(&planginfo[i].dobj);
7849
7850                 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
7851                 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
7852                 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
7853                 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
7854                 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
7855                 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
7856                 planginfo[i].rlanacl = pg_strdup(PQgetvalue(res, i, i_rlanacl));
7857                 planginfo[i].initlanacl = pg_strdup(PQgetvalue(res, i, i_initlanacl));
7858                 planginfo[i].initrlanacl = pg_strdup(PQgetvalue(res, i, i_initrlanacl));
7859                 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
7860
7861                 /* Decide whether we want to dump it */
7862                 selectDumpableProcLang(&(planginfo[i]), fout);
7863
7864                 /* Do not try to dump ACL if no ACL exists. */
7865                 if (PQgetisnull(res, i, i_lanacl) && PQgetisnull(res, i, i_rlanacl) &&
7866                         PQgetisnull(res, i, i_initlanacl) &&
7867                         PQgetisnull(res, i, i_initrlanacl))
7868                         planginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7869         }
7870
7871         PQclear(res);
7872
7873         destroyPQExpBuffer(query);
7874
7875         return planginfo;
7876 }
7877
7878 /*
7879  * getCasts
7880  *        get basic information about every cast in the system
7881  *
7882  * numCasts is set to the number of casts read in
7883  */
7884 CastInfo *
7885 getCasts(Archive *fout, int *numCasts)
7886 {
7887         PGresult   *res;
7888         int                     ntups;
7889         int                     i;
7890         PQExpBuffer query = createPQExpBuffer();
7891         CastInfo   *castinfo;
7892         int                     i_tableoid;
7893         int                     i_oid;
7894         int                     i_castsource;
7895         int                     i_casttarget;
7896         int                     i_castfunc;
7897         int                     i_castcontext;
7898         int                     i_castmethod;
7899
7900         if (fout->remoteVersion >= 80400)
7901         {
7902                 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7903                                                          "castsource, casttarget, castfunc, castcontext, "
7904                                                          "castmethod "
7905                                                          "FROM pg_cast ORDER BY 3,4");
7906         }
7907         else
7908         {
7909                 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7910                                                          "castsource, casttarget, castfunc, castcontext, "
7911                                                          "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
7912                                                          "FROM pg_cast ORDER BY 3,4");
7913         }
7914
7915         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7916
7917         ntups = PQntuples(res);
7918
7919         *numCasts = ntups;
7920
7921         castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
7922
7923         i_tableoid = PQfnumber(res, "tableoid");
7924         i_oid = PQfnumber(res, "oid");
7925         i_castsource = PQfnumber(res, "castsource");
7926         i_casttarget = PQfnumber(res, "casttarget");
7927         i_castfunc = PQfnumber(res, "castfunc");
7928         i_castcontext = PQfnumber(res, "castcontext");
7929         i_castmethod = PQfnumber(res, "castmethod");
7930
7931         for (i = 0; i < ntups; i++)
7932         {
7933                 PQExpBufferData namebuf;
7934                 TypeInfo   *sTypeInfo;
7935                 TypeInfo   *tTypeInfo;
7936
7937                 castinfo[i].dobj.objType = DO_CAST;
7938                 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7939                 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7940                 AssignDumpId(&castinfo[i].dobj);
7941                 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
7942                 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
7943                 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
7944                 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
7945                 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
7946
7947                 /*
7948                  * Try to name cast as concatenation of typnames.  This is only used
7949                  * for purposes of sorting.  If we fail to find either type, the name
7950                  * will be an empty string.
7951                  */
7952                 initPQExpBuffer(&namebuf);
7953                 sTypeInfo = findTypeByOid(castinfo[i].castsource);
7954                 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
7955                 if (sTypeInfo && tTypeInfo)
7956                         appendPQExpBuffer(&namebuf, "%s %s",
7957                                                           sTypeInfo->dobj.name, tTypeInfo->dobj.name);
7958                 castinfo[i].dobj.name = namebuf.data;
7959
7960                 /* Decide whether we want to dump it */
7961                 selectDumpableCast(&(castinfo[i]), fout);
7962
7963                 /* Casts do not currently have ACLs. */
7964                 castinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7965         }
7966
7967         PQclear(res);
7968
7969         destroyPQExpBuffer(query);
7970
7971         return castinfo;
7972 }
7973
7974 static char *
7975 get_language_name(Archive *fout, Oid langid)
7976 {
7977         PQExpBuffer query;
7978         PGresult   *res;
7979         char       *lanname;
7980
7981         query = createPQExpBuffer();
7982         appendPQExpBuffer(query, "SELECT lanname FROM pg_language WHERE oid = %u", langid);
7983         res = ExecuteSqlQueryForSingleRow(fout, query->data);
7984         lanname = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
7985         destroyPQExpBuffer(query);
7986         PQclear(res);
7987
7988         return lanname;
7989 }
7990
7991 /*
7992  * getTransforms
7993  *        get basic information about every transform in the system
7994  *
7995  * numTransforms is set to the number of transforms read in
7996  */
7997 TransformInfo *
7998 getTransforms(Archive *fout, int *numTransforms)
7999 {
8000         PGresult   *res;
8001         int                     ntups;
8002         int                     i;
8003         PQExpBuffer query;
8004         TransformInfo *transforminfo;
8005         int                     i_tableoid;
8006         int                     i_oid;
8007         int                     i_trftype;
8008         int                     i_trflang;
8009         int                     i_trffromsql;
8010         int                     i_trftosql;
8011
8012         /* Transforms didn't exist pre-9.5 */
8013         if (fout->remoteVersion < 90500)
8014         {
8015                 *numTransforms = 0;
8016                 return NULL;
8017         }
8018
8019         query = createPQExpBuffer();
8020
8021         appendPQExpBuffer(query, "SELECT tableoid, oid, "
8022                                           "trftype, trflang, trffromsql::oid, trftosql::oid "
8023                                           "FROM pg_transform "
8024                                           "ORDER BY 3,4");
8025
8026         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8027
8028         ntups = PQntuples(res);
8029
8030         *numTransforms = ntups;
8031
8032         transforminfo = (TransformInfo *) pg_malloc(ntups * sizeof(TransformInfo));
8033
8034         i_tableoid = PQfnumber(res, "tableoid");
8035         i_oid = PQfnumber(res, "oid");
8036         i_trftype = PQfnumber(res, "trftype");
8037         i_trflang = PQfnumber(res, "trflang");
8038         i_trffromsql = PQfnumber(res, "trffromsql");
8039         i_trftosql = PQfnumber(res, "trftosql");
8040
8041         for (i = 0; i < ntups; i++)
8042         {
8043                 PQExpBufferData namebuf;
8044                 TypeInfo   *typeInfo;
8045                 char       *lanname;
8046
8047                 transforminfo[i].dobj.objType = DO_TRANSFORM;
8048                 transforminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8049                 transforminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8050                 AssignDumpId(&transforminfo[i].dobj);
8051                 transforminfo[i].trftype = atooid(PQgetvalue(res, i, i_trftype));
8052                 transforminfo[i].trflang = atooid(PQgetvalue(res, i, i_trflang));
8053                 transforminfo[i].trffromsql = atooid(PQgetvalue(res, i, i_trffromsql));
8054                 transforminfo[i].trftosql = atooid(PQgetvalue(res, i, i_trftosql));
8055
8056                 /*
8057                  * Try to name transform as concatenation of type and language name.
8058                  * This is only used for purposes of sorting.  If we fail to find
8059                  * either, the name will be an empty string.
8060                  */
8061                 initPQExpBuffer(&namebuf);
8062                 typeInfo = findTypeByOid(transforminfo[i].trftype);
8063                 lanname = get_language_name(fout, transforminfo[i].trflang);
8064                 if (typeInfo && lanname)
8065                         appendPQExpBuffer(&namebuf, "%s %s",
8066                                                           typeInfo->dobj.name, lanname);
8067                 transforminfo[i].dobj.name = namebuf.data;
8068                 free(lanname);
8069
8070                 /* Decide whether we want to dump it */
8071                 selectDumpableObject(&(transforminfo[i].dobj), fout);
8072         }
8073
8074         PQclear(res);
8075
8076         destroyPQExpBuffer(query);
8077
8078         return transforminfo;
8079 }
8080
8081 /*
8082  * getTableAttrs -
8083  *        for each interesting table, read info about its attributes
8084  *        (names, types, default values, CHECK constraints, etc)
8085  *
8086  * This is implemented in a very inefficient way right now, looping
8087  * through the tblinfo and doing a join per table to find the attrs and their
8088  * types.  However, because we want type names and so forth to be named
8089  * relative to the schema of each table, we couldn't do it in just one
8090  * query.  (Maybe one query per schema?)
8091  *
8092  *      modifies tblinfo
8093  */
8094 void
8095 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
8096 {
8097         DumpOptions *dopt = fout->dopt;
8098         int                     i,
8099                                 j;
8100         PQExpBuffer q = createPQExpBuffer();
8101         int                     i_attnum;
8102         int                     i_attname;
8103         int                     i_atttypname;
8104         int                     i_atttypmod;
8105         int                     i_attstattarget;
8106         int                     i_attstorage;
8107         int                     i_typstorage;
8108         int                     i_attnotnull;
8109         int                     i_atthasdef;
8110         int                     i_attidentity;
8111         int                     i_attisdropped;
8112         int                     i_attlen;
8113         int                     i_attalign;
8114         int                     i_attislocal;
8115         int                     i_attoptions;
8116         int                     i_attcollation;
8117         int                     i_attfdwoptions;
8118         int                     i_attmissingval;
8119         PGresult   *res;
8120         int                     ntups;
8121         bool            hasdefaults;
8122
8123         for (i = 0; i < numTables; i++)
8124         {
8125                 TableInfo  *tbinfo = &tblinfo[i];
8126
8127                 /* Don't bother to collect info for sequences */
8128                 if (tbinfo->relkind == RELKIND_SEQUENCE)
8129                         continue;
8130
8131                 /* Don't bother with uninteresting tables, either */
8132                 if (!tbinfo->interesting)
8133                         continue;
8134
8135                 /* find all the user attributes and their types */
8136
8137                 /*
8138                  * we must read the attribute names in attribute number order! because
8139                  * we will use the attnum to index into the attnames array later.
8140                  */
8141                 if (g_verbose)
8142                         write_msg(NULL, "finding the columns and types of table \"%s.%s\"\n",
8143                                           tbinfo->dobj.namespace->dobj.name,
8144                                           tbinfo->dobj.name);
8145
8146                 resetPQExpBuffer(q);
8147
8148                 if (fout->remoteVersion >= 110000)
8149                 {
8150                         /* atthasmissing and attmissingval are new in 11 */
8151                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8152                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8153                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8154                                                           "a.attlen, a.attalign, a.attislocal, "
8155                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8156                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
8157                                                           "CASE WHEN a.attcollation <> t.typcollation "
8158                                                           "THEN a.attcollation ELSE 0 END AS attcollation, "
8159                                                           "a.attidentity, "
8160                                                           "pg_catalog.array_to_string(ARRAY("
8161                                                           "SELECT pg_catalog.quote_ident(option_name) || "
8162                                                           "' ' || pg_catalog.quote_literal(option_value) "
8163                                                           "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8164                                                           "ORDER BY option_name"
8165                                                           "), E',\n    ') AS attfdwoptions ,"
8166                                                           "CASE WHEN a.atthasmissing AND NOT a.attisdropped "
8167                                                           "THEN a.attmissingval ELSE null END AS attmissingval "
8168                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8169                                                           "ON a.atttypid = t.oid "
8170                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8171                                                           "AND a.attnum > 0::pg_catalog.int2 "
8172                                                           "ORDER BY a.attnum",
8173                                                           tbinfo->dobj.catId.oid);
8174                 }
8175                 else if (fout->remoteVersion >= 100000)
8176                 {
8177                         /*
8178                          * attidentity is new in version 10.
8179                          */
8180                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8181                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8182                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8183                                                           "a.attlen, a.attalign, a.attislocal, "
8184                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8185                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
8186                                                           "CASE WHEN a.attcollation <> t.typcollation "
8187                                                           "THEN a.attcollation ELSE 0 END AS attcollation, "
8188                                                           "a.attidentity, "
8189                                                           "pg_catalog.array_to_string(ARRAY("
8190                                                           "SELECT pg_catalog.quote_ident(option_name) || "
8191                                                           "' ' || pg_catalog.quote_literal(option_value) "
8192                                                           "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8193                                                           "ORDER BY option_name"
8194                                                           "), E',\n    ') AS attfdwoptions ,"
8195                                                           "NULL as attmissingval "
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 >= 90200)
8204                 {
8205                         /*
8206                          * attfdwoptions is new in 9.2.
8207                          */
8208                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8209                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8210                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8211                                                           "a.attlen, a.attalign, a.attislocal, "
8212                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8213                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
8214                                                           "CASE WHEN a.attcollation <> t.typcollation "
8215                                                           "THEN a.attcollation ELSE 0 END AS attcollation, "
8216                                                           "pg_catalog.array_to_string(ARRAY("
8217                                                           "SELECT pg_catalog.quote_ident(option_name) || "
8218                                                           "' ' || pg_catalog.quote_literal(option_value) "
8219                                                           "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8220                                                           "ORDER BY option_name"
8221                                                           "), E',\n    ') AS attfdwoptions, "
8222                                                           "NULL as attmissingval "
8223                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8224                                                           "ON a.atttypid = t.oid "
8225                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8226                                                           "AND a.attnum > 0::pg_catalog.int2 "
8227                                                           "ORDER BY a.attnum",
8228                                                           tbinfo->dobj.catId.oid);
8229                 }
8230                 else if (fout->remoteVersion >= 90100)
8231                 {
8232                         /*
8233                          * attcollation is new in 9.1.  Since we only want to dump COLLATE
8234                          * clauses for attributes whose collation is different from their
8235                          * type's default, we use a CASE here to suppress uninteresting
8236                          * attcollations cheaply.
8237                          */
8238                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8239                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8240                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8241                                                           "a.attlen, a.attalign, a.attislocal, "
8242                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8243                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
8244                                                           "CASE WHEN a.attcollation <> t.typcollation "
8245                                                           "THEN a.attcollation ELSE 0 END AS attcollation, "
8246                                                           "NULL AS attfdwoptions, "
8247                                                           "NULL as attmissingval "
8248                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8249                                                           "ON a.atttypid = t.oid "
8250                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8251                                                           "AND a.attnum > 0::pg_catalog.int2 "
8252                                                           "ORDER BY a.attnum",
8253                                                           tbinfo->dobj.catId.oid);
8254                 }
8255                 else if (fout->remoteVersion >= 90000)
8256                 {
8257                         /* attoptions is new in 9.0 */
8258                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8259                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8260                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8261                                                           "a.attlen, a.attalign, a.attislocal, "
8262                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8263                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
8264                                                           "0 AS attcollation, "
8265                                                           "NULL AS attfdwoptions, "
8266                                                           "NULL as attmissingval "
8267                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8268                                                           "ON a.atttypid = t.oid "
8269                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8270                                                           "AND a.attnum > 0::pg_catalog.int2 "
8271                                                           "ORDER BY a.attnum",
8272                                                           tbinfo->dobj.catId.oid);
8273                 }
8274                 else
8275                 {
8276                         /* need left join here to not fail on dropped columns ... */
8277                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8278                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8279                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8280                                                           "a.attlen, a.attalign, a.attislocal, "
8281                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8282                                                           "'' AS attoptions, 0 AS attcollation, "
8283                                                           "NULL AS attfdwoptions, "
8284                                                           "NULL as attmissingval "
8285                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8286                                                           "ON a.atttypid = t.oid "
8287                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8288                                                           "AND a.attnum > 0::pg_catalog.int2 "
8289                                                           "ORDER BY a.attnum",
8290                                                           tbinfo->dobj.catId.oid);
8291                 }
8292
8293                 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8294
8295                 ntups = PQntuples(res);
8296
8297                 i_attnum = PQfnumber(res, "attnum");
8298                 i_attname = PQfnumber(res, "attname");
8299                 i_atttypname = PQfnumber(res, "atttypname");
8300                 i_atttypmod = PQfnumber(res, "atttypmod");
8301                 i_attstattarget = PQfnumber(res, "attstattarget");
8302                 i_attstorage = PQfnumber(res, "attstorage");
8303                 i_typstorage = PQfnumber(res, "typstorage");
8304                 i_attnotnull = PQfnumber(res, "attnotnull");
8305                 i_atthasdef = PQfnumber(res, "atthasdef");
8306                 i_attidentity = PQfnumber(res, "attidentity");
8307                 i_attisdropped = PQfnumber(res, "attisdropped");
8308                 i_attlen = PQfnumber(res, "attlen");
8309                 i_attalign = PQfnumber(res, "attalign");
8310                 i_attislocal = PQfnumber(res, "attislocal");
8311                 i_attoptions = PQfnumber(res, "attoptions");
8312                 i_attcollation = PQfnumber(res, "attcollation");
8313                 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
8314                 i_attmissingval = PQfnumber(res, "attmissingval");
8315
8316                 tbinfo->numatts = ntups;
8317                 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
8318                 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
8319                 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
8320                 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
8321                 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
8322                 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
8323                 tbinfo->attidentity = (char *) pg_malloc(ntups * sizeof(char));
8324                 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
8325                 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
8326                 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
8327                 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
8328                 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
8329                 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
8330                 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
8331                 tbinfo->attmissingval = (char **) pg_malloc(ntups * sizeof(char *));
8332                 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
8333                 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
8334                 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
8335                 hasdefaults = false;
8336
8337                 for (j = 0; j < ntups; j++)
8338                 {
8339                         if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
8340                                 exit_horribly(NULL,
8341                                                           "invalid column numbering in table \"%s\"\n",
8342                                                           tbinfo->dobj.name);
8343                         tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
8344                         tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
8345                         tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
8346                         tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
8347                         tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
8348                         tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
8349                         tbinfo->attidentity[j] = (i_attidentity >= 0 ? *(PQgetvalue(res, j, i_attidentity)) : '\0');
8350                         tbinfo->needs_override = tbinfo->needs_override || (tbinfo->attidentity[j] == ATTRIBUTE_IDENTITY_ALWAYS);
8351                         tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
8352                         tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
8353                         tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
8354                         tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
8355                         tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
8356                         tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
8357                         tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
8358                         tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
8359                         tbinfo->attmissingval[j] = pg_strdup(PQgetvalue(res, j, i_attmissingval));
8360                         tbinfo->attrdefs[j] = NULL; /* fix below */
8361                         if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
8362                                 hasdefaults = true;
8363                         /* these flags will be set in flagInhAttrs() */
8364                         tbinfo->inhNotNull[j] = false;
8365                 }
8366
8367                 PQclear(res);
8368
8369                 /*
8370                  * Get info about column defaults
8371                  */
8372                 if (hasdefaults)
8373                 {
8374                         AttrDefInfo *attrdefs;
8375                         int                     numDefaults;
8376
8377                         if (g_verbose)
8378                                 write_msg(NULL, "finding default expressions of table \"%s.%s\"\n",
8379                                                   tbinfo->dobj.namespace->dobj.name,
8380                                                   tbinfo->dobj.name);
8381
8382                         printfPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
8383                                                           "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
8384                                                           "FROM pg_catalog.pg_attrdef "
8385                                                           "WHERE adrelid = '%u'::pg_catalog.oid",
8386                                                           tbinfo->dobj.catId.oid);
8387
8388                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8389
8390                         numDefaults = PQntuples(res);
8391                         attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
8392
8393                         for (j = 0; j < numDefaults; j++)
8394                         {
8395                                 int                     adnum;
8396
8397                                 adnum = atoi(PQgetvalue(res, j, 2));
8398
8399                                 if (adnum <= 0 || adnum > ntups)
8400                                         exit_horribly(NULL,
8401                                                                   "invalid adnum value %d for table \"%s\"\n",
8402                                                                   adnum, tbinfo->dobj.name);
8403
8404                                 /*
8405                                  * dropped columns shouldn't have defaults, but just in case,
8406                                  * ignore 'em
8407                                  */
8408                                 if (tbinfo->attisdropped[adnum - 1])
8409                                         continue;
8410
8411                                 attrdefs[j].dobj.objType = DO_ATTRDEF;
8412                                 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8413                                 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8414                                 AssignDumpId(&attrdefs[j].dobj);
8415                                 attrdefs[j].adtable = tbinfo;
8416                                 attrdefs[j].adnum = adnum;
8417                                 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
8418
8419                                 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
8420                                 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
8421
8422                                 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
8423
8424                                 /*
8425                                  * Defaults on a VIEW must always be dumped as separate ALTER
8426                                  * TABLE commands.  Defaults on regular tables are dumped as
8427                                  * part of the CREATE TABLE if possible, which it won't be if
8428                                  * the column is not going to be emitted explicitly.
8429                                  */
8430                                 if (tbinfo->relkind == RELKIND_VIEW)
8431                                 {
8432                                         attrdefs[j].separate = true;
8433                                 }
8434                                 else if (!shouldPrintColumn(dopt, tbinfo, adnum - 1))
8435                                 {
8436                                         /* column will be suppressed, print default separately */
8437                                         attrdefs[j].separate = true;
8438                                 }
8439                                 else
8440                                 {
8441                                         attrdefs[j].separate = false;
8442
8443                                         /*
8444                                          * Mark the default as needing to appear before the table,
8445                                          * so that any dependencies it has must be emitted before
8446                                          * the CREATE TABLE.  If this is not possible, we'll
8447                                          * change to "separate" mode while sorting dependencies.
8448                                          */
8449                                         addObjectDependency(&tbinfo->dobj,
8450                                                                                 attrdefs[j].dobj.dumpId);
8451                                 }
8452
8453                                 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
8454                         }
8455                         PQclear(res);
8456                 }
8457
8458                 /*
8459                  * Get info about table CHECK constraints
8460                  */
8461                 if (tbinfo->ncheck > 0)
8462                 {
8463                         ConstraintInfo *constrs;
8464                         int                     numConstrs;
8465
8466                         if (g_verbose)
8467                                 write_msg(NULL, "finding check constraints for table \"%s.%s\"\n",
8468                                                   tbinfo->dobj.namespace->dobj.name,
8469                                                   tbinfo->dobj.name);
8470
8471                         resetPQExpBuffer(q);
8472                         if (fout->remoteVersion >= 90200)
8473                         {
8474                                 /*
8475                                  * convalidated is new in 9.2 (actually, it is there in 9.1,
8476                                  * but it wasn't ever false for check constraints until 9.2).
8477                                  */
8478                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8479                                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8480                                                                   "conislocal, convalidated "
8481                                                                   "FROM pg_catalog.pg_constraint "
8482                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
8483                                                                   "   AND contype = 'c' "
8484                                                                   "ORDER BY conname",
8485                                                                   tbinfo->dobj.catId.oid);
8486                         }
8487                         else if (fout->remoteVersion >= 80400)
8488                         {
8489                                 /* conislocal is new in 8.4 */
8490                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8491                                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8492                                                                   "conislocal, true AS convalidated "
8493                                                                   "FROM pg_catalog.pg_constraint "
8494                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
8495                                                                   "   AND contype = 'c' "
8496                                                                   "ORDER BY conname",
8497                                                                   tbinfo->dobj.catId.oid);
8498                         }
8499                         else
8500                         {
8501                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8502                                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8503                                                                   "true AS conislocal, true AS convalidated "
8504                                                                   "FROM pg_catalog.pg_constraint "
8505                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
8506                                                                   "   AND contype = 'c' "
8507                                                                   "ORDER BY conname",
8508                                                                   tbinfo->dobj.catId.oid);
8509                         }
8510
8511                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8512
8513                         numConstrs = PQntuples(res);
8514                         if (numConstrs != tbinfo->ncheck)
8515                         {
8516                                 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
8517                                                                                  "expected %d check constraints on table \"%s\" but found %d\n",
8518                                                                                  tbinfo->ncheck),
8519                                                   tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
8520                                 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
8521                                 exit_nicely(1);
8522                         }
8523
8524                         constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
8525                         tbinfo->checkexprs = constrs;
8526
8527                         for (j = 0; j < numConstrs; j++)
8528                         {
8529                                 bool            validated = PQgetvalue(res, j, 5)[0] == 't';
8530
8531                                 constrs[j].dobj.objType = DO_CONSTRAINT;
8532                                 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8533                                 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8534                                 AssignDumpId(&constrs[j].dobj);
8535                                 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
8536                                 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
8537                                 constrs[j].contable = tbinfo;
8538                                 constrs[j].condomain = NULL;
8539                                 constrs[j].contype = 'c';
8540                                 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
8541                                 constrs[j].confrelid = InvalidOid;
8542                                 constrs[j].conindex = 0;
8543                                 constrs[j].condeferrable = false;
8544                                 constrs[j].condeferred = false;
8545                                 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
8546
8547                                 /*
8548                                  * An unvalidated constraint needs to be dumped separately, so
8549                                  * that potentially-violating existing data is loaded before
8550                                  * the constraint.
8551                                  */
8552                                 constrs[j].separate = !validated;
8553
8554                                 constrs[j].dobj.dump = tbinfo->dobj.dump;
8555
8556                                 /*
8557                                  * Mark the constraint as needing to appear before the table
8558                                  * --- this is so that any other dependencies of the
8559                                  * constraint will be emitted before we try to create the
8560                                  * table.  If the constraint is to be dumped separately, it
8561                                  * will be dumped after data is loaded anyway, so don't do it.
8562                                  * (There's an automatic dependency in the opposite direction
8563                                  * anyway, so don't need to add one manually here.)
8564                                  */
8565                                 if (!constrs[j].separate)
8566                                         addObjectDependency(&tbinfo->dobj,
8567                                                                                 constrs[j].dobj.dumpId);
8568
8569                                 /*
8570                                  * If the constraint is inherited, this will be detected later
8571                                  * (in pre-8.4 databases).  We also detect later if the
8572                                  * constraint must be split out from the table definition.
8573                                  */
8574                         }
8575                         PQclear(res);
8576                 }
8577         }
8578
8579         destroyPQExpBuffer(q);
8580 }
8581
8582 /*
8583  * Test whether a column should be printed as part of table's CREATE TABLE.
8584  * Column number is zero-based.
8585  *
8586  * Normally this is always true, but it's false for dropped columns, as well
8587  * as those that were inherited without any local definition.  (If we print
8588  * such a column it will mistakenly get pg_attribute.attislocal set to true.)
8589  * However, in binary_upgrade mode, we must print all such columns anyway and
8590  * fix the attislocal/attisdropped state later, so as to keep control of the
8591  * physical column order.
8592  *
8593  * This function exists because there are scattered nonobvious places that
8594  * must be kept in sync with this decision.
8595  */
8596 bool
8597 shouldPrintColumn(DumpOptions *dopt, TableInfo *tbinfo, int colno)
8598 {
8599         if (dopt->binary_upgrade)
8600                 return true;
8601         return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
8602 }
8603
8604
8605 /*
8606  * getTSParsers:
8607  *        read all text search parsers in the system catalogs and return them
8608  *        in the TSParserInfo* structure
8609  *
8610  *      numTSParsers is set to the number of parsers read in
8611  */
8612 TSParserInfo *
8613 getTSParsers(Archive *fout, int *numTSParsers)
8614 {
8615         PGresult   *res;
8616         int                     ntups;
8617         int                     i;
8618         PQExpBuffer query;
8619         TSParserInfo *prsinfo;
8620         int                     i_tableoid;
8621         int                     i_oid;
8622         int                     i_prsname;
8623         int                     i_prsnamespace;
8624         int                     i_prsstart;
8625         int                     i_prstoken;
8626         int                     i_prsend;
8627         int                     i_prsheadline;
8628         int                     i_prslextype;
8629
8630         /* Before 8.3, there is no built-in text search support */
8631         if (fout->remoteVersion < 80300)
8632         {
8633                 *numTSParsers = 0;
8634                 return NULL;
8635         }
8636
8637         query = createPQExpBuffer();
8638
8639         /*
8640          * find all text search objects, including builtin ones; we filter out
8641          * system-defined objects at dump-out time.
8642          */
8643
8644         appendPQExpBufferStr(query, "SELECT tableoid, oid, prsname, prsnamespace, "
8645                                                  "prsstart::oid, prstoken::oid, "
8646                                                  "prsend::oid, prsheadline::oid, prslextype::oid "
8647                                                  "FROM pg_ts_parser");
8648
8649         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8650
8651         ntups = PQntuples(res);
8652         *numTSParsers = ntups;
8653
8654         prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
8655
8656         i_tableoid = PQfnumber(res, "tableoid");
8657         i_oid = PQfnumber(res, "oid");
8658         i_prsname = PQfnumber(res, "prsname");
8659         i_prsnamespace = PQfnumber(res, "prsnamespace");
8660         i_prsstart = PQfnumber(res, "prsstart");
8661         i_prstoken = PQfnumber(res, "prstoken");
8662         i_prsend = PQfnumber(res, "prsend");
8663         i_prsheadline = PQfnumber(res, "prsheadline");
8664         i_prslextype = PQfnumber(res, "prslextype");
8665
8666         for (i = 0; i < ntups; i++)
8667         {
8668                 prsinfo[i].dobj.objType = DO_TSPARSER;
8669                 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8670                 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8671                 AssignDumpId(&prsinfo[i].dobj);
8672                 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
8673                 prsinfo[i].dobj.namespace =
8674                         findNamespace(fout,
8675                                                   atooid(PQgetvalue(res, i, i_prsnamespace)));
8676                 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
8677                 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
8678                 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
8679                 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
8680                 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
8681
8682                 /* Decide whether we want to dump it */
8683                 selectDumpableObject(&(prsinfo[i].dobj), fout);
8684
8685                 /* Text Search Parsers do not currently have ACLs. */
8686                 prsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8687         }
8688
8689         PQclear(res);
8690
8691         destroyPQExpBuffer(query);
8692
8693         return prsinfo;
8694 }
8695
8696 /*
8697  * getTSDictionaries:
8698  *        read all text search dictionaries in the system catalogs and return them
8699  *        in the TSDictInfo* structure
8700  *
8701  *      numTSDicts is set to the number of dictionaries read in
8702  */
8703 TSDictInfo *
8704 getTSDictionaries(Archive *fout, int *numTSDicts)
8705 {
8706         PGresult   *res;
8707         int                     ntups;
8708         int                     i;
8709         PQExpBuffer query;
8710         TSDictInfo *dictinfo;
8711         int                     i_tableoid;
8712         int                     i_oid;
8713         int                     i_dictname;
8714         int                     i_dictnamespace;
8715         int                     i_rolname;
8716         int                     i_dicttemplate;
8717         int                     i_dictinitoption;
8718
8719         /* Before 8.3, there is no built-in text search support */
8720         if (fout->remoteVersion < 80300)
8721         {
8722                 *numTSDicts = 0;
8723                 return NULL;
8724         }
8725
8726         query = createPQExpBuffer();
8727
8728         appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
8729                                           "dictnamespace, (%s dictowner) AS rolname, "
8730                                           "dicttemplate, dictinitoption "
8731                                           "FROM pg_ts_dict",
8732                                           username_subquery);
8733
8734         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8735
8736         ntups = PQntuples(res);
8737         *numTSDicts = ntups;
8738
8739         dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
8740
8741         i_tableoid = PQfnumber(res, "tableoid");
8742         i_oid = PQfnumber(res, "oid");
8743         i_dictname = PQfnumber(res, "dictname");
8744         i_dictnamespace = PQfnumber(res, "dictnamespace");
8745         i_rolname = PQfnumber(res, "rolname");
8746         i_dictinitoption = PQfnumber(res, "dictinitoption");
8747         i_dicttemplate = PQfnumber(res, "dicttemplate");
8748
8749         for (i = 0; i < ntups; i++)
8750         {
8751                 dictinfo[i].dobj.objType = DO_TSDICT;
8752                 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8753                 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8754                 AssignDumpId(&dictinfo[i].dobj);
8755                 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
8756                 dictinfo[i].dobj.namespace =
8757                         findNamespace(fout,
8758                                                   atooid(PQgetvalue(res, i, i_dictnamespace)));
8759                 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8760                 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
8761                 if (PQgetisnull(res, i, i_dictinitoption))
8762                         dictinfo[i].dictinitoption = NULL;
8763                 else
8764                         dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
8765
8766                 /* Decide whether we want to dump it */
8767                 selectDumpableObject(&(dictinfo[i].dobj), fout);
8768
8769                 /* Text Search Dictionaries do not currently have ACLs. */
8770                 dictinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8771         }
8772
8773         PQclear(res);
8774
8775         destroyPQExpBuffer(query);
8776
8777         return dictinfo;
8778 }
8779
8780 /*
8781  * getTSTemplates:
8782  *        read all text search templates in the system catalogs and return them
8783  *        in the TSTemplateInfo* structure
8784  *
8785  *      numTSTemplates is set to the number of templates read in
8786  */
8787 TSTemplateInfo *
8788 getTSTemplates(Archive *fout, int *numTSTemplates)
8789 {
8790         PGresult   *res;
8791         int                     ntups;
8792         int                     i;
8793         PQExpBuffer query;
8794         TSTemplateInfo *tmplinfo;
8795         int                     i_tableoid;
8796         int                     i_oid;
8797         int                     i_tmplname;
8798         int                     i_tmplnamespace;
8799         int                     i_tmplinit;
8800         int                     i_tmpllexize;
8801
8802         /* Before 8.3, there is no built-in text search support */
8803         if (fout->remoteVersion < 80300)
8804         {
8805                 *numTSTemplates = 0;
8806                 return NULL;
8807         }
8808
8809         query = createPQExpBuffer();
8810
8811         appendPQExpBufferStr(query, "SELECT tableoid, oid, tmplname, "
8812                                                  "tmplnamespace, tmplinit::oid, tmpllexize::oid "
8813                                                  "FROM pg_ts_template");
8814
8815         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8816
8817         ntups = PQntuples(res);
8818         *numTSTemplates = ntups;
8819
8820         tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
8821
8822         i_tableoid = PQfnumber(res, "tableoid");
8823         i_oid = PQfnumber(res, "oid");
8824         i_tmplname = PQfnumber(res, "tmplname");
8825         i_tmplnamespace = PQfnumber(res, "tmplnamespace");
8826         i_tmplinit = PQfnumber(res, "tmplinit");
8827         i_tmpllexize = PQfnumber(res, "tmpllexize");
8828
8829         for (i = 0; i < ntups; i++)
8830         {
8831                 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
8832                 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8833                 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8834                 AssignDumpId(&tmplinfo[i].dobj);
8835                 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
8836                 tmplinfo[i].dobj.namespace =
8837                         findNamespace(fout,
8838                                                   atooid(PQgetvalue(res, i, i_tmplnamespace)));
8839                 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
8840                 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
8841
8842                 /* Decide whether we want to dump it */
8843                 selectDumpableObject(&(tmplinfo[i].dobj), fout);
8844
8845                 /* Text Search Templates do not currently have ACLs. */
8846                 tmplinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8847         }
8848
8849         PQclear(res);
8850
8851         destroyPQExpBuffer(query);
8852
8853         return tmplinfo;
8854 }
8855
8856 /*
8857  * getTSConfigurations:
8858  *        read all text search configurations in the system catalogs and return
8859  *        them in the TSConfigInfo* structure
8860  *
8861  *      numTSConfigs is set to the number of configurations read in
8862  */
8863 TSConfigInfo *
8864 getTSConfigurations(Archive *fout, int *numTSConfigs)
8865 {
8866         PGresult   *res;
8867         int                     ntups;
8868         int                     i;
8869         PQExpBuffer query;
8870         TSConfigInfo *cfginfo;
8871         int                     i_tableoid;
8872         int                     i_oid;
8873         int                     i_cfgname;
8874         int                     i_cfgnamespace;
8875         int                     i_rolname;
8876         int                     i_cfgparser;
8877
8878         /* Before 8.3, there is no built-in text search support */
8879         if (fout->remoteVersion < 80300)
8880         {
8881                 *numTSConfigs = 0;
8882                 return NULL;
8883         }
8884
8885         query = createPQExpBuffer();
8886
8887         appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
8888                                           "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
8889                                           "FROM pg_ts_config",
8890                                           username_subquery);
8891
8892         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8893
8894         ntups = PQntuples(res);
8895         *numTSConfigs = ntups;
8896
8897         cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
8898
8899         i_tableoid = PQfnumber(res, "tableoid");
8900         i_oid = PQfnumber(res, "oid");
8901         i_cfgname = PQfnumber(res, "cfgname");
8902         i_cfgnamespace = PQfnumber(res, "cfgnamespace");
8903         i_rolname = PQfnumber(res, "rolname");
8904         i_cfgparser = PQfnumber(res, "cfgparser");
8905
8906         for (i = 0; i < ntups; i++)
8907         {
8908                 cfginfo[i].dobj.objType = DO_TSCONFIG;
8909                 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8910                 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8911                 AssignDumpId(&cfginfo[i].dobj);
8912                 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
8913                 cfginfo[i].dobj.namespace =
8914                         findNamespace(fout,
8915                                                   atooid(PQgetvalue(res, i, i_cfgnamespace)));
8916                 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8917                 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
8918
8919                 /* Decide whether we want to dump it */
8920                 selectDumpableObject(&(cfginfo[i].dobj), fout);
8921
8922                 /* Text Search Configurations do not currently have ACLs. */
8923                 cfginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8924         }
8925
8926         PQclear(res);
8927
8928         destroyPQExpBuffer(query);
8929
8930         return cfginfo;
8931 }
8932
8933 /*
8934  * getForeignDataWrappers:
8935  *        read all foreign-data wrappers in the system catalogs and return
8936  *        them in the FdwInfo* structure
8937  *
8938  *      numForeignDataWrappers is set to the number of fdws read in
8939  */
8940 FdwInfo *
8941 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
8942 {
8943         DumpOptions *dopt = fout->dopt;
8944         PGresult   *res;
8945         int                     ntups;
8946         int                     i;
8947         PQExpBuffer query;
8948         FdwInfo    *fdwinfo;
8949         int                     i_tableoid;
8950         int                     i_oid;
8951         int                     i_fdwname;
8952         int                     i_rolname;
8953         int                     i_fdwhandler;
8954         int                     i_fdwvalidator;
8955         int                     i_fdwacl;
8956         int                     i_rfdwacl;
8957         int                     i_initfdwacl;
8958         int                     i_initrfdwacl;
8959         int                     i_fdwoptions;
8960
8961         /* Before 8.4, there are no foreign-data wrappers */
8962         if (fout->remoteVersion < 80400)
8963         {
8964                 *numForeignDataWrappers = 0;
8965                 return NULL;
8966         }
8967
8968         query = createPQExpBuffer();
8969
8970         if (fout->remoteVersion >= 90600)
8971         {
8972                 PQExpBuffer acl_subquery = createPQExpBuffer();
8973                 PQExpBuffer racl_subquery = createPQExpBuffer();
8974                 PQExpBuffer initacl_subquery = createPQExpBuffer();
8975                 PQExpBuffer initracl_subquery = createPQExpBuffer();
8976
8977                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
8978                                                 initracl_subquery, "f.fdwacl", "f.fdwowner", "'F'",
8979                                                 dopt->binary_upgrade);
8980
8981                 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.fdwname, "
8982                                                   "(%s f.fdwowner) AS rolname, "
8983                                                   "f.fdwhandler::pg_catalog.regproc, "
8984                                                   "f.fdwvalidator::pg_catalog.regproc, "
8985                                                   "%s AS fdwacl, "
8986                                                   "%s AS rfdwacl, "
8987                                                   "%s AS initfdwacl, "
8988                                                   "%s AS initrfdwacl, "
8989                                                   "array_to_string(ARRAY("
8990                                                   "SELECT quote_ident(option_name) || ' ' || "
8991                                                   "quote_literal(option_value) "
8992                                                   "FROM pg_options_to_table(f.fdwoptions) "
8993                                                   "ORDER BY option_name"
8994                                                   "), E',\n    ') AS fdwoptions "
8995                                                   "FROM pg_foreign_data_wrapper f "
8996                                                   "LEFT JOIN pg_init_privs pip ON "
8997                                                   "(f.oid = pip.objoid "
8998                                                   "AND pip.classoid = 'pg_foreign_data_wrapper'::regclass "
8999                                                   "AND pip.objsubid = 0) ",
9000                                                   username_subquery,
9001                                                   acl_subquery->data,
9002                                                   racl_subquery->data,
9003                                                   initacl_subquery->data,
9004                                                   initracl_subquery->data);
9005
9006                 destroyPQExpBuffer(acl_subquery);
9007                 destroyPQExpBuffer(racl_subquery);
9008                 destroyPQExpBuffer(initacl_subquery);
9009                 destroyPQExpBuffer(initracl_subquery);
9010         }
9011         else if (fout->remoteVersion >= 90100)
9012         {
9013                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
9014                                                   "(%s fdwowner) AS rolname, "
9015                                                   "fdwhandler::pg_catalog.regproc, "
9016                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
9017                                                   "NULL as rfdwacl, "
9018                                                   "NULL as initfdwacl, NULL AS initrfdwacl, "
9019                                                   "array_to_string(ARRAY("
9020                                                   "SELECT quote_ident(option_name) || ' ' || "
9021                                                   "quote_literal(option_value) "
9022                                                   "FROM pg_options_to_table(fdwoptions) "
9023                                                   "ORDER BY option_name"
9024                                                   "), E',\n    ') AS fdwoptions "
9025                                                   "FROM pg_foreign_data_wrapper",
9026                                                   username_subquery);
9027         }
9028         else
9029         {
9030                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
9031                                                   "(%s fdwowner) AS rolname, "
9032                                                   "'-' AS fdwhandler, "
9033                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
9034                                                   "NULL as rfdwacl, "
9035                                                   "NULL as initfdwacl, NULL AS initrfdwacl, "
9036                                                   "array_to_string(ARRAY("
9037                                                   "SELECT quote_ident(option_name) || ' ' || "
9038                                                   "quote_literal(option_value) "
9039                                                   "FROM pg_options_to_table(fdwoptions) "
9040                                                   "ORDER BY option_name"
9041                                                   "), E',\n    ') AS fdwoptions "
9042                                                   "FROM pg_foreign_data_wrapper",
9043                                                   username_subquery);
9044         }
9045
9046         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9047
9048         ntups = PQntuples(res);
9049         *numForeignDataWrappers = ntups;
9050
9051         fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
9052
9053         i_tableoid = PQfnumber(res, "tableoid");
9054         i_oid = PQfnumber(res, "oid");
9055         i_fdwname = PQfnumber(res, "fdwname");
9056         i_rolname = PQfnumber(res, "rolname");
9057         i_fdwhandler = PQfnumber(res, "fdwhandler");
9058         i_fdwvalidator = PQfnumber(res, "fdwvalidator");
9059         i_fdwacl = PQfnumber(res, "fdwacl");
9060         i_rfdwacl = PQfnumber(res, "rfdwacl");
9061         i_initfdwacl = PQfnumber(res, "initfdwacl");
9062         i_initrfdwacl = PQfnumber(res, "initrfdwacl");
9063         i_fdwoptions = PQfnumber(res, "fdwoptions");
9064
9065         for (i = 0; i < ntups; i++)
9066         {
9067                 fdwinfo[i].dobj.objType = DO_FDW;
9068                 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9069                 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9070                 AssignDumpId(&fdwinfo[i].dobj);
9071                 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
9072                 fdwinfo[i].dobj.namespace = NULL;
9073                 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
9074                 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
9075                 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
9076                 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
9077                 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
9078                 fdwinfo[i].rfdwacl = pg_strdup(PQgetvalue(res, i, i_rfdwacl));
9079                 fdwinfo[i].initfdwacl = pg_strdup(PQgetvalue(res, i, i_initfdwacl));
9080                 fdwinfo[i].initrfdwacl = pg_strdup(PQgetvalue(res, i, i_initrfdwacl));
9081
9082                 /* Decide whether we want to dump it */
9083                 selectDumpableObject(&(fdwinfo[i].dobj), fout);
9084
9085                 /* Do not try to dump ACL if no ACL exists. */
9086                 if (PQgetisnull(res, i, i_fdwacl) && PQgetisnull(res, i, i_rfdwacl) &&
9087                         PQgetisnull(res, i, i_initfdwacl) &&
9088                         PQgetisnull(res, i, i_initrfdwacl))
9089                         fdwinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9090         }
9091
9092         PQclear(res);
9093
9094         destroyPQExpBuffer(query);
9095
9096         return fdwinfo;
9097 }
9098
9099 /*
9100  * getForeignServers:
9101  *        read all foreign servers in the system catalogs and return
9102  *        them in the ForeignServerInfo * structure
9103  *
9104  *      numForeignServers is set to the number of servers read in
9105  */
9106 ForeignServerInfo *
9107 getForeignServers(Archive *fout, int *numForeignServers)
9108 {
9109         DumpOptions *dopt = fout->dopt;
9110         PGresult   *res;
9111         int                     ntups;
9112         int                     i;
9113         PQExpBuffer query;
9114         ForeignServerInfo *srvinfo;
9115         int                     i_tableoid;
9116         int                     i_oid;
9117         int                     i_srvname;
9118         int                     i_rolname;
9119         int                     i_srvfdw;
9120         int                     i_srvtype;
9121         int                     i_srvversion;
9122         int                     i_srvacl;
9123         int                     i_rsrvacl;
9124         int                     i_initsrvacl;
9125         int                     i_initrsrvacl;
9126         int                     i_srvoptions;
9127
9128         /* Before 8.4, there are no foreign servers */
9129         if (fout->remoteVersion < 80400)
9130         {
9131                 *numForeignServers = 0;
9132                 return NULL;
9133         }
9134
9135         query = createPQExpBuffer();
9136
9137         if (fout->remoteVersion >= 90600)
9138         {
9139                 PQExpBuffer acl_subquery = createPQExpBuffer();
9140                 PQExpBuffer racl_subquery = createPQExpBuffer();
9141                 PQExpBuffer initacl_subquery = createPQExpBuffer();
9142                 PQExpBuffer initracl_subquery = createPQExpBuffer();
9143
9144                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9145                                                 initracl_subquery, "f.srvacl", "f.srvowner", "'S'",
9146                                                 dopt->binary_upgrade);
9147
9148                 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.srvname, "
9149                                                   "(%s f.srvowner) AS rolname, "
9150                                                   "f.srvfdw, f.srvtype, f.srvversion, "
9151                                                   "%s AS srvacl, "
9152                                                   "%s AS rsrvacl, "
9153                                                   "%s AS initsrvacl, "
9154                                                   "%s AS initrsrvacl, "
9155                                                   "array_to_string(ARRAY("
9156                                                   "SELECT quote_ident(option_name) || ' ' || "
9157                                                   "quote_literal(option_value) "
9158                                                   "FROM pg_options_to_table(f.srvoptions) "
9159                                                   "ORDER BY option_name"
9160                                                   "), E',\n    ') AS srvoptions "
9161                                                   "FROM pg_foreign_server f "
9162                                                   "LEFT JOIN pg_init_privs pip "
9163                                                   "ON (f.oid = pip.objoid "
9164                                                   "AND pip.classoid = 'pg_foreign_server'::regclass "
9165                                                   "AND pip.objsubid = 0) ",
9166                                                   username_subquery,
9167                                                   acl_subquery->data,
9168                                                   racl_subquery->data,
9169                                                   initacl_subquery->data,
9170                                                   initracl_subquery->data);
9171
9172                 destroyPQExpBuffer(acl_subquery);
9173                 destroyPQExpBuffer(racl_subquery);
9174                 destroyPQExpBuffer(initacl_subquery);
9175                 destroyPQExpBuffer(initracl_subquery);
9176         }
9177         else
9178         {
9179                 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
9180                                                   "(%s srvowner) AS rolname, "
9181                                                   "srvfdw, srvtype, srvversion, srvacl, "
9182                                                   "NULL AS rsrvacl, "
9183                                                   "NULL AS initsrvacl, NULL AS initrsrvacl, "
9184                                                   "array_to_string(ARRAY("
9185                                                   "SELECT quote_ident(option_name) || ' ' || "
9186                                                   "quote_literal(option_value) "
9187                                                   "FROM pg_options_to_table(srvoptions) "
9188                                                   "ORDER BY option_name"
9189                                                   "), E',\n    ') AS srvoptions "
9190                                                   "FROM pg_foreign_server",
9191                                                   username_subquery);
9192         }
9193
9194         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9195
9196         ntups = PQntuples(res);
9197         *numForeignServers = ntups;
9198
9199         srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
9200
9201         i_tableoid = PQfnumber(res, "tableoid");
9202         i_oid = PQfnumber(res, "oid");
9203         i_srvname = PQfnumber(res, "srvname");
9204         i_rolname = PQfnumber(res, "rolname");
9205         i_srvfdw = PQfnumber(res, "srvfdw");
9206         i_srvtype = PQfnumber(res, "srvtype");
9207         i_srvversion = PQfnumber(res, "srvversion");
9208         i_srvacl = PQfnumber(res, "srvacl");
9209         i_rsrvacl = PQfnumber(res, "rsrvacl");
9210         i_initsrvacl = PQfnumber(res, "initsrvacl");
9211         i_initrsrvacl = PQfnumber(res, "initrsrvacl");
9212         i_srvoptions = PQfnumber(res, "srvoptions");
9213
9214         for (i = 0; i < ntups; i++)
9215         {
9216                 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
9217                 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9218                 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9219                 AssignDumpId(&srvinfo[i].dobj);
9220                 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
9221                 srvinfo[i].dobj.namespace = NULL;
9222                 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
9223                 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
9224                 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
9225                 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
9226                 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
9227                 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
9228                 srvinfo[i].rsrvacl = pg_strdup(PQgetvalue(res, i, i_rsrvacl));
9229                 srvinfo[i].initsrvacl = pg_strdup(PQgetvalue(res, i, i_initsrvacl));
9230                 srvinfo[i].initrsrvacl = pg_strdup(PQgetvalue(res, i, i_initrsrvacl));
9231
9232                 /* Decide whether we want to dump it */
9233                 selectDumpableObject(&(srvinfo[i].dobj), fout);
9234
9235                 /* Do not try to dump ACL if no ACL exists. */
9236                 if (PQgetisnull(res, i, i_srvacl) && PQgetisnull(res, i, i_rsrvacl) &&
9237                         PQgetisnull(res, i, i_initsrvacl) &&
9238                         PQgetisnull(res, i, i_initrsrvacl))
9239                         srvinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9240         }
9241
9242         PQclear(res);
9243
9244         destroyPQExpBuffer(query);
9245
9246         return srvinfo;
9247 }
9248
9249 /*
9250  * getDefaultACLs:
9251  *        read all default ACL information in the system catalogs and return
9252  *        them in the DefaultACLInfo structure
9253  *
9254  *      numDefaultACLs is set to the number of ACLs read in
9255  */
9256 DefaultACLInfo *
9257 getDefaultACLs(Archive *fout, int *numDefaultACLs)
9258 {
9259         DumpOptions *dopt = fout->dopt;
9260         DefaultACLInfo *daclinfo;
9261         PQExpBuffer query;
9262         PGresult   *res;
9263         int                     i_oid;
9264         int                     i_tableoid;
9265         int                     i_defaclrole;
9266         int                     i_defaclnamespace;
9267         int                     i_defaclobjtype;
9268         int                     i_defaclacl;
9269         int                     i_rdefaclacl;
9270         int                     i_initdefaclacl;
9271         int                     i_initrdefaclacl;
9272         int                     i,
9273                                 ntups;
9274
9275         if (fout->remoteVersion < 90000)
9276         {
9277                 *numDefaultACLs = 0;
9278                 return NULL;
9279         }
9280
9281         query = createPQExpBuffer();
9282
9283         if (fout->remoteVersion >= 90600)
9284         {
9285                 PQExpBuffer acl_subquery = createPQExpBuffer();
9286                 PQExpBuffer racl_subquery = createPQExpBuffer();
9287                 PQExpBuffer initacl_subquery = createPQExpBuffer();
9288                 PQExpBuffer initracl_subquery = createPQExpBuffer();
9289
9290                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9291                                                 initracl_subquery, "defaclacl", "defaclrole",
9292                                                 "CASE WHEN defaclobjtype = 'S' THEN 's' ELSE defaclobjtype END::\"char\"",
9293                                                 dopt->binary_upgrade);
9294
9295                 appendPQExpBuffer(query, "SELECT d.oid, d.tableoid, "
9296                                                   "(%s d.defaclrole) AS defaclrole, "
9297                                                   "d.defaclnamespace, "
9298                                                   "d.defaclobjtype, "
9299                                                   "%s AS defaclacl, "
9300                                                   "%s AS rdefaclacl, "
9301                                                   "%s AS initdefaclacl, "
9302                                                   "%s AS initrdefaclacl "
9303                                                   "FROM pg_default_acl d "
9304                                                   "LEFT JOIN pg_init_privs pip ON "
9305                                                   "(d.oid = pip.objoid "
9306                                                   "AND pip.classoid = 'pg_default_acl'::regclass "
9307                                                   "AND pip.objsubid = 0) ",
9308                                                   username_subquery,
9309                                                   acl_subquery->data,
9310                                                   racl_subquery->data,
9311                                                   initacl_subquery->data,
9312                                                   initracl_subquery->data);
9313         }
9314         else
9315         {
9316                 appendPQExpBuffer(query, "SELECT oid, tableoid, "
9317                                                   "(%s defaclrole) AS defaclrole, "
9318                                                   "defaclnamespace, "
9319                                                   "defaclobjtype, "
9320                                                   "defaclacl, "
9321                                                   "NULL AS rdefaclacl, "
9322                                                   "NULL AS initdefaclacl, "
9323                                                   "NULL AS initrdefaclacl "
9324                                                   "FROM pg_default_acl",
9325                                                   username_subquery);
9326         }
9327
9328         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9329
9330         ntups = PQntuples(res);
9331         *numDefaultACLs = ntups;
9332
9333         daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
9334
9335         i_oid = PQfnumber(res, "oid");
9336         i_tableoid = PQfnumber(res, "tableoid");
9337         i_defaclrole = PQfnumber(res, "defaclrole");
9338         i_defaclnamespace = PQfnumber(res, "defaclnamespace");
9339         i_defaclobjtype = PQfnumber(res, "defaclobjtype");
9340         i_defaclacl = PQfnumber(res, "defaclacl");
9341         i_rdefaclacl = PQfnumber(res, "rdefaclacl");
9342         i_initdefaclacl = PQfnumber(res, "initdefaclacl");
9343         i_initrdefaclacl = PQfnumber(res, "initrdefaclacl");
9344
9345         for (i = 0; i < ntups; i++)
9346         {
9347                 Oid                     nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
9348
9349                 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
9350                 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9351                 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9352                 AssignDumpId(&daclinfo[i].dobj);
9353                 /* cheesy ... is it worth coming up with a better object name? */
9354                 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
9355
9356                 if (nspid != InvalidOid)
9357                         daclinfo[i].dobj.namespace = findNamespace(fout, nspid);
9358                 else
9359                         daclinfo[i].dobj.namespace = NULL;
9360
9361                 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
9362                 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
9363                 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
9364                 daclinfo[i].rdefaclacl = pg_strdup(PQgetvalue(res, i, i_rdefaclacl));
9365                 daclinfo[i].initdefaclacl = pg_strdup(PQgetvalue(res, i, i_initdefaclacl));
9366                 daclinfo[i].initrdefaclacl = pg_strdup(PQgetvalue(res, i, i_initrdefaclacl));
9367
9368                 /* Decide whether we want to dump it */
9369                 selectDumpableDefaultACL(&(daclinfo[i]), dopt);
9370         }
9371
9372         PQclear(res);
9373
9374         destroyPQExpBuffer(query);
9375
9376         return daclinfo;
9377 }
9378
9379 /*
9380  * dumpComment --
9381  *
9382  * This routine is used to dump any comments associated with the
9383  * object handed to this routine. The routine takes the object type
9384  * and object name (ready to print, except for schema decoration), plus
9385  * the namespace and owner of the object (for labeling the ArchiveEntry),
9386  * plus catalog ID and subid which are the lookup key for pg_description,
9387  * plus the dump ID for the object (for setting a dependency).
9388  * If a matching pg_description entry is found, it is dumped.
9389  *
9390  * Note: in some cases, such as comments for triggers and rules, the "type"
9391  * string really looks like, e.g., "TRIGGER name ON".  This is a bit of a hack
9392  * but it doesn't seem worth complicating the API for all callers to make
9393  * it cleaner.
9394  *
9395  * Note: although this routine takes a dumpId for dependency purposes,
9396  * that purpose is just to mark the dependency in the emitted dump file
9397  * for possible future use by pg_restore.  We do NOT use it for determining
9398  * ordering of the comment in the dump file, because this routine is called
9399  * after dependency sorting occurs.  This routine should be called just after
9400  * calling ArchiveEntry() for the specified object.
9401  */
9402 static void
9403 dumpComment(Archive *fout, const char *type, const char *name,
9404                         const char *namespace, const char *owner,
9405                         CatalogId catalogId, int subid, DumpId dumpId)
9406 {
9407         DumpOptions *dopt = fout->dopt;
9408         CommentItem *comments;
9409         int                     ncomments;
9410
9411         /* do nothing, if --no-comments is supplied */
9412         if (dopt->no_comments)
9413                 return;
9414
9415         /* Comments are schema not data ... except blob comments are data */
9416         if (strcmp(type, "LARGE OBJECT") != 0)
9417         {
9418                 if (dopt->dataOnly)
9419                         return;
9420         }
9421         else
9422         {
9423                 /* We do dump blob comments in binary-upgrade mode */
9424                 if (dopt->schemaOnly && !dopt->binary_upgrade)
9425                         return;
9426         }
9427
9428         /* Search for comments associated with catalogId, using table */
9429         ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
9430                                                          &comments);
9431
9432         /* Is there one matching the subid? */
9433         while (ncomments > 0)
9434         {
9435                 if (comments->objsubid == subid)
9436                         break;
9437                 comments++;
9438                 ncomments--;
9439         }
9440
9441         /* If a comment exists, build COMMENT ON statement */
9442         if (ncomments > 0)
9443         {
9444                 PQExpBuffer query = createPQExpBuffer();
9445                 PQExpBuffer tag = createPQExpBuffer();
9446
9447                 appendPQExpBuffer(query, "COMMENT ON %s ", type);
9448                 if (namespace && *namespace)
9449                         appendPQExpBuffer(query, "%s.", fmtId(namespace));
9450                 appendPQExpBuffer(query, "%s IS ", name);
9451                 appendStringLiteralAH(query, comments->descr, fout);
9452                 appendPQExpBufferStr(query, ";\n");
9453
9454                 appendPQExpBuffer(tag, "%s %s", type, name);
9455
9456                 /*
9457                  * We mark comments as SECTION_NONE because they really belong in the
9458                  * same section as their parent, whether that is pre-data or
9459                  * post-data.
9460                  */
9461                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9462                                          tag->data, namespace, NULL, owner,
9463                                          false, "COMMENT", SECTION_NONE,
9464                                          query->data, "", NULL,
9465                                          &(dumpId), 1,
9466                                          NULL, NULL);
9467
9468                 destroyPQExpBuffer(query);
9469                 destroyPQExpBuffer(tag);
9470         }
9471 }
9472
9473 /*
9474  * dumpTableComment --
9475  *
9476  * As above, but dump comments for both the specified table (or view)
9477  * and its columns.
9478  */
9479 static void
9480 dumpTableComment(Archive *fout, TableInfo *tbinfo,
9481                                  const char *reltypename)
9482 {
9483         DumpOptions *dopt = fout->dopt;
9484         CommentItem *comments;
9485         int                     ncomments;
9486         PQExpBuffer query;
9487         PQExpBuffer tag;
9488
9489         /* do nothing, if --no-comments is supplied */
9490         if (dopt->no_comments)
9491                 return;
9492
9493         /* Comments are SCHEMA not data */
9494         if (dopt->dataOnly)
9495                 return;
9496
9497         /* Search for comments associated with relation, using table */
9498         ncomments = findComments(fout,
9499                                                          tbinfo->dobj.catId.tableoid,
9500                                                          tbinfo->dobj.catId.oid,
9501                                                          &comments);
9502
9503         /* If comments exist, build COMMENT ON statements */
9504         if (ncomments <= 0)
9505                 return;
9506
9507         query = createPQExpBuffer();
9508         tag = createPQExpBuffer();
9509
9510         while (ncomments > 0)
9511         {
9512                 const char *descr = comments->descr;
9513                 int                     objsubid = comments->objsubid;
9514
9515                 if (objsubid == 0)
9516                 {
9517                         resetPQExpBuffer(tag);
9518                         appendPQExpBuffer(tag, "%s %s", reltypename,
9519                                                           fmtId(tbinfo->dobj.name));
9520
9521                         resetPQExpBuffer(query);
9522                         appendPQExpBuffer(query, "COMMENT ON %s %s IS ", reltypename,
9523                                                           fmtQualifiedDumpable(tbinfo));
9524                         appendStringLiteralAH(query, descr, fout);
9525                         appendPQExpBufferStr(query, ";\n");
9526
9527                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
9528                                                  tag->data,
9529                                                  tbinfo->dobj.namespace->dobj.name,
9530                                                  NULL, tbinfo->rolname,
9531                                                  false, "COMMENT", SECTION_NONE,
9532                                                  query->data, "", NULL,
9533                                                  &(tbinfo->dobj.dumpId), 1,
9534                                                  NULL, NULL);
9535                 }
9536                 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
9537                 {
9538                         resetPQExpBuffer(tag);
9539                         appendPQExpBuffer(tag, "COLUMN %s.",
9540                                                           fmtId(tbinfo->dobj.name));
9541                         appendPQExpBufferStr(tag, fmtId(tbinfo->attnames[objsubid - 1]));
9542
9543                         resetPQExpBuffer(query);
9544                         appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
9545                                                           fmtQualifiedDumpable(tbinfo));
9546                         appendPQExpBuffer(query, "%s IS ",
9547                                                           fmtId(tbinfo->attnames[objsubid - 1]));
9548                         appendStringLiteralAH(query, descr, fout);
9549                         appendPQExpBufferStr(query, ";\n");
9550
9551                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
9552                                                  tag->data,
9553                                                  tbinfo->dobj.namespace->dobj.name,
9554                                                  NULL, tbinfo->rolname,
9555                                                  false, "COMMENT", SECTION_NONE,
9556                                                  query->data, "", NULL,
9557                                                  &(tbinfo->dobj.dumpId), 1,
9558                                                  NULL, NULL);
9559                 }
9560
9561                 comments++;
9562                 ncomments--;
9563         }
9564
9565         destroyPQExpBuffer(query);
9566         destroyPQExpBuffer(tag);
9567 }
9568
9569 /*
9570  * findComments --
9571  *
9572  * Find the comment(s), if any, associated with the given object.  All the
9573  * objsubid values associated with the given classoid/objoid are found with
9574  * one search.
9575  */
9576 static int
9577 findComments(Archive *fout, Oid classoid, Oid objoid,
9578                          CommentItem **items)
9579 {
9580         /* static storage for table of comments */
9581         static CommentItem *comments = NULL;
9582         static int      ncomments = -1;
9583
9584         CommentItem *middle = NULL;
9585         CommentItem *low;
9586         CommentItem *high;
9587         int                     nmatch;
9588
9589         /* Get comments if we didn't already */
9590         if (ncomments < 0)
9591                 ncomments = collectComments(fout, &comments);
9592
9593         /*
9594          * Do binary search to find some item matching the object.
9595          */
9596         low = &comments[0];
9597         high = &comments[ncomments - 1];
9598         while (low <= high)
9599         {
9600                 middle = low + (high - low) / 2;
9601
9602                 if (classoid < middle->classoid)
9603                         high = middle - 1;
9604                 else if (classoid > middle->classoid)
9605                         low = middle + 1;
9606                 else if (objoid < middle->objoid)
9607                         high = middle - 1;
9608                 else if (objoid > middle->objoid)
9609                         low = middle + 1;
9610                 else
9611                         break;                          /* found a match */
9612         }
9613
9614         if (low > high)                         /* no matches */
9615         {
9616                 *items = NULL;
9617                 return 0;
9618         }
9619
9620         /*
9621          * Now determine how many items match the object.  The search loop
9622          * invariant still holds: only items between low and high inclusive could
9623          * match.
9624          */
9625         nmatch = 1;
9626         while (middle > low)
9627         {
9628                 if (classoid != middle[-1].classoid ||
9629                         objoid != middle[-1].objoid)
9630                         break;
9631                 middle--;
9632                 nmatch++;
9633         }
9634
9635         *items = middle;
9636
9637         middle += nmatch;
9638         while (middle <= high)
9639         {
9640                 if (classoid != middle->classoid ||
9641                         objoid != middle->objoid)
9642                         break;
9643                 middle++;
9644                 nmatch++;
9645         }
9646
9647         return nmatch;
9648 }
9649
9650 /*
9651  * collectComments --
9652  *
9653  * Construct a table of all comments available for database objects.
9654  * We used to do per-object queries for the comments, but it's much faster
9655  * to pull them all over at once, and on most databases the memory cost
9656  * isn't high.
9657  *
9658  * The table is sorted by classoid/objid/objsubid for speed in lookup.
9659  */
9660 static int
9661 collectComments(Archive *fout, CommentItem **items)
9662 {
9663         PGresult   *res;
9664         PQExpBuffer query;
9665         int                     i_description;
9666         int                     i_classoid;
9667         int                     i_objoid;
9668         int                     i_objsubid;
9669         int                     ntups;
9670         int                     i;
9671         CommentItem *comments;
9672
9673         query = createPQExpBuffer();
9674
9675         appendPQExpBufferStr(query, "SELECT description, classoid, objoid, objsubid "
9676                                                  "FROM pg_catalog.pg_description "
9677                                                  "ORDER BY classoid, objoid, objsubid");
9678
9679         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9680
9681         /* Construct lookup table containing OIDs in numeric form */
9682
9683         i_description = PQfnumber(res, "description");
9684         i_classoid = PQfnumber(res, "classoid");
9685         i_objoid = PQfnumber(res, "objoid");
9686         i_objsubid = PQfnumber(res, "objsubid");
9687
9688         ntups = PQntuples(res);
9689
9690         comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
9691
9692         for (i = 0; i < ntups; i++)
9693         {
9694                 comments[i].descr = PQgetvalue(res, i, i_description);
9695                 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
9696                 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
9697                 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
9698         }
9699
9700         /* Do NOT free the PGresult since we are keeping pointers into it */
9701         destroyPQExpBuffer(query);
9702
9703         *items = comments;
9704         return ntups;
9705 }
9706
9707 /*
9708  * dumpDumpableObject
9709  *
9710  * This routine and its subsidiaries are responsible for creating
9711  * ArchiveEntries (TOC objects) for each object to be dumped.
9712  */
9713 static void
9714 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
9715 {
9716         switch (dobj->objType)
9717         {
9718                 case DO_NAMESPACE:
9719                         dumpNamespace(fout, (NamespaceInfo *) dobj);
9720                         break;
9721                 case DO_EXTENSION:
9722                         dumpExtension(fout, (ExtensionInfo *) dobj);
9723                         break;
9724                 case DO_TYPE:
9725                         dumpType(fout, (TypeInfo *) dobj);
9726                         break;
9727                 case DO_SHELL_TYPE:
9728                         dumpShellType(fout, (ShellTypeInfo *) dobj);
9729                         break;
9730                 case DO_FUNC:
9731                         dumpFunc(fout, (FuncInfo *) dobj);
9732                         break;
9733                 case DO_AGG:
9734                         dumpAgg(fout, (AggInfo *) dobj);
9735                         break;
9736                 case DO_OPERATOR:
9737                         dumpOpr(fout, (OprInfo *) dobj);
9738                         break;
9739                 case DO_ACCESS_METHOD:
9740                         dumpAccessMethod(fout, (AccessMethodInfo *) dobj);
9741                         break;
9742                 case DO_OPCLASS:
9743                         dumpOpclass(fout, (OpclassInfo *) dobj);
9744                         break;
9745                 case DO_OPFAMILY:
9746                         dumpOpfamily(fout, (OpfamilyInfo *) dobj);
9747                         break;
9748                 case DO_COLLATION:
9749                         dumpCollation(fout, (CollInfo *) dobj);
9750                         break;
9751                 case DO_CONVERSION:
9752                         dumpConversion(fout, (ConvInfo *) dobj);
9753                         break;
9754                 case DO_TABLE:
9755                         dumpTable(fout, (TableInfo *) dobj);
9756                         break;
9757                 case DO_ATTRDEF:
9758                         dumpAttrDef(fout, (AttrDefInfo *) dobj);
9759                         break;
9760                 case DO_INDEX:
9761                         dumpIndex(fout, (IndxInfo *) dobj);
9762                         break;
9763                 case DO_INDEX_ATTACH:
9764                         dumpIndexAttach(fout, (IndexAttachInfo *) dobj);
9765                         break;
9766                 case DO_STATSEXT:
9767                         dumpStatisticsExt(fout, (StatsExtInfo *) dobj);
9768                         break;
9769                 case DO_REFRESH_MATVIEW:
9770                         refreshMatViewData(fout, (TableDataInfo *) dobj);
9771                         break;
9772                 case DO_RULE:
9773                         dumpRule(fout, (RuleInfo *) dobj);
9774                         break;
9775                 case DO_TRIGGER:
9776                         dumpTrigger(fout, (TriggerInfo *) dobj);
9777                         break;
9778                 case DO_EVENT_TRIGGER:
9779                         dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
9780                         break;
9781                 case DO_CONSTRAINT:
9782                         dumpConstraint(fout, (ConstraintInfo *) dobj);
9783                         break;
9784                 case DO_FK_CONSTRAINT:
9785                         dumpConstraint(fout, (ConstraintInfo *) dobj);
9786                         break;
9787                 case DO_PROCLANG:
9788                         dumpProcLang(fout, (ProcLangInfo *) dobj);
9789                         break;
9790                 case DO_CAST:
9791                         dumpCast(fout, (CastInfo *) dobj);
9792                         break;
9793                 case DO_TRANSFORM:
9794                         dumpTransform(fout, (TransformInfo *) dobj);
9795                         break;
9796                 case DO_SEQUENCE_SET:
9797                         dumpSequenceData(fout, (TableDataInfo *) dobj);
9798                         break;
9799                 case DO_TABLE_DATA:
9800                         dumpTableData(fout, (TableDataInfo *) dobj);
9801                         break;
9802                 case DO_DUMMY_TYPE:
9803                         /* table rowtypes and array types are never dumped separately */
9804                         break;
9805                 case DO_TSPARSER:
9806                         dumpTSParser(fout, (TSParserInfo *) dobj);
9807                         break;
9808                 case DO_TSDICT:
9809                         dumpTSDictionary(fout, (TSDictInfo *) dobj);
9810                         break;
9811                 case DO_TSTEMPLATE:
9812                         dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
9813                         break;
9814                 case DO_TSCONFIG:
9815                         dumpTSConfig(fout, (TSConfigInfo *) dobj);
9816                         break;
9817                 case DO_FDW:
9818                         dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
9819                         break;
9820                 case DO_FOREIGN_SERVER:
9821                         dumpForeignServer(fout, (ForeignServerInfo *) dobj);
9822                         break;
9823                 case DO_DEFAULT_ACL:
9824                         dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
9825                         break;
9826                 case DO_BLOB:
9827                         dumpBlob(fout, (BlobInfo *) dobj);
9828                         break;
9829                 case DO_BLOB_DATA:
9830                         if (dobj->dump & DUMP_COMPONENT_DATA)
9831                                 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
9832                                                          dobj->name, NULL, NULL, "",
9833                                                          false, "BLOBS", SECTION_DATA,
9834                                                          "", "", NULL,
9835                                                          NULL, 0,
9836                                                          dumpBlobs, NULL);
9837                         break;
9838                 case DO_POLICY:
9839                         dumpPolicy(fout, (PolicyInfo *) dobj);
9840                         break;
9841                 case DO_PUBLICATION:
9842                         dumpPublication(fout, (PublicationInfo *) dobj);
9843                         break;
9844                 case DO_PUBLICATION_REL:
9845                         dumpPublicationTable(fout, (PublicationRelInfo *) dobj);
9846                         break;
9847                 case DO_SUBSCRIPTION:
9848                         dumpSubscription(fout, (SubscriptionInfo *) dobj);
9849                         break;
9850                 case DO_PRE_DATA_BOUNDARY:
9851                 case DO_POST_DATA_BOUNDARY:
9852                         /* never dumped, nothing to do */
9853                         break;
9854         }
9855 }
9856
9857 /*
9858  * dumpNamespace
9859  *        writes out to fout the queries to recreate a user-defined namespace
9860  */
9861 static void
9862 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
9863 {
9864         DumpOptions *dopt = fout->dopt;
9865         PQExpBuffer q;
9866         PQExpBuffer delq;
9867         char       *qnspname;
9868
9869         /* Skip if not to be dumped */
9870         if (!nspinfo->dobj.dump || dopt->dataOnly)
9871                 return;
9872
9873         q = createPQExpBuffer();
9874         delq = createPQExpBuffer();
9875
9876         qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
9877
9878         appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
9879
9880         appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
9881
9882         if (dopt->binary_upgrade)
9883                 binary_upgrade_extension_member(q, &nspinfo->dobj,
9884                                                                                 "SCHEMA", qnspname, NULL);
9885
9886         if (nspinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9887                 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
9888                                          nspinfo->dobj.name,
9889                                          NULL, NULL,
9890                                          nspinfo->rolname,
9891                                          false, "SCHEMA", SECTION_PRE_DATA,
9892                                          q->data, delq->data, NULL,
9893                                          NULL, 0,
9894                                          NULL, NULL);
9895
9896         /* Dump Schema Comments and Security Labels */
9897         if (nspinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9898                 dumpComment(fout, "SCHEMA", qnspname,
9899                                         NULL, nspinfo->rolname,
9900                                         nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9901
9902         if (nspinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9903                 dumpSecLabel(fout, "SCHEMA", qnspname,
9904                                          NULL, nspinfo->rolname,
9905                                          nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9906
9907         if (nspinfo->dobj.dump & DUMP_COMPONENT_ACL)
9908                 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
9909                                 qnspname, NULL, NULL,
9910                                 nspinfo->rolname, nspinfo->nspacl, nspinfo->rnspacl,
9911                                 nspinfo->initnspacl, nspinfo->initrnspacl);
9912
9913         free(qnspname);
9914
9915         destroyPQExpBuffer(q);
9916         destroyPQExpBuffer(delq);
9917 }
9918
9919 /*
9920  * dumpExtension
9921  *        writes out to fout the queries to recreate an extension
9922  */
9923 static void
9924 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
9925 {
9926         DumpOptions *dopt = fout->dopt;
9927         PQExpBuffer q;
9928         PQExpBuffer delq;
9929         char       *qextname;
9930
9931         /* Skip if not to be dumped */
9932         if (!extinfo->dobj.dump || dopt->dataOnly)
9933                 return;
9934
9935         q = createPQExpBuffer();
9936         delq = createPQExpBuffer();
9937
9938         qextname = pg_strdup(fmtId(extinfo->dobj.name));
9939
9940         appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
9941
9942         if (!dopt->binary_upgrade)
9943         {
9944                 /*
9945                  * In a regular dump, we simply create the extension, intentionally
9946                  * not specifying a version, so that the destination installation's
9947                  * default version is used.
9948                  *
9949                  * Use of IF NOT EXISTS here is unlike our behavior for other object
9950                  * types; but there are various scenarios in which it's convenient to
9951                  * manually create the desired extension before restoring, so we
9952                  * prefer to allow it to exist already.
9953                  */
9954                 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
9955                                                   qextname, fmtId(extinfo->namespace));
9956         }
9957         else
9958         {
9959                 /*
9960                  * In binary-upgrade mode, it's critical to reproduce the state of the
9961                  * database exactly, so our procedure is to create an empty extension,
9962                  * restore all the contained objects normally, and add them to the
9963                  * extension one by one.  This function performs just the first of
9964                  * those steps.  binary_upgrade_extension_member() takes care of
9965                  * adding member objects as they're created.
9966                  */
9967                 int                     i;
9968                 int                     n;
9969
9970                 appendPQExpBufferStr(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
9971
9972                 /*
9973                  * We unconditionally create the extension, so we must drop it if it
9974                  * exists.  This could happen if the user deleted 'plpgsql' and then
9975                  * readded it, causing its oid to be greater than g_last_builtin_oid.
9976                  */
9977                 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
9978
9979                 appendPQExpBufferStr(q,
9980                                                          "SELECT pg_catalog.binary_upgrade_create_empty_extension(");
9981                 appendStringLiteralAH(q, extinfo->dobj.name, fout);
9982                 appendPQExpBufferStr(q, ", ");
9983                 appendStringLiteralAH(q, extinfo->namespace, fout);
9984                 appendPQExpBufferStr(q, ", ");
9985                 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
9986                 appendStringLiteralAH(q, extinfo->extversion, fout);
9987                 appendPQExpBufferStr(q, ", ");
9988
9989                 /*
9990                  * Note that we're pushing extconfig (an OID array) back into
9991                  * pg_extension exactly as-is.  This is OK because pg_class OIDs are
9992                  * preserved in binary upgrade.
9993                  */
9994                 if (strlen(extinfo->extconfig) > 2)
9995                         appendStringLiteralAH(q, extinfo->extconfig, fout);
9996                 else
9997                         appendPQExpBufferStr(q, "NULL");
9998                 appendPQExpBufferStr(q, ", ");
9999                 if (strlen(extinfo->extcondition) > 2)
10000                         appendStringLiteralAH(q, extinfo->extcondition, fout);
10001                 else
10002                         appendPQExpBufferStr(q, "NULL");
10003                 appendPQExpBufferStr(q, ", ");
10004                 appendPQExpBufferStr(q, "ARRAY[");
10005                 n = 0;
10006                 for (i = 0; i < extinfo->dobj.nDeps; i++)
10007                 {
10008                         DumpableObject *extobj;
10009
10010                         extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
10011                         if (extobj && extobj->objType == DO_EXTENSION)
10012                         {
10013                                 if (n++ > 0)
10014                                         appendPQExpBufferChar(q, ',');
10015                                 appendStringLiteralAH(q, extobj->name, fout);
10016                         }
10017                 }
10018                 appendPQExpBufferStr(q, "]::pg_catalog.text[]");
10019                 appendPQExpBufferStr(q, ");\n");
10020         }
10021
10022         if (extinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10023                 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
10024                                          extinfo->dobj.name,
10025                                          NULL, NULL,
10026                                          "",
10027                                          false, "EXTENSION", SECTION_PRE_DATA,
10028                                          q->data, delq->data, NULL,
10029                                          NULL, 0,
10030                                          NULL, NULL);
10031
10032         /* Dump Extension Comments and Security Labels */
10033         if (extinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10034                 dumpComment(fout, "EXTENSION", qextname,
10035                                         NULL, "",
10036                                         extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
10037
10038         if (extinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10039                 dumpSecLabel(fout, "EXTENSION", qextname,
10040                                          NULL, "",
10041                                          extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
10042
10043         free(qextname);
10044
10045         destroyPQExpBuffer(q);
10046         destroyPQExpBuffer(delq);
10047 }
10048
10049 /*
10050  * dumpType
10051  *        writes out to fout the queries to recreate a user-defined type
10052  */
10053 static void
10054 dumpType(Archive *fout, TypeInfo *tyinfo)
10055 {
10056         DumpOptions *dopt = fout->dopt;
10057
10058         /* Skip if not to be dumped */
10059         if (!tyinfo->dobj.dump || dopt->dataOnly)
10060                 return;
10061
10062         /* Dump out in proper style */
10063         if (tyinfo->typtype == TYPTYPE_BASE)
10064                 dumpBaseType(fout, tyinfo);
10065         else if (tyinfo->typtype == TYPTYPE_DOMAIN)
10066                 dumpDomain(fout, tyinfo);
10067         else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
10068                 dumpCompositeType(fout, tyinfo);
10069         else if (tyinfo->typtype == TYPTYPE_ENUM)
10070                 dumpEnumType(fout, tyinfo);
10071         else if (tyinfo->typtype == TYPTYPE_RANGE)
10072                 dumpRangeType(fout, tyinfo);
10073         else if (tyinfo->typtype == TYPTYPE_PSEUDO && !tyinfo->isDefined)
10074                 dumpUndefinedType(fout, tyinfo);
10075         else
10076                 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
10077                                   tyinfo->dobj.name);
10078 }
10079
10080 /*
10081  * dumpEnumType
10082  *        writes out to fout the queries to recreate a user-defined enum type
10083  */
10084 static void
10085 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
10086 {
10087         DumpOptions *dopt = fout->dopt;
10088         PQExpBuffer q = createPQExpBuffer();
10089         PQExpBuffer delq = createPQExpBuffer();
10090         PQExpBuffer query = createPQExpBuffer();
10091         PGresult   *res;
10092         int                     num,
10093                                 i;
10094         Oid                     enum_oid;
10095         char       *qtypname;
10096         char       *qualtypname;
10097         char       *label;
10098
10099         if (fout->remoteVersion >= 90100)
10100                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10101                                                   "FROM pg_catalog.pg_enum "
10102                                                   "WHERE enumtypid = '%u'"
10103                                                   "ORDER BY enumsortorder",
10104                                                   tyinfo->dobj.catId.oid);
10105         else
10106                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10107                                                   "FROM pg_catalog.pg_enum "
10108                                                   "WHERE enumtypid = '%u'"
10109                                                   "ORDER BY oid",
10110                                                   tyinfo->dobj.catId.oid);
10111
10112         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10113
10114         num = PQntuples(res);
10115
10116         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10117         qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10118
10119         /*
10120          * CASCADE shouldn't be required here as for normal types since the I/O
10121          * functions are generic and do not get dropped.
10122          */
10123         appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10124
10125         if (dopt->binary_upgrade)
10126                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10127                                                                                                  tyinfo->dobj.catId.oid,
10128                                                                                                  false);
10129
10130         appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
10131                                           qualtypname);
10132
10133         if (!dopt->binary_upgrade)
10134         {
10135                 /* Labels with server-assigned oids */
10136                 for (i = 0; i < num; i++)
10137                 {
10138                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10139                         if (i > 0)
10140                                 appendPQExpBufferChar(q, ',');
10141                         appendPQExpBufferStr(q, "\n    ");
10142                         appendStringLiteralAH(q, label, fout);
10143                 }
10144         }
10145
10146         appendPQExpBufferStr(q, "\n);\n");
10147
10148         if (dopt->binary_upgrade)
10149         {
10150                 /* Labels with dump-assigned (preserved) oids */
10151                 for (i = 0; i < num; i++)
10152                 {
10153                         enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
10154                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10155
10156                         if (i == 0)
10157                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
10158                         appendPQExpBuffer(q,
10159                                                           "SELECT pg_catalog.binary_upgrade_set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
10160                                                           enum_oid);
10161                         appendPQExpBuffer(q, "ALTER TYPE %s ADD VALUE ", qualtypname);
10162                         appendStringLiteralAH(q, label, fout);
10163                         appendPQExpBufferStr(q, ";\n\n");
10164                 }
10165         }
10166
10167         if (dopt->binary_upgrade)
10168                 binary_upgrade_extension_member(q, &tyinfo->dobj,
10169                                                                                 "TYPE", qtypname,
10170                                                                                 tyinfo->dobj.namespace->dobj.name);
10171
10172         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10173                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10174                                          tyinfo->dobj.name,
10175                                          tyinfo->dobj.namespace->dobj.name,
10176                                          NULL,
10177                                          tyinfo->rolname, false,
10178                                          "TYPE", SECTION_PRE_DATA,
10179                                          q->data, delq->data, NULL,
10180                                          NULL, 0,
10181                                          NULL, NULL);
10182
10183         /* Dump Type Comments and Security Labels */
10184         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10185                 dumpComment(fout, "TYPE", qtypname,
10186                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10187                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10188
10189         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10190                 dumpSecLabel(fout, "TYPE", qtypname,
10191                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10192                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10193
10194         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10195                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10196                                 qtypname, NULL,
10197                                 tyinfo->dobj.namespace->dobj.name,
10198                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10199                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10200
10201         PQclear(res);
10202         destroyPQExpBuffer(q);
10203         destroyPQExpBuffer(delq);
10204         destroyPQExpBuffer(query);
10205         free(qtypname);
10206         free(qualtypname);
10207 }
10208
10209 /*
10210  * dumpRangeType
10211  *        writes out to fout the queries to recreate a user-defined range type
10212  */
10213 static void
10214 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
10215 {
10216         DumpOptions *dopt = fout->dopt;
10217         PQExpBuffer q = createPQExpBuffer();
10218         PQExpBuffer delq = createPQExpBuffer();
10219         PQExpBuffer query = createPQExpBuffer();
10220         PGresult   *res;
10221         Oid                     collationOid;
10222         char       *qtypname;
10223         char       *qualtypname;
10224         char       *procname;
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         qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10245
10246         /*
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;\n", qualtypname);
10251
10252         if (dopt->binary_upgrade)
10253                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10254                                                                                                  tyinfo->dobj.catId.oid,
10255                                                                                                  false);
10256
10257         appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
10258                                           qualtypname);
10259
10260         appendPQExpBuffer(q, "\n    subtype = %s",
10261                                           PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
10262
10263         /* print subtype_opclass only if not default for subtype */
10264         if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
10265         {
10266                 char       *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
10267                 char       *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
10268
10269                 appendPQExpBuffer(q, ",\n    subtype_opclass = %s.",
10270                                                   fmtId(nspname));
10271                 appendPQExpBufferStr(q, fmtId(opcname));
10272         }
10273
10274         collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
10275         if (OidIsValid(collationOid))
10276         {
10277                 CollInfo   *coll = findCollationByOid(collationOid);
10278
10279                 if (coll)
10280                         appendPQExpBuffer(q, ",\n    collation = %s",
10281                                                           fmtQualifiedDumpable(coll));
10282         }
10283
10284         procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
10285         if (strcmp(procname, "-") != 0)
10286                 appendPQExpBuffer(q, ",\n    canonical = %s", procname);
10287
10288         procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
10289         if (strcmp(procname, "-") != 0)
10290                 appendPQExpBuffer(q, ",\n    subtype_diff = %s", procname);
10291
10292         appendPQExpBufferStr(q, "\n);\n");
10293
10294         if (dopt->binary_upgrade)
10295                 binary_upgrade_extension_member(q, &tyinfo->dobj,
10296                                                                                 "TYPE", qtypname,
10297                                                                                 tyinfo->dobj.namespace->dobj.name);
10298
10299         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10300                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10301                                          tyinfo->dobj.name,
10302                                          tyinfo->dobj.namespace->dobj.name,
10303                                          NULL,
10304                                          tyinfo->rolname, false,
10305                                          "TYPE", SECTION_PRE_DATA,
10306                                          q->data, delq->data, NULL,
10307                                          NULL, 0,
10308                                          NULL, NULL);
10309
10310         /* Dump Type Comments and Security Labels */
10311         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10312                 dumpComment(fout, "TYPE", qtypname,
10313                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10314                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10315
10316         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10317                 dumpSecLabel(fout, "TYPE", qtypname,
10318                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10319                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10320
10321         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10322                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10323                                 qtypname, NULL,
10324                                 tyinfo->dobj.namespace->dobj.name,
10325                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10326                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10327
10328         PQclear(res);
10329         destroyPQExpBuffer(q);
10330         destroyPQExpBuffer(delq);
10331         destroyPQExpBuffer(query);
10332         free(qtypname);
10333         free(qualtypname);
10334 }
10335
10336 /*
10337  * dumpUndefinedType
10338  *        writes out to fout the queries to recreate a !typisdefined type
10339  *
10340  * This is a shell type, but we use different terminology to distinguish
10341  * this case from where we have to emit a shell type definition to break
10342  * circular dependencies.  An undefined type shouldn't ever have anything
10343  * depending on it.
10344  */
10345 static void
10346 dumpUndefinedType(Archive *fout, TypeInfo *tyinfo)
10347 {
10348         DumpOptions *dopt = fout->dopt;
10349         PQExpBuffer q = createPQExpBuffer();
10350         PQExpBuffer delq = createPQExpBuffer();
10351         char       *qtypname;
10352         char       *qualtypname;
10353
10354         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10355         qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10356
10357         appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10358
10359         if (dopt->binary_upgrade)
10360                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10361                                                                                                  tyinfo->dobj.catId.oid,
10362                                                                                                  false);
10363
10364         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
10365                                           qualtypname);
10366
10367         if (dopt->binary_upgrade)
10368                 binary_upgrade_extension_member(q, &tyinfo->dobj,
10369                                                                                 "TYPE", qtypname,
10370                                                                                 tyinfo->dobj.namespace->dobj.name);
10371
10372         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10373                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10374                                          tyinfo->dobj.name,
10375                                          tyinfo->dobj.namespace->dobj.name,
10376                                          NULL,
10377                                          tyinfo->rolname, false,
10378                                          "TYPE", SECTION_PRE_DATA,
10379                                          q->data, delq->data, NULL,
10380                                          NULL, 0,
10381                                          NULL, NULL);
10382
10383         /* Dump Type Comments and Security Labels */
10384         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10385                 dumpComment(fout, "TYPE", qtypname,
10386                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10387                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10388
10389         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10390                 dumpSecLabel(fout, "TYPE", qtypname,
10391                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10392                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10393
10394         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10395                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10396                                 qtypname, NULL,
10397                                 tyinfo->dobj.namespace->dobj.name,
10398                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10399                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10400
10401         destroyPQExpBuffer(q);
10402         destroyPQExpBuffer(delq);
10403         free(qtypname);
10404         free(qualtypname);
10405 }
10406
10407 /*
10408  * dumpBaseType
10409  *        writes out to fout the queries to recreate a user-defined base type
10410  */
10411 static void
10412 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
10413 {
10414         DumpOptions *dopt = fout->dopt;
10415         PQExpBuffer q = createPQExpBuffer();
10416         PQExpBuffer delq = createPQExpBuffer();
10417         PQExpBuffer query = createPQExpBuffer();
10418         PGresult   *res;
10419         char       *qtypname;
10420         char       *qualtypname;
10421         char       *typlen;
10422         char       *typinput;
10423         char       *typoutput;
10424         char       *typreceive;
10425         char       *typsend;
10426         char       *typmodin;
10427         char       *typmodout;
10428         char       *typanalyze;
10429         Oid                     typreceiveoid;
10430         Oid                     typsendoid;
10431         Oid                     typmodinoid;
10432         Oid                     typmodoutoid;
10433         Oid                     typanalyzeoid;
10434         char       *typcategory;
10435         char       *typispreferred;
10436         char       *typdelim;
10437         char       *typbyval;
10438         char       *typalign;
10439         char       *typstorage;
10440         char       *typcollatable;
10441         char       *typdefault;
10442         bool            typdefault_is_literal = false;
10443
10444         /* Fetch type-specific details */
10445         if (fout->remoteVersion >= 90100)
10446         {
10447                 appendPQExpBuffer(query, "SELECT typlen, "
10448                                                   "typinput, typoutput, typreceive, typsend, "
10449                                                   "typmodin, typmodout, typanalyze, "
10450                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
10451                                                   "typsend::pg_catalog.oid AS typsendoid, "
10452                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
10453                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
10454                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10455                                                   "typcategory, typispreferred, "
10456                                                   "typdelim, typbyval, typalign, typstorage, "
10457                                                   "(typcollation <> 0) AS typcollatable, "
10458                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10459                                                   "FROM pg_catalog.pg_type "
10460                                                   "WHERE oid = '%u'::pg_catalog.oid",
10461                                                   tyinfo->dobj.catId.oid);
10462         }
10463         else if (fout->remoteVersion >= 80400)
10464         {
10465                 appendPQExpBuffer(query, "SELECT typlen, "
10466                                                   "typinput, typoutput, typreceive, typsend, "
10467                                                   "typmodin, typmodout, typanalyze, "
10468                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
10469                                                   "typsend::pg_catalog.oid AS typsendoid, "
10470                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
10471                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
10472                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10473                                                   "typcategory, typispreferred, "
10474                                                   "typdelim, typbyval, typalign, typstorage, "
10475                                                   "false AS typcollatable, "
10476                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10477                                                   "FROM pg_catalog.pg_type "
10478                                                   "WHERE oid = '%u'::pg_catalog.oid",
10479                                                   tyinfo->dobj.catId.oid);
10480         }
10481         else if (fout->remoteVersion >= 80300)
10482         {
10483                 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
10484                 appendPQExpBuffer(query, "SELECT typlen, "
10485                                                   "typinput, typoutput, typreceive, typsend, "
10486                                                   "typmodin, typmodout, typanalyze, "
10487                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
10488                                                   "typsend::pg_catalog.oid AS typsendoid, "
10489                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
10490                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
10491                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10492                                                   "'U' AS typcategory, false AS typispreferred, "
10493                                                   "typdelim, typbyval, typalign, typstorage, "
10494                                                   "false AS typcollatable, "
10495                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10496                                                   "FROM pg_catalog.pg_type "
10497                                                   "WHERE oid = '%u'::pg_catalog.oid",
10498                                                   tyinfo->dobj.catId.oid);
10499         }
10500         else
10501         {
10502                 appendPQExpBuffer(query, "SELECT typlen, "
10503                                                   "typinput, typoutput, typreceive, typsend, "
10504                                                   "'-' AS typmodin, '-' AS typmodout, "
10505                                                   "typanalyze, "
10506                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
10507                                                   "typsend::pg_catalog.oid AS typsendoid, "
10508                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
10509                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10510                                                   "'U' AS typcategory, false AS typispreferred, "
10511                                                   "typdelim, typbyval, typalign, typstorage, "
10512                                                   "false AS typcollatable, "
10513                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10514                                                   "FROM pg_catalog.pg_type "
10515                                                   "WHERE oid = '%u'::pg_catalog.oid",
10516                                                   tyinfo->dobj.catId.oid);
10517         }
10518
10519         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10520
10521         typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
10522         typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
10523         typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
10524         typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
10525         typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
10526         typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
10527         typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
10528         typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
10529         typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
10530         typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
10531         typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
10532         typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
10533         typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
10534         typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
10535         typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
10536         typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
10537         typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
10538         typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
10539         typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
10540         typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
10541         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10542                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10543         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10544         {
10545                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10546                 typdefault_is_literal = true;   /* it needs quotes */
10547         }
10548         else
10549                 typdefault = NULL;
10550
10551         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10552         qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10553
10554         /*
10555          * The reason we include CASCADE is that the circular dependency between
10556          * the type and its I/O functions makes it impossible to drop the type any
10557          * other way.
10558          */
10559         appendPQExpBuffer(delq, "DROP TYPE %s CASCADE;\n", qualtypname);
10560
10561         /*
10562          * We might already have a shell type, but setting pg_type_oid is
10563          * harmless, and in any case we'd better set the array type OID.
10564          */
10565         if (dopt->binary_upgrade)
10566                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10567                                                                                                  tyinfo->dobj.catId.oid,
10568                                                                                                  false);
10569
10570         appendPQExpBuffer(q,
10571                                           "CREATE TYPE %s (\n"
10572                                           "    INTERNALLENGTH = %s",
10573                                           qualtypname,
10574                                           (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
10575
10576         /* regproc result is sufficiently quoted already */
10577         appendPQExpBuffer(q, ",\n    INPUT = %s", typinput);
10578         appendPQExpBuffer(q, ",\n    OUTPUT = %s", typoutput);
10579         if (OidIsValid(typreceiveoid))
10580                 appendPQExpBuffer(q, ",\n    RECEIVE = %s", typreceive);
10581         if (OidIsValid(typsendoid))
10582                 appendPQExpBuffer(q, ",\n    SEND = %s", typsend);
10583         if (OidIsValid(typmodinoid))
10584                 appendPQExpBuffer(q, ",\n    TYPMOD_IN = %s", typmodin);
10585         if (OidIsValid(typmodoutoid))
10586                 appendPQExpBuffer(q, ",\n    TYPMOD_OUT = %s", typmodout);
10587         if (OidIsValid(typanalyzeoid))
10588                 appendPQExpBuffer(q, ",\n    ANALYZE = %s", typanalyze);
10589
10590         if (strcmp(typcollatable, "t") == 0)
10591                 appendPQExpBufferStr(q, ",\n    COLLATABLE = true");
10592
10593         if (typdefault != NULL)
10594         {
10595                 appendPQExpBufferStr(q, ",\n    DEFAULT = ");
10596                 if (typdefault_is_literal)
10597                         appendStringLiteralAH(q, typdefault, fout);
10598                 else
10599                         appendPQExpBufferStr(q, typdefault);
10600         }
10601
10602         if (OidIsValid(tyinfo->typelem))
10603         {
10604                 char       *elemType;
10605
10606                 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
10607                 appendPQExpBuffer(q, ",\n    ELEMENT = %s", elemType);
10608                 free(elemType);
10609         }
10610
10611         if (strcmp(typcategory, "U") != 0)
10612         {
10613                 appendPQExpBufferStr(q, ",\n    CATEGORY = ");
10614                 appendStringLiteralAH(q, typcategory, fout);
10615         }
10616
10617         if (strcmp(typispreferred, "t") == 0)
10618                 appendPQExpBufferStr(q, ",\n    PREFERRED = true");
10619
10620         if (typdelim && strcmp(typdelim, ",") != 0)
10621         {
10622                 appendPQExpBufferStr(q, ",\n    DELIMITER = ");
10623                 appendStringLiteralAH(q, typdelim, fout);
10624         }
10625
10626         if (strcmp(typalign, "c") == 0)
10627                 appendPQExpBufferStr(q, ",\n    ALIGNMENT = char");
10628         else if (strcmp(typalign, "s") == 0)
10629                 appendPQExpBufferStr(q, ",\n    ALIGNMENT = int2");
10630         else if (strcmp(typalign, "i") == 0)
10631                 appendPQExpBufferStr(q, ",\n    ALIGNMENT = int4");
10632         else if (strcmp(typalign, "d") == 0)
10633                 appendPQExpBufferStr(q, ",\n    ALIGNMENT = double");
10634
10635         if (strcmp(typstorage, "p") == 0)
10636                 appendPQExpBufferStr(q, ",\n    STORAGE = plain");
10637         else if (strcmp(typstorage, "e") == 0)
10638                 appendPQExpBufferStr(q, ",\n    STORAGE = external");
10639         else if (strcmp(typstorage, "x") == 0)
10640                 appendPQExpBufferStr(q, ",\n    STORAGE = extended");
10641         else if (strcmp(typstorage, "m") == 0)
10642                 appendPQExpBufferStr(q, ",\n    STORAGE = main");
10643
10644         if (strcmp(typbyval, "t") == 0)
10645                 appendPQExpBufferStr(q, ",\n    PASSEDBYVALUE");
10646
10647         appendPQExpBufferStr(q, "\n);\n");
10648
10649         if (dopt->binary_upgrade)
10650                 binary_upgrade_extension_member(q, &tyinfo->dobj,
10651                                                                                 "TYPE", qtypname,
10652                                                                                 tyinfo->dobj.namespace->dobj.name);
10653
10654         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10655                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10656                                          tyinfo->dobj.name,
10657                                          tyinfo->dobj.namespace->dobj.name,
10658                                          NULL,
10659                                          tyinfo->rolname, false,
10660                                          "TYPE", SECTION_PRE_DATA,
10661                                          q->data, delq->data, NULL,
10662                                          NULL, 0,
10663                                          NULL, NULL);
10664
10665         /* Dump Type Comments and Security Labels */
10666         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10667                 dumpComment(fout, "TYPE", qtypname,
10668                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10669                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10670
10671         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10672                 dumpSecLabel(fout, "TYPE", qtypname,
10673                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10674                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10675
10676         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10677                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10678                                 qtypname, NULL,
10679                                 tyinfo->dobj.namespace->dobj.name,
10680                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10681                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10682
10683         PQclear(res);
10684         destroyPQExpBuffer(q);
10685         destroyPQExpBuffer(delq);
10686         destroyPQExpBuffer(query);
10687         free(qtypname);
10688         free(qualtypname);
10689 }
10690
10691 /*
10692  * dumpDomain
10693  *        writes out to fout the queries to recreate a user-defined domain
10694  */
10695 static void
10696 dumpDomain(Archive *fout, TypeInfo *tyinfo)
10697 {
10698         DumpOptions *dopt = fout->dopt;
10699         PQExpBuffer q = createPQExpBuffer();
10700         PQExpBuffer delq = createPQExpBuffer();
10701         PQExpBuffer query = createPQExpBuffer();
10702         PGresult   *res;
10703         int                     i;
10704         char       *qtypname;
10705         char       *qualtypname;
10706         char       *typnotnull;
10707         char       *typdefn;
10708         char       *typdefault;
10709         Oid                     typcollation;
10710         bool            typdefault_is_literal = false;
10711
10712         /* Fetch domain specific details */
10713         if (fout->remoteVersion >= 90100)
10714         {
10715                 /* typcollation is new in 9.1 */
10716                 appendPQExpBuffer(query, "SELECT t.typnotnull, "
10717                                                   "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
10718                                                   "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10719                                                   "t.typdefault, "
10720                                                   "CASE WHEN t.typcollation <> u.typcollation "
10721                                                   "THEN t.typcollation ELSE 0 END AS typcollation "
10722                                                   "FROM pg_catalog.pg_type t "
10723                                                   "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
10724                                                   "WHERE t.oid = '%u'::pg_catalog.oid",
10725                                                   tyinfo->dobj.catId.oid);
10726         }
10727         else
10728         {
10729                 appendPQExpBuffer(query, "SELECT typnotnull, "
10730                                                   "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
10731                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10732                                                   "typdefault, 0 AS typcollation "
10733                                                   "FROM pg_catalog.pg_type "
10734                                                   "WHERE oid = '%u'::pg_catalog.oid",
10735                                                   tyinfo->dobj.catId.oid);
10736         }
10737
10738         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10739
10740         typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
10741         typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
10742         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10743                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10744         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10745         {
10746                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10747                 typdefault_is_literal = true;   /* it needs quotes */
10748         }
10749         else
10750                 typdefault = NULL;
10751         typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
10752
10753         if (dopt->binary_upgrade)
10754                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10755                                                                                                  tyinfo->dobj.catId.oid,
10756                                                                                                  true); /* force array type */
10757
10758         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10759         qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10760
10761         appendPQExpBuffer(q,
10762                                           "CREATE DOMAIN %s AS %s",
10763                                           qualtypname,
10764                                           typdefn);
10765
10766         /* Print collation only if different from base type's collation */
10767         if (OidIsValid(typcollation))
10768         {
10769                 CollInfo   *coll;
10770
10771                 coll = findCollationByOid(typcollation);
10772                 if (coll)
10773                         appendPQExpBuffer(q, " COLLATE %s", fmtQualifiedDumpable(coll));
10774         }
10775
10776         if (typnotnull[0] == 't')
10777                 appendPQExpBufferStr(q, " NOT NULL");
10778
10779         if (typdefault != NULL)
10780         {
10781                 appendPQExpBufferStr(q, " DEFAULT ");
10782                 if (typdefault_is_literal)
10783                         appendStringLiteralAH(q, typdefault, fout);
10784                 else
10785                         appendPQExpBufferStr(q, typdefault);
10786         }
10787
10788         PQclear(res);
10789
10790         /*
10791          * Add any CHECK constraints for the domain
10792          */
10793         for (i = 0; i < tyinfo->nDomChecks; i++)
10794         {
10795                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10796
10797                 if (!domcheck->separate)
10798                         appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
10799                                                           fmtId(domcheck->dobj.name), domcheck->condef);
10800         }
10801
10802         appendPQExpBufferStr(q, ";\n");
10803
10804         appendPQExpBuffer(delq, "DROP DOMAIN %s;\n", qualtypname);
10805
10806         if (dopt->binary_upgrade)
10807                 binary_upgrade_extension_member(q, &tyinfo->dobj,
10808                                                                                 "DOMAIN", qtypname,
10809                                                                                 tyinfo->dobj.namespace->dobj.name);
10810
10811         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10812                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10813                                          tyinfo->dobj.name,
10814                                          tyinfo->dobj.namespace->dobj.name,
10815                                          NULL,
10816                                          tyinfo->rolname, false,
10817                                          "DOMAIN", SECTION_PRE_DATA,
10818                                          q->data, delq->data, NULL,
10819                                          NULL, 0,
10820                                          NULL, NULL);
10821
10822         /* Dump Domain Comments and Security Labels */
10823         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10824                 dumpComment(fout, "DOMAIN", qtypname,
10825                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10826                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10827
10828         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10829                 dumpSecLabel(fout, "DOMAIN", qtypname,
10830                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10831                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10832
10833         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10834                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10835                                 qtypname, NULL,
10836                                 tyinfo->dobj.namespace->dobj.name,
10837                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10838                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10839
10840         /* Dump any per-constraint comments */
10841         for (i = 0; i < tyinfo->nDomChecks; i++)
10842         {
10843                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10844                 PQExpBuffer conprefix = createPQExpBuffer();
10845
10846                 appendPQExpBuffer(conprefix, "CONSTRAINT %s ON DOMAIN",
10847                                                   fmtId(domcheck->dobj.name));
10848
10849                 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10850                         dumpComment(fout, conprefix->data, qtypname,
10851                                                 tyinfo->dobj.namespace->dobj.name,
10852                                                 tyinfo->rolname,
10853                                                 domcheck->dobj.catId, 0, tyinfo->dobj.dumpId);
10854
10855                 destroyPQExpBuffer(conprefix);
10856         }
10857
10858         destroyPQExpBuffer(q);
10859         destroyPQExpBuffer(delq);
10860         destroyPQExpBuffer(query);
10861         free(qtypname);
10862         free(qualtypname);
10863 }
10864
10865 /*
10866  * dumpCompositeType
10867  *        writes out to fout the queries to recreate a user-defined stand-alone
10868  *        composite type
10869  */
10870 static void
10871 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
10872 {
10873         DumpOptions *dopt = fout->dopt;
10874         PQExpBuffer q = createPQExpBuffer();
10875         PQExpBuffer dropped = createPQExpBuffer();
10876         PQExpBuffer delq = createPQExpBuffer();
10877         PQExpBuffer query = createPQExpBuffer();
10878         PGresult   *res;
10879         char       *qtypname;
10880         char       *qualtypname;
10881         int                     ntups;
10882         int                     i_attname;
10883         int                     i_atttypdefn;
10884         int                     i_attlen;
10885         int                     i_attalign;
10886         int                     i_attisdropped;
10887         int                     i_attcollation;
10888         int                     i;
10889         int                     actual_atts;
10890
10891         /* Fetch type specific details */
10892         if (fout->remoteVersion >= 90100)
10893         {
10894                 /*
10895                  * attcollation is new in 9.1.  Since we only want to dump COLLATE
10896                  * clauses for attributes whose collation is different from their
10897                  * type's default, we use a CASE here to suppress uninteresting
10898                  * attcollations cheaply.  atttypid will be 0 for dropped columns;
10899                  * collation does not matter for those.
10900                  */
10901                 appendPQExpBuffer(query, "SELECT a.attname, "
10902                                                   "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10903                                                   "a.attlen, a.attalign, a.attisdropped, "
10904                                                   "CASE WHEN a.attcollation <> at.typcollation "
10905                                                   "THEN a.attcollation ELSE 0 END AS attcollation "
10906                                                   "FROM pg_catalog.pg_type ct "
10907                                                   "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
10908                                                   "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
10909                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
10910                                                   "ORDER BY a.attnum ",
10911                                                   tyinfo->dobj.catId.oid);
10912         }
10913         else
10914         {
10915                 /*
10916                  * Since ALTER TYPE could not drop columns until 9.1, attisdropped
10917                  * should always be false.
10918                  */
10919                 appendPQExpBuffer(query, "SELECT a.attname, "
10920                                                   "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10921                                                   "a.attlen, a.attalign, a.attisdropped, "
10922                                                   "0 AS attcollation "
10923                                                   "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
10924                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
10925                                                   "AND a.attrelid = ct.typrelid "
10926                                                   "ORDER BY a.attnum ",
10927                                                   tyinfo->dobj.catId.oid);
10928         }
10929
10930         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10931
10932         ntups = PQntuples(res);
10933
10934         i_attname = PQfnumber(res, "attname");
10935         i_atttypdefn = PQfnumber(res, "atttypdefn");
10936         i_attlen = PQfnumber(res, "attlen");
10937         i_attalign = PQfnumber(res, "attalign");
10938         i_attisdropped = PQfnumber(res, "attisdropped");
10939         i_attcollation = PQfnumber(res, "attcollation");
10940
10941         if (dopt->binary_upgrade)
10942         {
10943                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10944                                                                                                  tyinfo->dobj.catId.oid,
10945                                                                                                  false);
10946                 binary_upgrade_set_pg_class_oids(fout, q, tyinfo->typrelid, false);
10947         }
10948
10949         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10950         qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10951
10952         appendPQExpBuffer(q, "CREATE TYPE %s AS (",
10953                                           qualtypname);
10954
10955         actual_atts = 0;
10956         for (i = 0; i < ntups; i++)
10957         {
10958                 char       *attname;
10959                 char       *atttypdefn;
10960                 char       *attlen;
10961                 char       *attalign;
10962                 bool            attisdropped;
10963                 Oid                     attcollation;
10964
10965                 attname = PQgetvalue(res, i, i_attname);
10966                 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
10967                 attlen = PQgetvalue(res, i, i_attlen);
10968                 attalign = PQgetvalue(res, i, i_attalign);
10969                 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
10970                 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
10971
10972                 if (attisdropped && !dopt->binary_upgrade)
10973                         continue;
10974
10975                 /* Format properly if not first attr */
10976                 if (actual_atts++ > 0)
10977                         appendPQExpBufferChar(q, ',');
10978                 appendPQExpBufferStr(q, "\n\t");
10979
10980                 if (!attisdropped)
10981                 {
10982                         appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
10983
10984                         /* Add collation if not default for the column type */
10985                         if (OidIsValid(attcollation))
10986                         {
10987                                 CollInfo   *coll;
10988
10989                                 coll = findCollationByOid(attcollation);
10990                                 if (coll)
10991                                         appendPQExpBuffer(q, " COLLATE %s",
10992                                                                           fmtQualifiedDumpable(coll));
10993                         }
10994                 }
10995                 else
10996                 {
10997                         /*
10998                          * This is a dropped attribute and we're in binary_upgrade mode.
10999                          * Insert a placeholder for it in the CREATE TYPE command, and set
11000                          * length and alignment with direct UPDATE to the catalogs
11001                          * afterwards. See similar code in dumpTableSchema().
11002                          */
11003                         appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
11004
11005                         /* stash separately for insertion after the CREATE TYPE */
11006                         appendPQExpBufferStr(dropped,
11007                                                                  "\n-- For binary upgrade, recreate dropped column.\n");
11008                         appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
11009                                                           "SET attlen = %s, "
11010                                                           "attalign = '%s', attbyval = false\n"
11011                                                           "WHERE attname = ", attlen, attalign);
11012                         appendStringLiteralAH(dropped, attname, fout);
11013                         appendPQExpBufferStr(dropped, "\n  AND attrelid = ");
11014                         appendStringLiteralAH(dropped, qualtypname, fout);
11015                         appendPQExpBufferStr(dropped, "::pg_catalog.regclass;\n");
11016
11017                         appendPQExpBuffer(dropped, "ALTER TYPE %s ",
11018                                                           qualtypname);
11019                         appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
11020                                                           fmtId(attname));
11021                 }
11022         }
11023         appendPQExpBufferStr(q, "\n);\n");
11024         appendPQExpBufferStr(q, dropped->data);
11025
11026         appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
11027
11028         if (dopt->binary_upgrade)
11029                 binary_upgrade_extension_member(q, &tyinfo->dobj,
11030                                                                                 "TYPE", qtypname,
11031                                                                                 tyinfo->dobj.namespace->dobj.name);
11032
11033         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11034                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11035                                          tyinfo->dobj.name,
11036                                          tyinfo->dobj.namespace->dobj.name,
11037                                          NULL,
11038                                          tyinfo->rolname, false,
11039                                          "TYPE", SECTION_PRE_DATA,
11040                                          q->data, delq->data, NULL,
11041                                          NULL, 0,
11042                                          NULL, NULL);
11043
11044
11045         /* Dump Type Comments and Security Labels */
11046         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11047                 dumpComment(fout, "TYPE", qtypname,
11048                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11049                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11050
11051         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11052                 dumpSecLabel(fout, "TYPE", qtypname,
11053                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11054                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11055
11056         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11057                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
11058                                 qtypname, NULL,
11059                                 tyinfo->dobj.namespace->dobj.name,
11060                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
11061                                 tyinfo->inittypacl, tyinfo->initrtypacl);
11062
11063         PQclear(res);
11064         destroyPQExpBuffer(q);
11065         destroyPQExpBuffer(dropped);
11066         destroyPQExpBuffer(delq);
11067         destroyPQExpBuffer(query);
11068         free(qtypname);
11069         free(qualtypname);
11070
11071         /* Dump any per-column comments */
11072         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11073                 dumpCompositeTypeColComments(fout, tyinfo);
11074 }
11075
11076 /*
11077  * dumpCompositeTypeColComments
11078  *        writes out to fout the queries to recreate comments on the columns of
11079  *        a user-defined stand-alone composite type
11080  */
11081 static void
11082 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
11083 {
11084         CommentItem *comments;
11085         int                     ncomments;
11086         PGresult   *res;
11087         PQExpBuffer query;
11088         PQExpBuffer target;
11089         Oid                     pgClassOid;
11090         int                     i;
11091         int                     ntups;
11092         int                     i_attname;
11093         int                     i_attnum;
11094
11095         /* do nothing, if --no-comments is supplied */
11096         if (fout->dopt->no_comments)
11097                 return;
11098
11099         query = createPQExpBuffer();
11100
11101         appendPQExpBuffer(query,
11102                                           "SELECT c.tableoid, a.attname, a.attnum "
11103                                           "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
11104                                           "WHERE c.oid = '%u' AND c.oid = a.attrelid "
11105                                           "  AND NOT a.attisdropped "
11106                                           "ORDER BY a.attnum ",
11107                                           tyinfo->typrelid);
11108
11109         /* Fetch column attnames */
11110         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11111
11112         ntups = PQntuples(res);
11113         if (ntups < 1)
11114         {
11115                 PQclear(res);
11116                 destroyPQExpBuffer(query);
11117                 return;
11118         }
11119
11120         pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
11121
11122         /* Search for comments associated with type's pg_class OID */
11123         ncomments = findComments(fout,
11124                                                          pgClassOid,
11125                                                          tyinfo->typrelid,
11126                                                          &comments);
11127
11128         /* If no comments exist, we're done */
11129         if (ncomments <= 0)
11130         {
11131                 PQclear(res);
11132                 destroyPQExpBuffer(query);
11133                 return;
11134         }
11135
11136         /* Build COMMENT ON statements */
11137         target = createPQExpBuffer();
11138
11139         i_attnum = PQfnumber(res, "attnum");
11140         i_attname = PQfnumber(res, "attname");
11141         while (ncomments > 0)
11142         {
11143                 const char *attname;
11144
11145                 attname = NULL;
11146                 for (i = 0; i < ntups; i++)
11147                 {
11148                         if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
11149                         {
11150                                 attname = PQgetvalue(res, i, i_attname);
11151                                 break;
11152                         }
11153                 }
11154                 if (attname)                    /* just in case we don't find it */
11155                 {
11156                         const char *descr = comments->descr;
11157
11158                         resetPQExpBuffer(target);
11159                         appendPQExpBuffer(target, "COLUMN %s.",
11160                                                           fmtId(tyinfo->dobj.name));
11161                         appendPQExpBufferStr(target, fmtId(attname));
11162
11163                         resetPQExpBuffer(query);
11164                         appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
11165                                                           fmtQualifiedDumpable(tyinfo));
11166                         appendPQExpBuffer(query, "%s IS ", fmtId(attname));
11167                         appendStringLiteralAH(query, descr, fout);
11168                         appendPQExpBufferStr(query, ";\n");
11169
11170                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
11171                                                  target->data,
11172                                                  tyinfo->dobj.namespace->dobj.name,
11173                                                  NULL, tyinfo->rolname,
11174                                                  false, "COMMENT", SECTION_NONE,
11175                                                  query->data, "", NULL,
11176                                                  &(tyinfo->dobj.dumpId), 1,
11177                                                  NULL, NULL);
11178                 }
11179
11180                 comments++;
11181                 ncomments--;
11182         }
11183
11184         PQclear(res);
11185         destroyPQExpBuffer(query);
11186         destroyPQExpBuffer(target);
11187 }
11188
11189 /*
11190  * dumpShellType
11191  *        writes out to fout the queries to create a shell type
11192  *
11193  * We dump a shell definition in advance of the I/O functions for the type.
11194  */
11195 static void
11196 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
11197 {
11198         DumpOptions *dopt = fout->dopt;
11199         PQExpBuffer q;
11200
11201         /* Skip if not to be dumped */
11202         if (!stinfo->dobj.dump || dopt->dataOnly)
11203                 return;
11204
11205         q = createPQExpBuffer();
11206
11207         /*
11208          * Note the lack of a DROP command for the shell type; any required DROP
11209          * is driven off the base type entry, instead.  This interacts with
11210          * _printTocEntry()'s use of the presence of a DROP command to decide
11211          * whether an entry needs an ALTER OWNER command.  We don't want to alter
11212          * the shell type's owner immediately on creation; that should happen only
11213          * after it's filled in, otherwise the backend complains.
11214          */
11215
11216         if (dopt->binary_upgrade)
11217                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
11218                                                                                                  stinfo->baseType->dobj.catId.oid,
11219                                                                                                  false);
11220
11221         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
11222                                           fmtQualifiedDumpable(stinfo));
11223
11224         if (stinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11225                 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
11226                                          stinfo->dobj.name,
11227                                          stinfo->dobj.namespace->dobj.name,
11228                                          NULL,
11229                                          stinfo->baseType->rolname, false,
11230                                          "SHELL TYPE", SECTION_PRE_DATA,
11231                                          q->data, "", NULL,
11232                                          NULL, 0,
11233                                          NULL, NULL);
11234
11235         destroyPQExpBuffer(q);
11236 }
11237
11238 /*
11239  * dumpProcLang
11240  *                writes out to fout the queries to recreate a user-defined
11241  *                procedural language
11242  */
11243 static void
11244 dumpProcLang(Archive *fout, ProcLangInfo *plang)
11245 {
11246         DumpOptions *dopt = fout->dopt;
11247         PQExpBuffer defqry;
11248         PQExpBuffer delqry;
11249         bool            useParams;
11250         char       *qlanname;
11251         FuncInfo   *funcInfo;
11252         FuncInfo   *inlineInfo = NULL;
11253         FuncInfo   *validatorInfo = NULL;
11254
11255         /* Skip if not to be dumped */
11256         if (!plang->dobj.dump || dopt->dataOnly)
11257                 return;
11258
11259         /*
11260          * Try to find the support function(s).  It is not an error if we don't
11261          * find them --- if the functions are in the pg_catalog schema, as is
11262          * standard in 8.1 and up, then we won't have loaded them. (In this case
11263          * we will emit a parameterless CREATE LANGUAGE command, which will
11264          * require PL template knowledge in the backend to reload.)
11265          */
11266
11267         funcInfo = findFuncByOid(plang->lanplcallfoid);
11268         if (funcInfo != NULL && !funcInfo->dobj.dump)
11269                 funcInfo = NULL;                /* treat not-dumped same as not-found */
11270
11271         if (OidIsValid(plang->laninline))
11272         {
11273                 inlineInfo = findFuncByOid(plang->laninline);
11274                 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
11275                         inlineInfo = NULL;
11276         }
11277
11278         if (OidIsValid(plang->lanvalidator))
11279         {
11280                 validatorInfo = findFuncByOid(plang->lanvalidator);
11281                 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
11282                         validatorInfo = NULL;
11283         }
11284
11285         /*
11286          * If the functions are dumpable then emit a traditional CREATE LANGUAGE
11287          * with parameters.  Otherwise, we'll write a parameterless command, which
11288          * will rely on data from pg_pltemplate.
11289          */
11290         useParams = (funcInfo != NULL &&
11291                                  (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
11292                                  (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
11293
11294         defqry = createPQExpBuffer();
11295         delqry = createPQExpBuffer();
11296
11297         qlanname = pg_strdup(fmtId(plang->dobj.name));
11298
11299         appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
11300                                           qlanname);
11301
11302         if (useParams)
11303         {
11304                 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
11305                                                   plang->lanpltrusted ? "TRUSTED " : "",
11306                                                   qlanname);
11307                 appendPQExpBuffer(defqry, " HANDLER %s",
11308                                                   fmtQualifiedDumpable(funcInfo));
11309                 if (OidIsValid(plang->laninline))
11310                         appendPQExpBuffer(defqry, " INLINE %s",
11311                                                           fmtQualifiedDumpable(inlineInfo));
11312                 if (OidIsValid(plang->lanvalidator))
11313                         appendPQExpBuffer(defqry, " VALIDATOR %s",
11314                                                           fmtQualifiedDumpable(validatorInfo));
11315         }
11316         else
11317         {
11318                 /*
11319                  * If not dumping parameters, then use CREATE OR REPLACE so that the
11320                  * command will not fail if the language is preinstalled in the target
11321                  * database.  We restrict the use of REPLACE to this case so as to
11322                  * eliminate the risk of replacing a language with incompatible
11323                  * parameter settings: this command will only succeed at all if there
11324                  * is a pg_pltemplate entry, and if there is one, the existing entry
11325                  * must match it too.
11326                  */
11327                 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
11328                                                   qlanname);
11329         }
11330         appendPQExpBufferStr(defqry, ";\n");
11331
11332         if (dopt->binary_upgrade)
11333                 binary_upgrade_extension_member(defqry, &plang->dobj,
11334                                                                                 "LANGUAGE", qlanname, NULL);
11335
11336         if (plang->dobj.dump & DUMP_COMPONENT_DEFINITION)
11337                 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
11338                                          plang->dobj.name,
11339                                          NULL, NULL, plang->lanowner,
11340                                          false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
11341                                          defqry->data, delqry->data, NULL,
11342                                          NULL, 0,
11343                                          NULL, NULL);
11344
11345         /* Dump Proc Lang Comments and Security Labels */
11346         if (plang->dobj.dump & DUMP_COMPONENT_COMMENT)
11347                 dumpComment(fout, "LANGUAGE", qlanname,
11348                                         NULL, plang->lanowner,
11349                                         plang->dobj.catId, 0, plang->dobj.dumpId);
11350
11351         if (plang->dobj.dump & DUMP_COMPONENT_SECLABEL)
11352                 dumpSecLabel(fout, "LANGUAGE", qlanname,
11353                                          NULL, plang->lanowner,
11354                                          plang->dobj.catId, 0, plang->dobj.dumpId);
11355
11356         if (plang->lanpltrusted && plang->dobj.dump & DUMP_COMPONENT_ACL)
11357                 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
11358                                 qlanname, NULL, NULL,
11359                                 plang->lanowner, plang->lanacl, plang->rlanacl,
11360                                 plang->initlanacl, plang->initrlanacl);
11361
11362         free(qlanname);
11363
11364         destroyPQExpBuffer(defqry);
11365         destroyPQExpBuffer(delqry);
11366 }
11367
11368 /*
11369  * format_function_arguments: generate function name and argument list
11370  *
11371  * This is used when we can rely on pg_get_function_arguments to format
11372  * the argument list.  Note, however, that pg_get_function_arguments
11373  * does not special-case zero-argument aggregates.
11374  */
11375 static char *
11376 format_function_arguments(FuncInfo *finfo, char *funcargs, bool is_agg)
11377 {
11378         PQExpBufferData fn;
11379
11380         initPQExpBuffer(&fn);
11381         appendPQExpBufferStr(&fn, fmtId(finfo->dobj.name));
11382         if (is_agg && finfo->nargs == 0)
11383                 appendPQExpBufferStr(&fn, "(*)");
11384         else
11385                 appendPQExpBuffer(&fn, "(%s)", funcargs);
11386         return fn.data;
11387 }
11388
11389 /*
11390  * format_function_arguments_old: generate function name and argument list
11391  *
11392  * The argument type names are qualified if needed.  The function name
11393  * is never qualified.
11394  *
11395  * This is used only with pre-8.4 servers, so we aren't expecting to see
11396  * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
11397  *
11398  * Any or all of allargtypes, argmodes, argnames may be NULL.
11399  */
11400 static char *
11401 format_function_arguments_old(Archive *fout,
11402                                                           FuncInfo *finfo, int nallargs,
11403                                                           char **allargtypes,
11404                                                           char **argmodes,
11405                                                           char **argnames)
11406 {
11407         PQExpBufferData fn;
11408         int                     j;
11409
11410         initPQExpBuffer(&fn);
11411         appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11412         for (j = 0; j < nallargs; j++)
11413         {
11414                 Oid                     typid;
11415                 char       *typname;
11416                 const char *argmode;
11417                 const char *argname;
11418
11419                 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
11420                 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
11421
11422                 if (argmodes)
11423                 {
11424                         switch (argmodes[j][0])
11425                         {
11426                                 case PROARGMODE_IN:
11427                                         argmode = "";
11428                                         break;
11429                                 case PROARGMODE_OUT:
11430                                         argmode = "OUT ";
11431                                         break;
11432                                 case PROARGMODE_INOUT:
11433                                         argmode = "INOUT ";
11434                                         break;
11435                                 default:
11436                                         write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
11437                                         argmode = "";
11438                                         break;
11439                         }
11440                 }
11441                 else
11442                         argmode = "";
11443
11444                 argname = argnames ? argnames[j] : (char *) NULL;
11445                 if (argname && argname[0] == '\0')
11446                         argname = NULL;
11447
11448                 appendPQExpBuffer(&fn, "%s%s%s%s%s",
11449                                                   (j > 0) ? ", " : "",
11450                                                   argmode,
11451                                                   argname ? fmtId(argname) : "",
11452                                                   argname ? " " : "",
11453                                                   typname);
11454                 free(typname);
11455         }
11456         appendPQExpBufferChar(&fn, ')');
11457         return fn.data;
11458 }
11459
11460 /*
11461  * format_function_signature: generate function name and argument list
11462  *
11463  * This is like format_function_arguments_old except that only a minimal
11464  * list of input argument types is generated; this is sufficient to
11465  * reference the function, but not to define it.
11466  *
11467  * If honor_quotes is false then the function name is never quoted.
11468  * This is appropriate for use in TOC tags, but not in SQL commands.
11469  */
11470 static char *
11471 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
11472 {
11473         PQExpBufferData fn;
11474         int                     j;
11475
11476         initPQExpBuffer(&fn);
11477         if (honor_quotes)
11478                 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11479         else
11480                 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
11481         for (j = 0; j < finfo->nargs; j++)
11482         {
11483                 char       *typname;
11484
11485                 if (j > 0)
11486                         appendPQExpBufferStr(&fn, ", ");
11487
11488                 typname = getFormattedTypeName(fout, finfo->argtypes[j],
11489                                                                            zeroAsOpaque);
11490                 appendPQExpBufferStr(&fn, typname);
11491                 free(typname);
11492         }
11493         appendPQExpBufferChar(&fn, ')');
11494         return fn.data;
11495 }
11496
11497
11498 /*
11499  * dumpFunc:
11500  *        dump out one function
11501  */
11502 static void
11503 dumpFunc(Archive *fout, FuncInfo *finfo)
11504 {
11505         DumpOptions *dopt = fout->dopt;
11506         PQExpBuffer query;
11507         PQExpBuffer q;
11508         PQExpBuffer delqry;
11509         PQExpBuffer asPart;
11510         PGresult   *res;
11511         char       *funcsig;            /* identity signature */
11512         char       *funcfullsig = NULL; /* full signature */
11513         char       *funcsig_tag;
11514         char       *proretset;
11515         char       *prosrc;
11516         char       *probin;
11517         char       *funcargs;
11518         char       *funciargs;
11519         char       *funcresult;
11520         char       *proallargtypes;
11521         char       *proargmodes;
11522         char       *proargnames;
11523         char       *protrftypes;
11524         char       *prokind;
11525         char       *provolatile;
11526         char       *proisstrict;
11527         char       *prosecdef;
11528         char       *proleakproof;
11529         char       *proconfig;
11530         char       *procost;
11531         char       *prorows;
11532         char       *proparallel;
11533         char       *lanname;
11534         char       *rettypename;
11535         int                     nallargs;
11536         char      **allargtypes = NULL;
11537         char      **argmodes = NULL;
11538         char      **argnames = NULL;
11539         char      **configitems = NULL;
11540         int                     nconfigitems = 0;
11541         const char *keyword;
11542         int                     i;
11543
11544         /* Skip if not to be dumped */
11545         if (!finfo->dobj.dump || dopt->dataOnly)
11546                 return;
11547
11548         query = createPQExpBuffer();
11549         q = createPQExpBuffer();
11550         delqry = createPQExpBuffer();
11551         asPart = createPQExpBuffer();
11552
11553         /* Fetch function-specific details */
11554         if (fout->remoteVersion >= 110000)
11555         {
11556                 /*
11557                  * prokind was added in 11
11558                  */
11559                 appendPQExpBuffer(query,
11560                                                   "SELECT proretset, prosrc, probin, "
11561                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11562                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11563                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11564                                                   "array_to_string(protrftypes, ' ') AS protrftypes, "
11565                                                   "prokind, provolatile, proisstrict, prosecdef, "
11566                                                   "proleakproof, proconfig, procost, prorows, "
11567                                                   "proparallel, "
11568                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11569                                                   "FROM pg_catalog.pg_proc "
11570                                                   "WHERE oid = '%u'::pg_catalog.oid",
11571                                                   finfo->dobj.catId.oid);
11572         }
11573         else if (fout->remoteVersion >= 90600)
11574         {
11575                 /*
11576                  * proparallel was added in 9.6
11577                  */
11578                 appendPQExpBuffer(query,
11579                                                   "SELECT proretset, prosrc, probin, "
11580                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11581                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11582                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11583                                                   "array_to_string(protrftypes, ' ') AS protrftypes, "
11584                                                   "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11585                                                   "provolatile, proisstrict, prosecdef, "
11586                                                   "proleakproof, proconfig, procost, prorows, "
11587                                                   "proparallel, "
11588                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11589                                                   "FROM pg_catalog.pg_proc "
11590                                                   "WHERE oid = '%u'::pg_catalog.oid",
11591                                                   finfo->dobj.catId.oid);
11592         }
11593         else if (fout->remoteVersion >= 90500)
11594         {
11595                 /*
11596                  * protrftypes was added in 9.5
11597                  */
11598                 appendPQExpBuffer(query,
11599                                                   "SELECT proretset, prosrc, probin, "
11600                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11601                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11602                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11603                                                   "array_to_string(protrftypes, ' ') AS protrftypes, "
11604                                                   "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11605                                                   "provolatile, proisstrict, prosecdef, "
11606                                                   "proleakproof, proconfig, procost, prorows, "
11607                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11608                                                   "FROM pg_catalog.pg_proc "
11609                                                   "WHERE oid = '%u'::pg_catalog.oid",
11610                                                   finfo->dobj.catId.oid);
11611         }
11612         else if (fout->remoteVersion >= 90200)
11613         {
11614                 /*
11615                  * proleakproof was added in 9.2
11616                  */
11617                 appendPQExpBuffer(query,
11618                                                   "SELECT proretset, prosrc, probin, "
11619                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11620                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11621                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11622                                                   "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11623                                                   "provolatile, proisstrict, prosecdef, "
11624                                                   "proleakproof, proconfig, procost, prorows, "
11625                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11626                                                   "FROM pg_catalog.pg_proc "
11627                                                   "WHERE oid = '%u'::pg_catalog.oid",
11628                                                   finfo->dobj.catId.oid);
11629         }
11630         else if (fout->remoteVersion >= 80400)
11631         {
11632                 /*
11633                  * In 8.4 and up we rely on pg_get_function_arguments and
11634                  * pg_get_function_result instead of examining proallargtypes etc.
11635                  */
11636                 appendPQExpBuffer(query,
11637                                                   "SELECT proretset, prosrc, probin, "
11638                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11639                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11640                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11641                                                   "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11642                                                   "provolatile, proisstrict, prosecdef, "
11643                                                   "false AS proleakproof, "
11644                                                   " proconfig, procost, prorows, "
11645                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11646                                                   "FROM pg_catalog.pg_proc "
11647                                                   "WHERE oid = '%u'::pg_catalog.oid",
11648                                                   finfo->dobj.catId.oid);
11649         }
11650         else if (fout->remoteVersion >= 80300)
11651         {
11652                 appendPQExpBuffer(query,
11653                                                   "SELECT proretset, prosrc, probin, "
11654                                                   "proallargtypes, proargmodes, proargnames, "
11655                                                   "'f' AS prokind, "
11656                                                   "provolatile, proisstrict, prosecdef, "
11657                                                   "false AS proleakproof, "
11658                                                   "proconfig, procost, prorows, "
11659                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11660                                                   "FROM pg_catalog.pg_proc "
11661                                                   "WHERE oid = '%u'::pg_catalog.oid",
11662                                                   finfo->dobj.catId.oid);
11663         }
11664         else if (fout->remoteVersion >= 80100)
11665         {
11666                 appendPQExpBuffer(query,
11667                                                   "SELECT proretset, prosrc, probin, "
11668                                                   "proallargtypes, proargmodes, proargnames, "
11669                                                   "'f' AS prokind, "
11670                                                   "provolatile, proisstrict, prosecdef, "
11671                                                   "false AS proleakproof, "
11672                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
11673                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11674                                                   "FROM pg_catalog.pg_proc "
11675                                                   "WHERE oid = '%u'::pg_catalog.oid",
11676                                                   finfo->dobj.catId.oid);
11677         }
11678         else
11679         {
11680                 appendPQExpBuffer(query,
11681                                                   "SELECT proretset, prosrc, probin, "
11682                                                   "null AS proallargtypes, "
11683                                                   "null AS proargmodes, "
11684                                                   "proargnames, "
11685                                                   "'f' AS prokind, "
11686                                                   "provolatile, proisstrict, prosecdef, "
11687                                                   "false AS proleakproof, "
11688                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
11689                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11690                                                   "FROM pg_catalog.pg_proc "
11691                                                   "WHERE oid = '%u'::pg_catalog.oid",
11692                                                   finfo->dobj.catId.oid);
11693         }
11694
11695         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11696
11697         proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
11698         prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
11699         probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
11700         if (fout->remoteVersion >= 80400)
11701         {
11702                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
11703                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
11704                 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
11705                 proallargtypes = proargmodes = proargnames = NULL;
11706         }
11707         else
11708         {
11709                 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
11710                 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
11711                 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
11712                 funcargs = funciargs = funcresult = NULL;
11713         }
11714         if (PQfnumber(res, "protrftypes") != -1)
11715                 protrftypes = PQgetvalue(res, 0, PQfnumber(res, "protrftypes"));
11716         else
11717                 protrftypes = NULL;
11718         prokind = PQgetvalue(res, 0, PQfnumber(res, "prokind"));
11719         provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
11720         proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
11721         prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
11722         proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
11723         proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
11724         procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
11725         prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
11726
11727         if (PQfnumber(res, "proparallel") != -1)
11728                 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
11729         else
11730                 proparallel = NULL;
11731
11732         lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
11733
11734         /*
11735          * See backend/commands/functioncmds.c for details of how the 'AS' clause
11736          * is used.  In 8.4 and up, an unused probin is NULL (here ""); previous
11737          * versions would set it to "-".  There are no known cases in which prosrc
11738          * is unused, so the tests below for "-" are probably useless.
11739          */
11740         if (probin[0] != '\0' && strcmp(probin, "-") != 0)
11741         {
11742                 appendPQExpBufferStr(asPart, "AS ");
11743                 appendStringLiteralAH(asPart, probin, fout);
11744                 if (strcmp(prosrc, "-") != 0)
11745                 {
11746                         appendPQExpBufferStr(asPart, ", ");
11747
11748                         /*
11749                          * where we have bin, use dollar quoting if allowed and src
11750                          * contains quote or backslash; else use regular quoting.
11751                          */
11752                         if (dopt->disable_dollar_quoting ||
11753                                 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
11754                                 appendStringLiteralAH(asPart, prosrc, fout);
11755                         else
11756                                 appendStringLiteralDQ(asPart, prosrc, NULL);
11757                 }
11758         }
11759         else
11760         {
11761                 if (strcmp(prosrc, "-") != 0)
11762                 {
11763                         appendPQExpBufferStr(asPart, "AS ");
11764                         /* with no bin, dollar quote src unconditionally if allowed */
11765                         if (dopt->disable_dollar_quoting)
11766                                 appendStringLiteralAH(asPart, prosrc, fout);
11767                         else
11768                                 appendStringLiteralDQ(asPart, prosrc, NULL);
11769                 }
11770         }
11771
11772         nallargs = finfo->nargs;        /* unless we learn different from allargs */
11773
11774         if (proallargtypes && *proallargtypes)
11775         {
11776                 int                     nitems = 0;
11777
11778                 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
11779                         nitems < finfo->nargs)
11780                 {
11781                         write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
11782                         if (allargtypes)
11783                                 free(allargtypes);
11784                         allargtypes = NULL;
11785                 }
11786                 else
11787                         nallargs = nitems;
11788         }
11789
11790         if (proargmodes && *proargmodes)
11791         {
11792                 int                     nitems = 0;
11793
11794                 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
11795                         nitems != nallargs)
11796                 {
11797                         write_msg(NULL, "WARNING: could not parse proargmodes array\n");
11798                         if (argmodes)
11799                                 free(argmodes);
11800                         argmodes = NULL;
11801                 }
11802         }
11803
11804         if (proargnames && *proargnames)
11805         {
11806                 int                     nitems = 0;
11807
11808                 if (!parsePGArray(proargnames, &argnames, &nitems) ||
11809                         nitems != nallargs)
11810                 {
11811                         write_msg(NULL, "WARNING: could not parse proargnames array\n");
11812                         if (argnames)
11813                                 free(argnames);
11814                         argnames = NULL;
11815                 }
11816         }
11817
11818         if (proconfig && *proconfig)
11819         {
11820                 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
11821                 {
11822                         write_msg(NULL, "WARNING: could not parse proconfig array\n");
11823                         if (configitems)
11824                                 free(configitems);
11825                         configitems = NULL;
11826                         nconfigitems = 0;
11827                 }
11828         }
11829
11830         if (funcargs)
11831         {
11832                 /* 8.4 or later; we rely on server-side code for most of the work */
11833                 funcfullsig = format_function_arguments(finfo, funcargs, false);
11834                 funcsig = format_function_arguments(finfo, funciargs, false);
11835         }
11836         else
11837                 /* pre-8.4, do it ourselves */
11838                 funcsig = format_function_arguments_old(fout,
11839                                                                                                 finfo, nallargs, allargtypes,
11840                                                                                                 argmodes, argnames);
11841
11842         funcsig_tag = format_function_signature(fout, finfo, false);
11843
11844         if (prokind[0] == PROKIND_PROCEDURE)
11845                 keyword = "PROCEDURE";
11846         else
11847                 keyword = "FUNCTION";   /* works for window functions too */
11848
11849         appendPQExpBuffer(delqry, "DROP %s %s.%s;\n",
11850                                           keyword,
11851                                           fmtId(finfo->dobj.namespace->dobj.name),
11852                                           funcsig);
11853
11854         appendPQExpBuffer(q, "CREATE %s %s.%s",
11855                                           keyword,
11856                                           fmtId(finfo->dobj.namespace->dobj.name),
11857                                           funcfullsig ? funcfullsig :
11858                                           funcsig);
11859
11860         if (prokind[0] == PROKIND_PROCEDURE)
11861                  /* no result type to output */ ;
11862         else if (funcresult)
11863                 appendPQExpBuffer(q, " RETURNS %s", funcresult);
11864         else
11865         {
11866                 rettypename = getFormattedTypeName(fout, finfo->prorettype,
11867                                                                                    zeroAsOpaque);
11868                 appendPQExpBuffer(q, " RETURNS %s%s",
11869                                                   (proretset[0] == 't') ? "SETOF " : "",
11870                                                   rettypename);
11871                 free(rettypename);
11872         }
11873
11874         appendPQExpBuffer(q, "\n    LANGUAGE %s", fmtId(lanname));
11875
11876         if (protrftypes != NULL && strcmp(protrftypes, "") != 0)
11877         {
11878                 Oid                *typeids = palloc(FUNC_MAX_ARGS * sizeof(Oid));
11879                 int                     i;
11880
11881                 appendPQExpBufferStr(q, " TRANSFORM ");
11882                 parseOidArray(protrftypes, typeids, FUNC_MAX_ARGS);
11883                 for (i = 0; typeids[i]; i++)
11884                 {
11885                         if (i != 0)
11886                                 appendPQExpBufferStr(q, ", ");
11887                         appendPQExpBuffer(q, "FOR TYPE %s",
11888                                                           getFormattedTypeName(fout, typeids[i], zeroAsNone));
11889                 }
11890         }
11891
11892         if (prokind[0] == PROKIND_WINDOW)
11893                 appendPQExpBufferStr(q, " WINDOW");
11894
11895         if (provolatile[0] != PROVOLATILE_VOLATILE)
11896         {
11897                 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
11898                         appendPQExpBufferStr(q, " IMMUTABLE");
11899                 else if (provolatile[0] == PROVOLATILE_STABLE)
11900                         appendPQExpBufferStr(q, " STABLE");
11901                 else if (provolatile[0] != PROVOLATILE_VOLATILE)
11902                         exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
11903                                                   finfo->dobj.name);
11904         }
11905
11906         if (proisstrict[0] == 't')
11907                 appendPQExpBufferStr(q, " STRICT");
11908
11909         if (prosecdef[0] == 't')
11910                 appendPQExpBufferStr(q, " SECURITY DEFINER");
11911
11912         if (proleakproof[0] == 't')
11913                 appendPQExpBufferStr(q, " LEAKPROOF");
11914
11915         /*
11916          * COST and ROWS are emitted only if present and not default, so as not to
11917          * break backwards-compatibility of the dump without need.  Keep this code
11918          * in sync with the defaults in functioncmds.c.
11919          */
11920         if (strcmp(procost, "0") != 0)
11921         {
11922                 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
11923                 {
11924                         /* default cost is 1 */
11925                         if (strcmp(procost, "1") != 0)
11926                                 appendPQExpBuffer(q, " COST %s", procost);
11927                 }
11928                 else
11929                 {
11930                         /* default cost is 100 */
11931                         if (strcmp(procost, "100") != 0)
11932                                 appendPQExpBuffer(q, " COST %s", procost);
11933                 }
11934         }
11935         if (proretset[0] == 't' &&
11936                 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
11937                 appendPQExpBuffer(q, " ROWS %s", prorows);
11938
11939         if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
11940         {
11941                 if (proparallel[0] == PROPARALLEL_SAFE)
11942                         appendPQExpBufferStr(q, " PARALLEL SAFE");
11943                 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
11944                         appendPQExpBufferStr(q, " PARALLEL RESTRICTED");
11945                 else if (proparallel[0] != PROPARALLEL_UNSAFE)
11946                         exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
11947                                                   finfo->dobj.name);
11948         }
11949
11950         for (i = 0; i < nconfigitems; i++)
11951         {
11952                 /* we feel free to scribble on configitems[] here */
11953                 char       *configitem = configitems[i];
11954                 char       *pos;
11955
11956                 pos = strchr(configitem, '=');
11957                 if (pos == NULL)
11958                         continue;
11959                 *pos++ = '\0';
11960                 appendPQExpBuffer(q, "\n    SET %s TO ", fmtId(configitem));
11961
11962                 /*
11963                  * Variables that are marked GUC_LIST_QUOTE were already fully quoted
11964                  * by flatten_set_variable_args() before they were put into the
11965                  * proconfig array.  However, because the quoting rules used there
11966                  * aren't exactly like SQL's, we have to break the list value apart
11967                  * and then quote the elements as string literals.  (The elements may
11968                  * be double-quoted as-is, but we can't just feed them to the SQL
11969                  * parser; it would do the wrong thing with elements that are
11970                  * zero-length or longer than NAMEDATALEN.)
11971                  *
11972                  * Variables that are not so marked should just be emitted as simple
11973                  * string literals.  If the variable is not known to
11974                  * variable_is_guc_list_quote(), we'll do that; this makes it unsafe
11975                  * to use GUC_LIST_QUOTE for extension variables.
11976                  */
11977                 if (variable_is_guc_list_quote(configitem))
11978                 {
11979                         char      **namelist;
11980                         char      **nameptr;
11981
11982                         /* Parse string into list of identifiers */
11983                         /* this shouldn't fail really */
11984                         if (SplitGUCList(pos, ',', &namelist))
11985                         {
11986                                 for (nameptr = namelist; *nameptr; nameptr++)
11987                                 {
11988                                         if (nameptr != namelist)
11989                                                 appendPQExpBufferStr(q, ", ");
11990                                         appendStringLiteralAH(q, *nameptr, fout);
11991                                 }
11992                         }
11993                         pg_free(namelist);
11994                 }
11995                 else
11996                         appendStringLiteralAH(q, pos, fout);
11997         }
11998
11999         appendPQExpBuffer(q, "\n    %s;\n", asPart->data);
12000
12001         if (dopt->binary_upgrade)
12002                 binary_upgrade_extension_member(q, &finfo->dobj,
12003                                                                                 keyword, funcsig,
12004                                                                                 finfo->dobj.namespace->dobj.name);
12005
12006         if (finfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12007                 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
12008                                          funcsig_tag,
12009                                          finfo->dobj.namespace->dobj.name,
12010                                          NULL,
12011                                          finfo->rolname, false,
12012                                          keyword, SECTION_PRE_DATA,
12013                                          q->data, delqry->data, NULL,
12014                                          NULL, 0,
12015                                          NULL, NULL);
12016
12017         /* Dump Function Comments and Security Labels */
12018         if (finfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12019                 dumpComment(fout, keyword, funcsig,
12020                                         finfo->dobj.namespace->dobj.name, finfo->rolname,
12021                                         finfo->dobj.catId, 0, finfo->dobj.dumpId);
12022
12023         if (finfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
12024                 dumpSecLabel(fout, keyword, funcsig,
12025                                          finfo->dobj.namespace->dobj.name, finfo->rolname,
12026                                          finfo->dobj.catId, 0, finfo->dobj.dumpId);
12027
12028         if (finfo->dobj.dump & DUMP_COMPONENT_ACL)
12029                 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, keyword,
12030                                 funcsig, NULL,
12031                                 finfo->dobj.namespace->dobj.name,
12032                                 finfo->rolname, finfo->proacl, finfo->rproacl,
12033                                 finfo->initproacl, finfo->initrproacl);
12034
12035         PQclear(res);
12036
12037         destroyPQExpBuffer(query);
12038         destroyPQExpBuffer(q);
12039         destroyPQExpBuffer(delqry);
12040         destroyPQExpBuffer(asPart);
12041         free(funcsig);
12042         if (funcfullsig)
12043                 free(funcfullsig);
12044         free(funcsig_tag);
12045         if (allargtypes)
12046                 free(allargtypes);
12047         if (argmodes)
12048                 free(argmodes);
12049         if (argnames)
12050                 free(argnames);
12051         if (configitems)
12052                 free(configitems);
12053 }
12054
12055
12056 /*
12057  * Dump a user-defined cast
12058  */
12059 static void
12060 dumpCast(Archive *fout, CastInfo *cast)
12061 {
12062         DumpOptions *dopt = fout->dopt;
12063         PQExpBuffer defqry;
12064         PQExpBuffer delqry;
12065         PQExpBuffer labelq;
12066         PQExpBuffer castargs;
12067         FuncInfo   *funcInfo = NULL;
12068         char       *sourceType;
12069         char       *targetType;
12070
12071         /* Skip if not to be dumped */
12072         if (!cast->dobj.dump || dopt->dataOnly)
12073                 return;
12074
12075         /* Cannot dump if we don't have the cast function's info */
12076         if (OidIsValid(cast->castfunc))
12077         {
12078                 funcInfo = findFuncByOid(cast->castfunc);
12079                 if (funcInfo == NULL)
12080                         exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12081                                                   cast->castfunc);
12082         }
12083
12084         defqry = createPQExpBuffer();
12085         delqry = createPQExpBuffer();
12086         labelq = createPQExpBuffer();
12087         castargs = createPQExpBuffer();
12088
12089         sourceType = getFormattedTypeName(fout, cast->castsource, zeroAsNone);
12090         targetType = getFormattedTypeName(fout, cast->casttarget, zeroAsNone);
12091         appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
12092                                           sourceType, targetType);
12093
12094         appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
12095                                           sourceType, targetType);
12096
12097         switch (cast->castmethod)
12098         {
12099                 case COERCION_METHOD_BINARY:
12100                         appendPQExpBufferStr(defqry, "WITHOUT FUNCTION");
12101                         break;
12102                 case COERCION_METHOD_INOUT:
12103                         appendPQExpBufferStr(defqry, "WITH INOUT");
12104                         break;
12105                 case COERCION_METHOD_FUNCTION:
12106                         if (funcInfo)
12107                         {
12108                                 char       *fsig = format_function_signature(fout, funcInfo, true);
12109
12110                                 /*
12111                                  * Always qualify the function name (format_function_signature
12112                                  * won't qualify it).
12113                                  */
12114                                 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
12115                                                                   fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
12116                                 free(fsig);
12117                         }
12118                         else
12119                                 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
12120                         break;
12121                 default:
12122                         write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
12123         }
12124
12125         if (cast->castcontext == 'a')
12126                 appendPQExpBufferStr(defqry, " AS ASSIGNMENT");
12127         else if (cast->castcontext == 'i')
12128                 appendPQExpBufferStr(defqry, " AS IMPLICIT");
12129         appendPQExpBufferStr(defqry, ";\n");
12130
12131         appendPQExpBuffer(labelq, "CAST (%s AS %s)",
12132                                           sourceType, targetType);
12133
12134         appendPQExpBuffer(castargs, "(%s AS %s)",
12135                                           sourceType, targetType);
12136
12137         if (dopt->binary_upgrade)
12138                 binary_upgrade_extension_member(defqry, &cast->dobj,
12139                                                                                 "CAST", castargs->data, NULL);
12140
12141         if (cast->dobj.dump & DUMP_COMPONENT_DEFINITION)
12142                 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
12143                                          labelq->data,
12144                                          NULL, NULL, "",
12145                                          false, "CAST", SECTION_PRE_DATA,
12146                                          defqry->data, delqry->data, NULL,
12147                                          NULL, 0,
12148                                          NULL, NULL);
12149
12150         /* Dump Cast Comments */
12151         if (cast->dobj.dump & DUMP_COMPONENT_COMMENT)
12152                 dumpComment(fout, "CAST", castargs->data,
12153                                         NULL, "",
12154                                         cast->dobj.catId, 0, cast->dobj.dumpId);
12155
12156         free(sourceType);
12157         free(targetType);
12158
12159         destroyPQExpBuffer(defqry);
12160         destroyPQExpBuffer(delqry);
12161         destroyPQExpBuffer(labelq);
12162         destroyPQExpBuffer(castargs);
12163 }
12164
12165 /*
12166  * Dump a transform
12167  */
12168 static void
12169 dumpTransform(Archive *fout, TransformInfo *transform)
12170 {
12171         DumpOptions *dopt = fout->dopt;
12172         PQExpBuffer defqry;
12173         PQExpBuffer delqry;
12174         PQExpBuffer labelq;
12175         PQExpBuffer transformargs;
12176         FuncInfo   *fromsqlFuncInfo = NULL;
12177         FuncInfo   *tosqlFuncInfo = NULL;
12178         char       *lanname;
12179         char       *transformType;
12180
12181         /* Skip if not to be dumped */
12182         if (!transform->dobj.dump || dopt->dataOnly)
12183                 return;
12184
12185         /* Cannot dump if we don't have the transform functions' info */
12186         if (OidIsValid(transform->trffromsql))
12187         {
12188                 fromsqlFuncInfo = findFuncByOid(transform->trffromsql);
12189                 if (fromsqlFuncInfo == NULL)
12190                         exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12191                                                   transform->trffromsql);
12192         }
12193         if (OidIsValid(transform->trftosql))
12194         {
12195                 tosqlFuncInfo = findFuncByOid(transform->trftosql);
12196                 if (tosqlFuncInfo == NULL)
12197                         exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12198                                                   transform->trftosql);
12199         }
12200
12201         defqry = createPQExpBuffer();
12202         delqry = createPQExpBuffer();
12203         labelq = createPQExpBuffer();
12204         transformargs = createPQExpBuffer();
12205
12206         lanname = get_language_name(fout, transform->trflang);
12207         transformType = getFormattedTypeName(fout, transform->trftype, zeroAsNone);
12208
12209         appendPQExpBuffer(delqry, "DROP TRANSFORM FOR %s LANGUAGE %s;\n",
12210                                           transformType, lanname);
12211
12212         appendPQExpBuffer(defqry, "CREATE TRANSFORM FOR %s LANGUAGE %s (",
12213                                           transformType, lanname);
12214
12215         if (!transform->trffromsql && !transform->trftosql)
12216                 write_msg(NULL, "WARNING: bogus transform definition, at least one of trffromsql and trftosql should be nonzero\n");
12217
12218         if (transform->trffromsql)
12219         {
12220                 if (fromsqlFuncInfo)
12221                 {
12222                         char       *fsig = format_function_signature(fout, fromsqlFuncInfo, true);
12223
12224                         /*
12225                          * Always qualify the function name (format_function_signature
12226                          * won't qualify it).
12227                          */
12228                         appendPQExpBuffer(defqry, "FROM SQL WITH FUNCTION %s.%s",
12229                                                           fmtId(fromsqlFuncInfo->dobj.namespace->dobj.name), fsig);
12230                         free(fsig);
12231                 }
12232                 else
12233                         write_msg(NULL, "WARNING: bogus value in pg_transform.trffromsql field\n");
12234         }
12235
12236         if (transform->trftosql)
12237         {
12238                 if (transform->trffromsql)
12239                         appendPQExpBuffer(defqry, ", ");
12240
12241                 if (tosqlFuncInfo)
12242                 {
12243                         char       *fsig = format_function_signature(fout, tosqlFuncInfo, true);
12244
12245                         /*
12246                          * Always qualify the function name (format_function_signature
12247                          * won't qualify it).
12248                          */
12249                         appendPQExpBuffer(defqry, "TO SQL WITH FUNCTION %s.%s",
12250                                                           fmtId(tosqlFuncInfo->dobj.namespace->dobj.name), fsig);
12251                         free(fsig);
12252                 }
12253                 else
12254                         write_msg(NULL, "WARNING: bogus value in pg_transform.trftosql field\n");
12255         }
12256
12257         appendPQExpBuffer(defqry, ");\n");
12258
12259         appendPQExpBuffer(labelq, "TRANSFORM FOR %s LANGUAGE %s",
12260                                           transformType, lanname);
12261
12262         appendPQExpBuffer(transformargs, "FOR %s LANGUAGE %s",
12263                                           transformType, lanname);
12264
12265         if (dopt->binary_upgrade)
12266                 binary_upgrade_extension_member(defqry, &transform->dobj,
12267                                                                                 "TRANSFORM", transformargs->data, NULL);
12268
12269         if (transform->dobj.dump & DUMP_COMPONENT_DEFINITION)
12270                 ArchiveEntry(fout, transform->dobj.catId, transform->dobj.dumpId,
12271                                          labelq->data,
12272                                          NULL, NULL, "",
12273                                          false, "TRANSFORM", SECTION_PRE_DATA,
12274                                          defqry->data, delqry->data, NULL,
12275                                          transform->dobj.dependencies, transform->dobj.nDeps,
12276                                          NULL, NULL);
12277
12278         /* Dump Transform Comments */
12279         if (transform->dobj.dump & DUMP_COMPONENT_COMMENT)
12280                 dumpComment(fout, "TRANSFORM", transformargs->data,
12281                                         NULL, "",
12282                                         transform->dobj.catId, 0, transform->dobj.dumpId);
12283
12284         free(lanname);
12285         free(transformType);
12286         destroyPQExpBuffer(defqry);
12287         destroyPQExpBuffer(delqry);
12288         destroyPQExpBuffer(labelq);
12289         destroyPQExpBuffer(transformargs);
12290 }
12291
12292
12293 /*
12294  * dumpOpr
12295  *        write out a single operator definition
12296  */
12297 static void
12298 dumpOpr(Archive *fout, OprInfo *oprinfo)
12299 {
12300         DumpOptions *dopt = fout->dopt;
12301         PQExpBuffer query;
12302         PQExpBuffer q;
12303         PQExpBuffer delq;
12304         PQExpBuffer oprid;
12305         PQExpBuffer details;
12306         PGresult   *res;
12307         int                     i_oprkind;
12308         int                     i_oprcode;
12309         int                     i_oprleft;
12310         int                     i_oprright;
12311         int                     i_oprcom;
12312         int                     i_oprnegate;
12313         int                     i_oprrest;
12314         int                     i_oprjoin;
12315         int                     i_oprcanmerge;
12316         int                     i_oprcanhash;
12317         char       *oprkind;
12318         char       *oprcode;
12319         char       *oprleft;
12320         char       *oprright;
12321         char       *oprcom;
12322         char       *oprnegate;
12323         char       *oprrest;
12324         char       *oprjoin;
12325         char       *oprcanmerge;
12326         char       *oprcanhash;
12327         char       *oprregproc;
12328         char       *oprref;
12329
12330         /* Skip if not to be dumped */
12331         if (!oprinfo->dobj.dump || dopt->dataOnly)
12332                 return;
12333
12334         /*
12335          * some operators are invalid because they were the result of user
12336          * defining operators before commutators exist
12337          */
12338         if (!OidIsValid(oprinfo->oprcode))
12339                 return;
12340
12341         query = createPQExpBuffer();
12342         q = createPQExpBuffer();
12343         delq = createPQExpBuffer();
12344         oprid = createPQExpBuffer();
12345         details = createPQExpBuffer();
12346
12347         if (fout->remoteVersion >= 80300)
12348         {
12349                 appendPQExpBuffer(query, "SELECT oprkind, "
12350                                                   "oprcode::pg_catalog.regprocedure, "
12351                                                   "oprleft::pg_catalog.regtype, "
12352                                                   "oprright::pg_catalog.regtype, "
12353                                                   "oprcom, "
12354                                                   "oprnegate, "
12355                                                   "oprrest::pg_catalog.regprocedure, "
12356                                                   "oprjoin::pg_catalog.regprocedure, "
12357                                                   "oprcanmerge, oprcanhash "
12358                                                   "FROM pg_catalog.pg_operator "
12359                                                   "WHERE oid = '%u'::pg_catalog.oid",
12360                                                   oprinfo->dobj.catId.oid);
12361         }
12362         else
12363         {
12364                 appendPQExpBuffer(query, "SELECT oprkind, "
12365                                                   "oprcode::pg_catalog.regprocedure, "
12366                                                   "oprleft::pg_catalog.regtype, "
12367                                                   "oprright::pg_catalog.regtype, "
12368                                                   "oprcom, "
12369                                                   "oprnegate, "
12370                                                   "oprrest::pg_catalog.regprocedure, "
12371                                                   "oprjoin::pg_catalog.regprocedure, "
12372                                                   "(oprlsortop != 0) AS oprcanmerge, "
12373                                                   "oprcanhash "
12374                                                   "FROM pg_catalog.pg_operator "
12375                                                   "WHERE oid = '%u'::pg_catalog.oid",
12376                                                   oprinfo->dobj.catId.oid);
12377         }
12378
12379         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12380
12381         i_oprkind = PQfnumber(res, "oprkind");
12382         i_oprcode = PQfnumber(res, "oprcode");
12383         i_oprleft = PQfnumber(res, "oprleft");
12384         i_oprright = PQfnumber(res, "oprright");
12385         i_oprcom = PQfnumber(res, "oprcom");
12386         i_oprnegate = PQfnumber(res, "oprnegate");
12387         i_oprrest = PQfnumber(res, "oprrest");
12388         i_oprjoin = PQfnumber(res, "oprjoin");
12389         i_oprcanmerge = PQfnumber(res, "oprcanmerge");
12390         i_oprcanhash = PQfnumber(res, "oprcanhash");
12391
12392         oprkind = PQgetvalue(res, 0, i_oprkind);
12393         oprcode = PQgetvalue(res, 0, i_oprcode);
12394         oprleft = PQgetvalue(res, 0, i_oprleft);
12395         oprright = PQgetvalue(res, 0, i_oprright);
12396         oprcom = PQgetvalue(res, 0, i_oprcom);
12397         oprnegate = PQgetvalue(res, 0, i_oprnegate);
12398         oprrest = PQgetvalue(res, 0, i_oprrest);
12399         oprjoin = PQgetvalue(res, 0, i_oprjoin);
12400         oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
12401         oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
12402
12403         oprregproc = convertRegProcReference(fout, oprcode);
12404         if (oprregproc)
12405         {
12406                 appendPQExpBuffer(details, "    PROCEDURE = %s", oprregproc);
12407                 free(oprregproc);
12408         }
12409
12410         appendPQExpBuffer(oprid, "%s (",
12411                                           oprinfo->dobj.name);
12412
12413         /*
12414          * right unary means there's a left arg and left unary means there's a
12415          * right arg
12416          */
12417         if (strcmp(oprkind, "r") == 0 ||
12418                 strcmp(oprkind, "b") == 0)
12419         {
12420                 appendPQExpBuffer(details, ",\n    LEFTARG = %s", oprleft);
12421                 appendPQExpBufferStr(oprid, oprleft);
12422         }
12423         else
12424                 appendPQExpBufferStr(oprid, "NONE");
12425
12426         if (strcmp(oprkind, "l") == 0 ||
12427                 strcmp(oprkind, "b") == 0)
12428         {
12429                 appendPQExpBuffer(details, ",\n    RIGHTARG = %s", oprright);
12430                 appendPQExpBuffer(oprid, ", %s)", oprright);
12431         }
12432         else
12433                 appendPQExpBufferStr(oprid, ", NONE)");
12434
12435         oprref = getFormattedOperatorName(fout, oprcom);
12436         if (oprref)
12437         {
12438                 appendPQExpBuffer(details, ",\n    COMMUTATOR = %s", oprref);
12439                 free(oprref);
12440         }
12441
12442         oprref = getFormattedOperatorName(fout, oprnegate);
12443         if (oprref)
12444         {
12445                 appendPQExpBuffer(details, ",\n    NEGATOR = %s", oprref);
12446                 free(oprref);
12447         }
12448
12449         if (strcmp(oprcanmerge, "t") == 0)
12450                 appendPQExpBufferStr(details, ",\n    MERGES");
12451
12452         if (strcmp(oprcanhash, "t") == 0)
12453                 appendPQExpBufferStr(details, ",\n    HASHES");
12454
12455         oprregproc = convertRegProcReference(fout, oprrest);
12456         if (oprregproc)
12457         {
12458                 appendPQExpBuffer(details, ",\n    RESTRICT = %s", oprregproc);
12459                 free(oprregproc);
12460         }
12461
12462         oprregproc = convertRegProcReference(fout, oprjoin);
12463         if (oprregproc)
12464         {
12465                 appendPQExpBuffer(details, ",\n    JOIN = %s", oprregproc);
12466                 free(oprregproc);
12467         }
12468
12469         appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
12470                                           fmtId(oprinfo->dobj.namespace->dobj.name),
12471                                           oprid->data);
12472
12473         appendPQExpBuffer(q, "CREATE OPERATOR %s.%s (\n%s\n);\n",
12474                                           fmtId(oprinfo->dobj.namespace->dobj.name),
12475                                           oprinfo->dobj.name, details->data);
12476
12477         if (dopt->binary_upgrade)
12478                 binary_upgrade_extension_member(q, &oprinfo->dobj,
12479                                                                                 "OPERATOR", oprid->data,
12480                                                                                 oprinfo->dobj.namespace->dobj.name);
12481
12482         if (oprinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12483                 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
12484                                          oprinfo->dobj.name,
12485                                          oprinfo->dobj.namespace->dobj.name,
12486                                          NULL,
12487                                          oprinfo->rolname,
12488                                          false, "OPERATOR", SECTION_PRE_DATA,
12489                                          q->data, delq->data, NULL,
12490                                          NULL, 0,
12491                                          NULL, NULL);
12492
12493         /* Dump Operator Comments */
12494         if (oprinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12495                 dumpComment(fout, "OPERATOR", oprid->data,
12496                                         oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
12497                                         oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
12498
12499         PQclear(res);
12500
12501         destroyPQExpBuffer(query);
12502         destroyPQExpBuffer(q);
12503         destroyPQExpBuffer(delq);
12504         destroyPQExpBuffer(oprid);
12505         destroyPQExpBuffer(details);
12506 }
12507
12508 /*
12509  * Convert a function reference obtained from pg_operator
12510  *
12511  * Returns allocated string of what to print, or NULL if function references
12512  * is InvalidOid. Returned string is expected to be free'd by the caller.
12513  *
12514  * The input is a REGPROCEDURE display; we have to strip the argument-types
12515  * part.
12516  */
12517 static char *
12518 convertRegProcReference(Archive *fout, const char *proc)
12519 {
12520         char       *name;
12521         char       *paren;
12522         bool            inquote;
12523
12524         /* In all cases "-" means a null reference */
12525         if (strcmp(proc, "-") == 0)
12526                 return NULL;
12527
12528         name = pg_strdup(proc);
12529         /* find non-double-quoted left paren */
12530         inquote = false;
12531         for (paren = name; *paren; paren++)
12532         {
12533                 if (*paren == '(' && !inquote)
12534                 {
12535                         *paren = '\0';
12536                         break;
12537                 }
12538                 if (*paren == '"')
12539                         inquote = !inquote;
12540         }
12541         return name;
12542 }
12543
12544 /*
12545  * getFormattedOperatorName - retrieve the operator name for the
12546  * given operator OID (presented in string form).
12547  *
12548  * Returns an allocated string, or NULL if the given OID is invalid.
12549  * Caller is responsible for free'ing result string.
12550  *
12551  * What we produce has the format "OPERATOR(schema.oprname)".  This is only
12552  * useful in commands where the operator's argument types can be inferred from
12553  * context.  We always schema-qualify the name, though.  The predecessor to
12554  * this code tried to skip the schema qualification if possible, but that led
12555  * to wrong results in corner cases, such as if an operator and its negator
12556  * are in different schemas.
12557  */
12558 static char *
12559 getFormattedOperatorName(Archive *fout, const char *oproid)
12560 {
12561         OprInfo    *oprInfo;
12562
12563         /* In all cases "0" means a null reference */
12564         if (strcmp(oproid, "0") == 0)
12565                 return NULL;
12566
12567         oprInfo = findOprByOid(atooid(oproid));
12568         if (oprInfo == NULL)
12569         {
12570                 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
12571                                   oproid);
12572                 return NULL;
12573         }
12574
12575         return psprintf("OPERATOR(%s.%s)",
12576                                         fmtId(oprInfo->dobj.namespace->dobj.name),
12577                                         oprInfo->dobj.name);
12578 }
12579
12580 /*
12581  * Convert a function OID obtained from pg_ts_parser or pg_ts_template
12582  *
12583  * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
12584  * argument lists of these functions are predetermined.  Note that the
12585  * caller should ensure we are in the proper schema, because the results
12586  * are search path dependent!
12587  */
12588 static char *
12589 convertTSFunction(Archive *fout, Oid funcOid)
12590 {
12591         char       *result;
12592         char            query[128];
12593         PGresult   *res;
12594
12595         snprintf(query, sizeof(query),
12596                          "SELECT '%u'::pg_catalog.regproc", funcOid);
12597         res = ExecuteSqlQueryForSingleRow(fout, query);
12598
12599         result = pg_strdup(PQgetvalue(res, 0, 0));
12600
12601         PQclear(res);
12602
12603         return result;
12604 }
12605
12606 /*
12607  * dumpAccessMethod
12608  *        write out a single access method definition
12609  */
12610 static void
12611 dumpAccessMethod(Archive *fout, AccessMethodInfo *aminfo)
12612 {
12613         DumpOptions *dopt = fout->dopt;
12614         PQExpBuffer q;
12615         PQExpBuffer delq;
12616         char       *qamname;
12617
12618         /* Skip if not to be dumped */
12619         if (!aminfo->dobj.dump || dopt->dataOnly)
12620                 return;
12621
12622         q = createPQExpBuffer();
12623         delq = createPQExpBuffer();
12624
12625         qamname = pg_strdup(fmtId(aminfo->dobj.name));
12626
12627         appendPQExpBuffer(q, "CREATE ACCESS METHOD %s ", qamname);
12628
12629         switch (aminfo->amtype)
12630         {
12631                 case AMTYPE_INDEX:
12632                         appendPQExpBuffer(q, "TYPE INDEX ");
12633                         break;
12634                 default:
12635                         write_msg(NULL, "WARNING: invalid type \"%c\" of access method \"%s\"\n",
12636                                           aminfo->amtype, qamname);
12637                         destroyPQExpBuffer(q);
12638                         destroyPQExpBuffer(delq);
12639                         free(qamname);
12640                         return;
12641         }
12642
12643         appendPQExpBuffer(q, "HANDLER %s;\n", aminfo->amhandler);
12644
12645         appendPQExpBuffer(delq, "DROP ACCESS METHOD %s;\n",
12646                                           qamname);
12647
12648         if (dopt->binary_upgrade)
12649                 binary_upgrade_extension_member(q, &aminfo->dobj,
12650                                                                                 "ACCESS METHOD", qamname, NULL);
12651
12652         if (aminfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12653                 ArchiveEntry(fout, aminfo->dobj.catId, aminfo->dobj.dumpId,
12654                                          aminfo->dobj.name,
12655                                          NULL,
12656                                          NULL,
12657                                          "",
12658                                          false, "ACCESS METHOD", SECTION_PRE_DATA,
12659                                          q->data, delq->data, NULL,
12660                                          NULL, 0,
12661                                          NULL, NULL);
12662
12663         /* Dump Access Method Comments */
12664         if (aminfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12665                 dumpComment(fout, "ACCESS METHOD", qamname,
12666                                         NULL, "",
12667                                         aminfo->dobj.catId, 0, aminfo->dobj.dumpId);
12668
12669         destroyPQExpBuffer(q);
12670         destroyPQExpBuffer(delq);
12671         free(qamname);
12672 }
12673
12674 /*
12675  * dumpOpclass
12676  *        write out a single operator class definition
12677  */
12678 static void
12679 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
12680 {
12681         DumpOptions *dopt = fout->dopt;
12682         PQExpBuffer query;
12683         PQExpBuffer q;
12684         PQExpBuffer delq;
12685         PQExpBuffer nameusing;
12686         PGresult   *res;
12687         int                     ntups;
12688         int                     i_opcintype;
12689         int                     i_opckeytype;
12690         int                     i_opcdefault;
12691         int                     i_opcfamily;
12692         int                     i_opcfamilyname;
12693         int                     i_opcfamilynsp;
12694         int                     i_amname;
12695         int                     i_amopstrategy;
12696         int                     i_amopreqcheck;
12697         int                     i_amopopr;
12698         int                     i_sortfamily;
12699         int                     i_sortfamilynsp;
12700         int                     i_amprocnum;
12701         int                     i_amproc;
12702         int                     i_amproclefttype;
12703         int                     i_amprocrighttype;
12704         char       *opcintype;
12705         char       *opckeytype;
12706         char       *opcdefault;
12707         char       *opcfamily;
12708         char       *opcfamilyname;
12709         char       *opcfamilynsp;
12710         char       *amname;
12711         char       *amopstrategy;
12712         char       *amopreqcheck;
12713         char       *amopopr;
12714         char       *sortfamily;
12715         char       *sortfamilynsp;
12716         char       *amprocnum;
12717         char       *amproc;
12718         char       *amproclefttype;
12719         char       *amprocrighttype;
12720         bool            needComma;
12721         int                     i;
12722
12723         /* Skip if not to be dumped */
12724         if (!opcinfo->dobj.dump || dopt->dataOnly)
12725                 return;
12726
12727         query = createPQExpBuffer();
12728         q = createPQExpBuffer();
12729         delq = createPQExpBuffer();
12730         nameusing = createPQExpBuffer();
12731
12732         /* Get additional fields from the pg_opclass row */
12733         if (fout->remoteVersion >= 80300)
12734         {
12735                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12736                                                   "opckeytype::pg_catalog.regtype, "
12737                                                   "opcdefault, opcfamily, "
12738                                                   "opfname AS opcfamilyname, "
12739                                                   "nspname AS opcfamilynsp, "
12740                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
12741                                                   "FROM pg_catalog.pg_opclass c "
12742                                                   "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
12743                                                   "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12744                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
12745                                                   opcinfo->dobj.catId.oid);
12746         }
12747         else
12748         {
12749                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12750                                                   "opckeytype::pg_catalog.regtype, "
12751                                                   "opcdefault, NULL AS opcfamily, "
12752                                                   "NULL AS opcfamilyname, "
12753                                                   "NULL AS opcfamilynsp, "
12754                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
12755                                                   "FROM pg_catalog.pg_opclass "
12756                                                   "WHERE oid = '%u'::pg_catalog.oid",
12757                                                   opcinfo->dobj.catId.oid);
12758         }
12759
12760         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12761
12762         i_opcintype = PQfnumber(res, "opcintype");
12763         i_opckeytype = PQfnumber(res, "opckeytype");
12764         i_opcdefault = PQfnumber(res, "opcdefault");
12765         i_opcfamily = PQfnumber(res, "opcfamily");
12766         i_opcfamilyname = PQfnumber(res, "opcfamilyname");
12767         i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
12768         i_amname = PQfnumber(res, "amname");
12769
12770         /* opcintype may still be needed after we PQclear res */
12771         opcintype = pg_strdup(PQgetvalue(res, 0, i_opcintype));
12772         opckeytype = PQgetvalue(res, 0, i_opckeytype);
12773         opcdefault = PQgetvalue(res, 0, i_opcdefault);
12774         /* opcfamily will still be needed after we PQclear res */
12775         opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
12776         opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
12777         opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
12778         /* amname will still be needed after we PQclear res */
12779         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
12780
12781         appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
12782                                           fmtQualifiedDumpable(opcinfo));
12783         appendPQExpBuffer(delq, " USING %s;\n",
12784                                           fmtId(amname));
12785
12786         /* Build the fixed portion of the CREATE command */
12787         appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n    ",
12788                                           fmtQualifiedDumpable(opcinfo));
12789         if (strcmp(opcdefault, "t") == 0)
12790                 appendPQExpBufferStr(q, "DEFAULT ");
12791         appendPQExpBuffer(q, "FOR TYPE %s USING %s",
12792                                           opcintype,
12793                                           fmtId(amname));
12794         if (strlen(opcfamilyname) > 0)
12795         {
12796                 appendPQExpBufferStr(q, " FAMILY ");
12797                 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
12798                 appendPQExpBufferStr(q, fmtId(opcfamilyname));
12799         }
12800         appendPQExpBufferStr(q, " AS\n    ");
12801
12802         needComma = false;
12803
12804         if (strcmp(opckeytype, "-") != 0)
12805         {
12806                 appendPQExpBuffer(q, "STORAGE %s",
12807                                                   opckeytype);
12808                 needComma = true;
12809         }
12810
12811         PQclear(res);
12812
12813         /*
12814          * Now fetch and print the OPERATOR entries (pg_amop rows).
12815          *
12816          * Print only those opfamily members that are tied to the opclass by
12817          * pg_depend entries.
12818          *
12819          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
12820          * older server's opclass in which it is used.  This is to avoid
12821          * hard-to-detect breakage if a newer pg_dump is used to dump from an
12822          * older server and then reload into that old version.  This can go away
12823          * once 8.3 is so old as to not be of interest to anyone.
12824          */
12825         resetPQExpBuffer(query);
12826
12827         if (fout->remoteVersion >= 90100)
12828         {
12829                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12830                                                   "amopopr::pg_catalog.regoperator, "
12831                                                   "opfname AS sortfamily, "
12832                                                   "nspname AS sortfamilynsp "
12833                                                   "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
12834                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
12835                                                   "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
12836                                                   "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12837                                                   "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12838                                                   "AND refobjid = '%u'::pg_catalog.oid "
12839                                                   "AND amopfamily = '%s'::pg_catalog.oid "
12840                                                   "ORDER BY amopstrategy",
12841                                                   opcinfo->dobj.catId.oid,
12842                                                   opcfamily);
12843         }
12844         else if (fout->remoteVersion >= 80400)
12845         {
12846                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12847                                                   "amopopr::pg_catalog.regoperator, "
12848                                                   "NULL AS sortfamily, "
12849                                                   "NULL AS sortfamilynsp "
12850                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12851                                                   "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12852                                                   "AND refobjid = '%u'::pg_catalog.oid "
12853                                                   "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12854                                                   "AND objid = ao.oid "
12855                                                   "ORDER BY amopstrategy",
12856                                                   opcinfo->dobj.catId.oid);
12857         }
12858         else if (fout->remoteVersion >= 80300)
12859         {
12860                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12861                                                   "amopopr::pg_catalog.regoperator, "
12862                                                   "NULL AS sortfamily, "
12863                                                   "NULL AS sortfamilynsp "
12864                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12865                                                   "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12866                                                   "AND refobjid = '%u'::pg_catalog.oid "
12867                                                   "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12868                                                   "AND objid = ao.oid "
12869                                                   "ORDER BY amopstrategy",
12870                                                   opcinfo->dobj.catId.oid);
12871         }
12872         else
12873         {
12874                 /*
12875                  * Here, we print all entries since there are no opfamilies and hence
12876                  * no loose operators to worry about.
12877                  */
12878                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12879                                                   "amopopr::pg_catalog.regoperator, "
12880                                                   "NULL AS sortfamily, "
12881                                                   "NULL AS sortfamilynsp "
12882                                                   "FROM pg_catalog.pg_amop "
12883                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
12884                                                   "ORDER BY amopstrategy",
12885                                                   opcinfo->dobj.catId.oid);
12886         }
12887
12888         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12889
12890         ntups = PQntuples(res);
12891
12892         i_amopstrategy = PQfnumber(res, "amopstrategy");
12893         i_amopreqcheck = PQfnumber(res, "amopreqcheck");
12894         i_amopopr = PQfnumber(res, "amopopr");
12895         i_sortfamily = PQfnumber(res, "sortfamily");
12896         i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
12897
12898         for (i = 0; i < ntups; i++)
12899         {
12900                 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
12901                 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
12902                 amopopr = PQgetvalue(res, i, i_amopopr);
12903                 sortfamily = PQgetvalue(res, i, i_sortfamily);
12904                 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
12905
12906                 if (needComma)
12907                         appendPQExpBufferStr(q, " ,\n    ");
12908
12909                 appendPQExpBuffer(q, "OPERATOR %s %s",
12910                                                   amopstrategy, amopopr);
12911
12912                 if (strlen(sortfamily) > 0)
12913                 {
12914                         appendPQExpBufferStr(q, " FOR ORDER BY ");
12915                         appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
12916                         appendPQExpBufferStr(q, fmtId(sortfamily));
12917                 }
12918
12919                 if (strcmp(amopreqcheck, "t") == 0)
12920                         appendPQExpBufferStr(q, " RECHECK");
12921
12922                 needComma = true;
12923         }
12924
12925         PQclear(res);
12926
12927         /*
12928          * Now fetch and print the FUNCTION entries (pg_amproc rows).
12929          *
12930          * Print only those opfamily members that are tied to the opclass by
12931          * pg_depend entries.
12932          *
12933          * We print the amproclefttype/amprocrighttype even though in most cases
12934          * the backend could deduce the right values, because of the corner case
12935          * of a btree sort support function for a cross-type comparison.  That's
12936          * only allowed in 9.2 and later, but for simplicity print them in all
12937          * versions that have the columns.
12938          */
12939         resetPQExpBuffer(query);
12940
12941         if (fout->remoteVersion >= 80300)
12942         {
12943                 appendPQExpBuffer(query, "SELECT amprocnum, "
12944                                                   "amproc::pg_catalog.regprocedure, "
12945                                                   "amproclefttype::pg_catalog.regtype, "
12946                                                   "amprocrighttype::pg_catalog.regtype "
12947                                                   "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
12948                                                   "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12949                                                   "AND refobjid = '%u'::pg_catalog.oid "
12950                                                   "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
12951                                                   "AND objid = ap.oid "
12952                                                   "ORDER BY amprocnum",
12953                                                   opcinfo->dobj.catId.oid);
12954         }
12955         else
12956         {
12957                 appendPQExpBuffer(query, "SELECT amprocnum, "
12958                                                   "amproc::pg_catalog.regprocedure, "
12959                                                   "'' AS amproclefttype, "
12960                                                   "'' AS amprocrighttype "
12961                                                   "FROM pg_catalog.pg_amproc "
12962                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
12963                                                   "ORDER BY amprocnum",
12964                                                   opcinfo->dobj.catId.oid);
12965         }
12966
12967         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12968
12969         ntups = PQntuples(res);
12970
12971         i_amprocnum = PQfnumber(res, "amprocnum");
12972         i_amproc = PQfnumber(res, "amproc");
12973         i_amproclefttype = PQfnumber(res, "amproclefttype");
12974         i_amprocrighttype = PQfnumber(res, "amprocrighttype");
12975
12976         for (i = 0; i < ntups; i++)
12977         {
12978                 amprocnum = PQgetvalue(res, i, i_amprocnum);
12979                 amproc = PQgetvalue(res, i, i_amproc);
12980                 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
12981                 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
12982
12983                 if (needComma)
12984                         appendPQExpBufferStr(q, " ,\n    ");
12985
12986                 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
12987
12988                 if (*amproclefttype && *amprocrighttype)
12989                         appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
12990
12991                 appendPQExpBuffer(q, " %s", amproc);
12992
12993                 needComma = true;
12994         }
12995
12996         PQclear(res);
12997
12998         /*
12999          * If needComma is still false it means we haven't added anything after
13000          * the AS keyword.  To avoid printing broken SQL, append a dummy STORAGE
13001          * clause with the same datatype.  This isn't sanctioned by the
13002          * documentation, but actually DefineOpClass will treat it as a no-op.
13003          */
13004         if (!needComma)
13005                 appendPQExpBuffer(q, "STORAGE %s", opcintype);
13006
13007         appendPQExpBufferStr(q, ";\n");
13008
13009         appendPQExpBufferStr(nameusing, fmtId(opcinfo->dobj.name));
13010         appendPQExpBuffer(nameusing, " USING %s",
13011                                           fmtId(amname));
13012
13013         if (dopt->binary_upgrade)
13014                 binary_upgrade_extension_member(q, &opcinfo->dobj,
13015                                                                                 "OPERATOR CLASS", nameusing->data,
13016                                                                                 opcinfo->dobj.namespace->dobj.name);
13017
13018         if (opcinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13019                 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
13020                                          opcinfo->dobj.name,
13021                                          opcinfo->dobj.namespace->dobj.name,
13022                                          NULL,
13023                                          opcinfo->rolname,
13024                                          false, "OPERATOR CLASS", SECTION_PRE_DATA,
13025                                          q->data, delq->data, NULL,
13026                                          NULL, 0,
13027                                          NULL, NULL);
13028
13029         /* Dump Operator Class Comments */
13030         if (opcinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13031                 dumpComment(fout, "OPERATOR CLASS", nameusing->data,
13032                                         opcinfo->dobj.namespace->dobj.name, opcinfo->rolname,
13033                                         opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
13034
13035         free(opcintype);
13036         free(opcfamily);
13037         free(amname);
13038         destroyPQExpBuffer(query);
13039         destroyPQExpBuffer(q);
13040         destroyPQExpBuffer(delq);
13041         destroyPQExpBuffer(nameusing);
13042 }
13043
13044 /*
13045  * dumpOpfamily
13046  *        write out a single operator family definition
13047  *
13048  * Note: this also dumps any "loose" operator members that aren't bound to a
13049  * specific opclass within the opfamily.
13050  */
13051 static void
13052 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
13053 {
13054         DumpOptions *dopt = fout->dopt;
13055         PQExpBuffer query;
13056         PQExpBuffer q;
13057         PQExpBuffer delq;
13058         PQExpBuffer nameusing;
13059         PGresult   *res;
13060         PGresult   *res_ops;
13061         PGresult   *res_procs;
13062         int                     ntups;
13063         int                     i_amname;
13064         int                     i_amopstrategy;
13065         int                     i_amopreqcheck;
13066         int                     i_amopopr;
13067         int                     i_sortfamily;
13068         int                     i_sortfamilynsp;
13069         int                     i_amprocnum;
13070         int                     i_amproc;
13071         int                     i_amproclefttype;
13072         int                     i_amprocrighttype;
13073         char       *amname;
13074         char       *amopstrategy;
13075         char       *amopreqcheck;
13076         char       *amopopr;
13077         char       *sortfamily;
13078         char       *sortfamilynsp;
13079         char       *amprocnum;
13080         char       *amproc;
13081         char       *amproclefttype;
13082         char       *amprocrighttype;
13083         bool            needComma;
13084         int                     i;
13085
13086         /* Skip if not to be dumped */
13087         if (!opfinfo->dobj.dump || dopt->dataOnly)
13088                 return;
13089
13090         query = createPQExpBuffer();
13091         q = createPQExpBuffer();
13092         delq = createPQExpBuffer();
13093         nameusing = createPQExpBuffer();
13094
13095         /*
13096          * Fetch only those opfamily members that are tied directly to the
13097          * opfamily by pg_depend entries.
13098          *
13099          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
13100          * older server's opclass in which it is used.  This is to avoid
13101          * hard-to-detect breakage if a newer pg_dump is used to dump from an
13102          * older server and then reload into that old version.  This can go away
13103          * once 8.3 is so old as to not be of interest to anyone.
13104          */
13105         if (fout->remoteVersion >= 90100)
13106         {
13107                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13108                                                   "amopopr::pg_catalog.regoperator, "
13109                                                   "opfname AS sortfamily, "
13110                                                   "nspname AS sortfamilynsp "
13111                                                   "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
13112                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
13113                                                   "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
13114                                                   "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13115                                                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13116                                                   "AND refobjid = '%u'::pg_catalog.oid "
13117                                                   "AND amopfamily = '%u'::pg_catalog.oid "
13118                                                   "ORDER BY amopstrategy",
13119                                                   opfinfo->dobj.catId.oid,
13120                                                   opfinfo->dobj.catId.oid);
13121         }
13122         else if (fout->remoteVersion >= 80400)
13123         {
13124                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13125                                                   "amopopr::pg_catalog.regoperator, "
13126                                                   "NULL AS sortfamily, "
13127                                                   "NULL AS sortfamilynsp "
13128                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13129                                                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13130                                                   "AND refobjid = '%u'::pg_catalog.oid "
13131                                                   "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13132                                                   "AND objid = ao.oid "
13133                                                   "ORDER BY amopstrategy",
13134                                                   opfinfo->dobj.catId.oid);
13135         }
13136         else
13137         {
13138                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
13139                                                   "amopopr::pg_catalog.regoperator, "
13140                                                   "NULL AS sortfamily, "
13141                                                   "NULL AS sortfamilynsp "
13142                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13143                                                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13144                                                   "AND refobjid = '%u'::pg_catalog.oid "
13145                                                   "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13146                                                   "AND objid = ao.oid "
13147                                                   "ORDER BY amopstrategy",
13148                                                   opfinfo->dobj.catId.oid);
13149         }
13150
13151         res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13152
13153         resetPQExpBuffer(query);
13154
13155         appendPQExpBuffer(query, "SELECT amprocnum, "
13156                                           "amproc::pg_catalog.regprocedure, "
13157                                           "amproclefttype::pg_catalog.regtype, "
13158                                           "amprocrighttype::pg_catalog.regtype "
13159                                           "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
13160                                           "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13161                                           "AND refobjid = '%u'::pg_catalog.oid "
13162                                           "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
13163                                           "AND objid = ap.oid "
13164                                           "ORDER BY amprocnum",
13165                                           opfinfo->dobj.catId.oid);
13166
13167         res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13168
13169         /* Get additional fields from the pg_opfamily row */
13170         resetPQExpBuffer(query);
13171
13172         appendPQExpBuffer(query, "SELECT "
13173                                           "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
13174                                           "FROM pg_catalog.pg_opfamily "
13175                                           "WHERE oid = '%u'::pg_catalog.oid",
13176                                           opfinfo->dobj.catId.oid);
13177
13178         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13179
13180         i_amname = PQfnumber(res, "amname");
13181
13182         /* amname will still be needed after we PQclear res */
13183         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
13184
13185         appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
13186                                           fmtQualifiedDumpable(opfinfo));
13187         appendPQExpBuffer(delq, " USING %s;\n",
13188                                           fmtId(amname));
13189
13190         /* Build the fixed portion of the CREATE command */
13191         appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
13192                                           fmtQualifiedDumpable(opfinfo));
13193         appendPQExpBuffer(q, " USING %s;\n",
13194                                           fmtId(amname));
13195
13196         PQclear(res);
13197
13198         /* Do we need an ALTER to add loose members? */
13199         if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
13200         {
13201                 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
13202                                                   fmtQualifiedDumpable(opfinfo));
13203                 appendPQExpBuffer(q, " USING %s ADD\n    ",
13204                                                   fmtId(amname));
13205
13206                 needComma = false;
13207
13208                 /*
13209                  * Now fetch and print the OPERATOR entries (pg_amop rows).
13210                  */
13211                 ntups = PQntuples(res_ops);
13212
13213                 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
13214                 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
13215                 i_amopopr = PQfnumber(res_ops, "amopopr");
13216                 i_sortfamily = PQfnumber(res_ops, "sortfamily");
13217                 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
13218
13219                 for (i = 0; i < ntups; i++)
13220                 {
13221                         amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
13222                         amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
13223                         amopopr = PQgetvalue(res_ops, i, i_amopopr);
13224                         sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
13225                         sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
13226
13227                         if (needComma)
13228                                 appendPQExpBufferStr(q, " ,\n    ");
13229
13230                         appendPQExpBuffer(q, "OPERATOR %s %s",
13231                                                           amopstrategy, amopopr);
13232
13233                         if (strlen(sortfamily) > 0)
13234                         {
13235                                 appendPQExpBufferStr(q, " FOR ORDER BY ");
13236                                 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
13237                                 appendPQExpBufferStr(q, fmtId(sortfamily));
13238                         }
13239
13240                         if (strcmp(amopreqcheck, "t") == 0)
13241                                 appendPQExpBufferStr(q, " RECHECK");
13242
13243                         needComma = true;
13244                 }
13245
13246                 /*
13247                  * Now fetch and print the FUNCTION entries (pg_amproc rows).
13248                  */
13249                 ntups = PQntuples(res_procs);
13250
13251                 i_amprocnum = PQfnumber(res_procs, "amprocnum");
13252                 i_amproc = PQfnumber(res_procs, "amproc");
13253                 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
13254                 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
13255
13256                 for (i = 0; i < ntups; i++)
13257                 {
13258                         amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
13259                         amproc = PQgetvalue(res_procs, i, i_amproc);
13260                         amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
13261                         amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
13262
13263                         if (needComma)
13264                                 appendPQExpBufferStr(q, " ,\n    ");
13265
13266                         appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
13267                                                           amprocnum, amproclefttype, amprocrighttype,
13268                                                           amproc);
13269
13270                         needComma = true;
13271                 }
13272
13273                 appendPQExpBufferStr(q, ";\n");
13274         }
13275
13276         appendPQExpBufferStr(nameusing, fmtId(opfinfo->dobj.name));
13277         appendPQExpBuffer(nameusing, " USING %s",
13278                                           fmtId(amname));
13279
13280         if (dopt->binary_upgrade)
13281                 binary_upgrade_extension_member(q, &opfinfo->dobj,
13282                                                                                 "OPERATOR FAMILY", nameusing->data,
13283                                                                                 opfinfo->dobj.namespace->dobj.name);
13284
13285         if (opfinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13286                 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
13287                                          opfinfo->dobj.name,
13288                                          opfinfo->dobj.namespace->dobj.name,
13289                                          NULL,
13290                                          opfinfo->rolname,
13291                                          false, "OPERATOR FAMILY", SECTION_PRE_DATA,
13292                                          q->data, delq->data, NULL,
13293                                          NULL, 0,
13294                                          NULL, NULL);
13295
13296         /* Dump Operator Family Comments */
13297         if (opfinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13298                 dumpComment(fout, "OPERATOR FAMILY", nameusing->data,
13299                                         opfinfo->dobj.namespace->dobj.name, opfinfo->rolname,
13300                                         opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
13301
13302         free(amname);
13303         PQclear(res_ops);
13304         PQclear(res_procs);
13305         destroyPQExpBuffer(query);
13306         destroyPQExpBuffer(q);
13307         destroyPQExpBuffer(delq);
13308         destroyPQExpBuffer(nameusing);
13309 }
13310
13311 /*
13312  * dumpCollation
13313  *        write out a single collation definition
13314  */
13315 static void
13316 dumpCollation(Archive *fout, CollInfo *collinfo)
13317 {
13318         DumpOptions *dopt = fout->dopt;
13319         PQExpBuffer query;
13320         PQExpBuffer q;
13321         PQExpBuffer delq;
13322         char       *qcollname;
13323         PGresult   *res;
13324         int                     i_collprovider;
13325         int                     i_collcollate;
13326         int                     i_collctype;
13327         const char *collprovider;
13328         const char *collcollate;
13329         const char *collctype;
13330
13331         /* Skip if not to be dumped */
13332         if (!collinfo->dobj.dump || dopt->dataOnly)
13333                 return;
13334
13335         query = createPQExpBuffer();
13336         q = createPQExpBuffer();
13337         delq = createPQExpBuffer();
13338
13339         qcollname = pg_strdup(fmtId(collinfo->dobj.name));
13340
13341         /* Get collation-specific details */
13342         if (fout->remoteVersion >= 100000)
13343                 appendPQExpBuffer(query, "SELECT "
13344                                                   "collprovider, "
13345                                                   "collcollate, "
13346                                                   "collctype, "
13347                                                   "collversion "
13348                                                   "FROM pg_catalog.pg_collation c "
13349                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
13350                                                   collinfo->dobj.catId.oid);
13351         else
13352                 appendPQExpBuffer(query, "SELECT "
13353                                                   "'c' AS collprovider, "
13354                                                   "collcollate, "
13355                                                   "collctype, "
13356                                                   "NULL AS collversion "
13357                                                   "FROM pg_catalog.pg_collation c "
13358                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
13359                                                   collinfo->dobj.catId.oid);
13360
13361         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13362
13363         i_collprovider = PQfnumber(res, "collprovider");
13364         i_collcollate = PQfnumber(res, "collcollate");
13365         i_collctype = PQfnumber(res, "collctype");
13366
13367         collprovider = PQgetvalue(res, 0, i_collprovider);
13368         collcollate = PQgetvalue(res, 0, i_collcollate);
13369         collctype = PQgetvalue(res, 0, i_collctype);
13370
13371         appendPQExpBuffer(delq, "DROP COLLATION %s;\n",
13372                                           fmtQualifiedDumpable(collinfo));
13373
13374         appendPQExpBuffer(q, "CREATE COLLATION %s (",
13375                                           fmtQualifiedDumpable(collinfo));
13376
13377         appendPQExpBufferStr(q, "provider = ");
13378         if (collprovider[0] == 'c')
13379                 appendPQExpBufferStr(q, "libc");
13380         else if (collprovider[0] == 'i')
13381                 appendPQExpBufferStr(q, "icu");
13382         else if (collprovider[0] == 'd')
13383                 /* to allow dumping pg_catalog; not accepted on input */
13384                 appendPQExpBufferStr(q, "default");
13385         else
13386                 exit_horribly(NULL,
13387                                           "unrecognized collation provider: %s\n",
13388                                           collprovider);
13389
13390         if (strcmp(collcollate, collctype) == 0)
13391         {
13392                 appendPQExpBufferStr(q, ", locale = ");
13393                 appendStringLiteralAH(q, collcollate, fout);
13394         }
13395         else
13396         {
13397                 appendPQExpBufferStr(q, ", lc_collate = ");
13398                 appendStringLiteralAH(q, collcollate, fout);
13399                 appendPQExpBufferStr(q, ", lc_ctype = ");
13400                 appendStringLiteralAH(q, collctype, fout);
13401         }
13402
13403         /*
13404          * For binary upgrade, carry over the collation version.  For normal
13405          * dump/restore, omit the version, so that it is computed upon restore.
13406          */
13407         if (dopt->binary_upgrade)
13408         {
13409                 int                     i_collversion;
13410
13411                 i_collversion = PQfnumber(res, "collversion");
13412                 if (!PQgetisnull(res, 0, i_collversion))
13413                 {
13414                         appendPQExpBufferStr(q, ", version = ");
13415                         appendStringLiteralAH(q,
13416                                                                   PQgetvalue(res, 0, i_collversion),
13417                                                                   fout);
13418                 }
13419         }
13420
13421         appendPQExpBufferStr(q, ");\n");
13422
13423         if (dopt->binary_upgrade)
13424                 binary_upgrade_extension_member(q, &collinfo->dobj,
13425                                                                                 "COLLATION", qcollname,
13426                                                                                 collinfo->dobj.namespace->dobj.name);
13427
13428         if (collinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13429                 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
13430                                          collinfo->dobj.name,
13431                                          collinfo->dobj.namespace->dobj.name,
13432                                          NULL,
13433                                          collinfo->rolname,
13434                                          false, "COLLATION", SECTION_PRE_DATA,
13435                                          q->data, delq->data, NULL,
13436                                          NULL, 0,
13437                                          NULL, NULL);
13438
13439         /* Dump Collation Comments */
13440         if (collinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13441                 dumpComment(fout, "COLLATION", qcollname,
13442                                         collinfo->dobj.namespace->dobj.name, collinfo->rolname,
13443                                         collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
13444
13445         PQclear(res);
13446
13447         destroyPQExpBuffer(query);
13448         destroyPQExpBuffer(q);
13449         destroyPQExpBuffer(delq);
13450         free(qcollname);
13451 }
13452
13453 /*
13454  * dumpConversion
13455  *        write out a single conversion definition
13456  */
13457 static void
13458 dumpConversion(Archive *fout, ConvInfo *convinfo)
13459 {
13460         DumpOptions *dopt = fout->dopt;
13461         PQExpBuffer query;
13462         PQExpBuffer q;
13463         PQExpBuffer delq;
13464         char       *qconvname;
13465         PGresult   *res;
13466         int                     i_conforencoding;
13467         int                     i_contoencoding;
13468         int                     i_conproc;
13469         int                     i_condefault;
13470         const char *conforencoding;
13471         const char *contoencoding;
13472         const char *conproc;
13473         bool            condefault;
13474
13475         /* Skip if not to be dumped */
13476         if (!convinfo->dobj.dump || dopt->dataOnly)
13477                 return;
13478
13479         query = createPQExpBuffer();
13480         q = createPQExpBuffer();
13481         delq = createPQExpBuffer();
13482
13483         qconvname = pg_strdup(fmtId(convinfo->dobj.name));
13484
13485         /* Get conversion-specific details */
13486         appendPQExpBuffer(query, "SELECT "
13487                                           "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
13488                                           "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
13489                                           "conproc, condefault "
13490                                           "FROM pg_catalog.pg_conversion c "
13491                                           "WHERE c.oid = '%u'::pg_catalog.oid",
13492                                           convinfo->dobj.catId.oid);
13493
13494         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13495
13496         i_conforencoding = PQfnumber(res, "conforencoding");
13497         i_contoencoding = PQfnumber(res, "contoencoding");
13498         i_conproc = PQfnumber(res, "conproc");
13499         i_condefault = PQfnumber(res, "condefault");
13500
13501         conforencoding = PQgetvalue(res, 0, i_conforencoding);
13502         contoencoding = PQgetvalue(res, 0, i_contoencoding);
13503         conproc = PQgetvalue(res, 0, i_conproc);
13504         condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
13505
13506         appendPQExpBuffer(delq, "DROP CONVERSION %s;\n",
13507                                           fmtQualifiedDumpable(convinfo));
13508
13509         appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
13510                                           (condefault) ? "DEFAULT " : "",
13511                                           fmtQualifiedDumpable(convinfo));
13512         appendStringLiteralAH(q, conforencoding, fout);
13513         appendPQExpBufferStr(q, " TO ");
13514         appendStringLiteralAH(q, contoencoding, fout);
13515         /* regproc output is already sufficiently quoted */
13516         appendPQExpBuffer(q, " FROM %s;\n", conproc);
13517
13518         if (dopt->binary_upgrade)
13519                 binary_upgrade_extension_member(q, &convinfo->dobj,
13520                                                                                 "CONVERSION", qconvname,
13521                                                                                 convinfo->dobj.namespace->dobj.name);
13522
13523         if (convinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13524                 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
13525                                          convinfo->dobj.name,
13526                                          convinfo->dobj.namespace->dobj.name,
13527                                          NULL,
13528                                          convinfo->rolname,
13529                                          false, "CONVERSION", SECTION_PRE_DATA,
13530                                          q->data, delq->data, NULL,
13531                                          NULL, 0,
13532                                          NULL, NULL);
13533
13534         /* Dump Conversion Comments */
13535         if (convinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13536                 dumpComment(fout, "CONVERSION", qconvname,
13537                                         convinfo->dobj.namespace->dobj.name, convinfo->rolname,
13538                                         convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
13539
13540         PQclear(res);
13541
13542         destroyPQExpBuffer(query);
13543         destroyPQExpBuffer(q);
13544         destroyPQExpBuffer(delq);
13545         free(qconvname);
13546 }
13547
13548 /*
13549  * format_aggregate_signature: generate aggregate name and argument list
13550  *
13551  * The argument type names are qualified if needed.  The aggregate name
13552  * is never qualified.
13553  */
13554 static char *
13555 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
13556 {
13557         PQExpBufferData buf;
13558         int                     j;
13559
13560         initPQExpBuffer(&buf);
13561         if (honor_quotes)
13562                 appendPQExpBufferStr(&buf, fmtId(agginfo->aggfn.dobj.name));
13563         else
13564                 appendPQExpBufferStr(&buf, agginfo->aggfn.dobj.name);
13565
13566         if (agginfo->aggfn.nargs == 0)
13567                 appendPQExpBuffer(&buf, "(*)");
13568         else
13569         {
13570                 appendPQExpBufferChar(&buf, '(');
13571                 for (j = 0; j < agginfo->aggfn.nargs; j++)
13572                 {
13573                         char       *typname;
13574
13575                         typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
13576                                                                                    zeroAsOpaque);
13577
13578                         appendPQExpBuffer(&buf, "%s%s",
13579                                                           (j > 0) ? ", " : "",
13580                                                           typname);
13581                         free(typname);
13582                 }
13583                 appendPQExpBufferChar(&buf, ')');
13584         }
13585         return buf.data;
13586 }
13587
13588 /*
13589  * dumpAgg
13590  *        write out a single aggregate definition
13591  */
13592 static void
13593 dumpAgg(Archive *fout, AggInfo *agginfo)
13594 {
13595         DumpOptions *dopt = fout->dopt;
13596         PQExpBuffer query;
13597         PQExpBuffer q;
13598         PQExpBuffer delq;
13599         PQExpBuffer details;
13600         char       *aggsig;                     /* identity signature */
13601         char       *aggfullsig = NULL;  /* full signature */
13602         char       *aggsig_tag;
13603         PGresult   *res;
13604         int                     i_aggtransfn;
13605         int                     i_aggfinalfn;
13606         int                     i_aggcombinefn;
13607         int                     i_aggserialfn;
13608         int                     i_aggdeserialfn;
13609         int                     i_aggmtransfn;
13610         int                     i_aggminvtransfn;
13611         int                     i_aggmfinalfn;
13612         int                     i_aggfinalextra;
13613         int                     i_aggmfinalextra;
13614         int                     i_aggfinalmodify;
13615         int                     i_aggmfinalmodify;
13616         int                     i_aggsortop;
13617         int                     i_aggkind;
13618         int                     i_aggtranstype;
13619         int                     i_aggtransspace;
13620         int                     i_aggmtranstype;
13621         int                     i_aggmtransspace;
13622         int                     i_agginitval;
13623         int                     i_aggminitval;
13624         int                     i_convertok;
13625         int                     i_proparallel;
13626         const char *aggtransfn;
13627         const char *aggfinalfn;
13628         const char *aggcombinefn;
13629         const char *aggserialfn;
13630         const char *aggdeserialfn;
13631         const char *aggmtransfn;
13632         const char *aggminvtransfn;
13633         const char *aggmfinalfn;
13634         bool            aggfinalextra;
13635         bool            aggmfinalextra;
13636         char            aggfinalmodify;
13637         char            aggmfinalmodify;
13638         const char *aggsortop;
13639         char       *aggsortconvop;
13640         char            aggkind;
13641         const char *aggtranstype;
13642         const char *aggtransspace;
13643         const char *aggmtranstype;
13644         const char *aggmtransspace;
13645         const char *agginitval;
13646         const char *aggminitval;
13647         bool            convertok;
13648         const char *proparallel;
13649         char            defaultfinalmodify;
13650
13651         /* Skip if not to be dumped */
13652         if (!agginfo->aggfn.dobj.dump || dopt->dataOnly)
13653                 return;
13654
13655         query = createPQExpBuffer();
13656         q = createPQExpBuffer();
13657         delq = createPQExpBuffer();
13658         details = createPQExpBuffer();
13659
13660         /* Get aggregate-specific details */
13661         if (fout->remoteVersion >= 110000)
13662         {
13663                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13664                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13665                                                   "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13666                                                   "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13667                                                   "aggfinalextra, aggmfinalextra, "
13668                                                   "aggfinalmodify, aggmfinalmodify, "
13669                                                   "aggsortop, "
13670                                                   "aggkind, "
13671                                                   "aggtransspace, agginitval, "
13672                                                   "aggmtransspace, aggminitval, "
13673                                                   "true AS convertok, "
13674                                                   "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13675                                                   "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13676                                                   "p.proparallel "
13677                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13678                                                   "WHERE a.aggfnoid = p.oid "
13679                                                   "AND p.oid = '%u'::pg_catalog.oid",
13680                                                   agginfo->aggfn.dobj.catId.oid);
13681         }
13682         else if (fout->remoteVersion >= 90600)
13683         {
13684                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13685                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13686                                                   "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13687                                                   "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13688                                                   "aggfinalextra, aggmfinalextra, "
13689                                                   "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13690                                                   "aggsortop, "
13691                                                   "aggkind, "
13692                                                   "aggtransspace, agginitval, "
13693                                                   "aggmtransspace, aggminitval, "
13694                                                   "true AS convertok, "
13695                                                   "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13696                                                   "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13697                                                   "p.proparallel "
13698                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13699                                                   "WHERE a.aggfnoid = p.oid "
13700                                                   "AND p.oid = '%u'::pg_catalog.oid",
13701                                                   agginfo->aggfn.dobj.catId.oid);
13702         }
13703         else if (fout->remoteVersion >= 90400)
13704         {
13705                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13706                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13707                                                   "'-' AS aggcombinefn, '-' AS aggserialfn, "
13708                                                   "'-' AS aggdeserialfn, aggmtransfn, aggminvtransfn, "
13709                                                   "aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13710                                                   "aggfinalextra, aggmfinalextra, "
13711                                                   "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13712                                                   "aggsortop, "
13713                                                   "aggkind, "
13714                                                   "aggtransspace, agginitval, "
13715                                                   "aggmtransspace, aggminitval, "
13716                                                   "true AS convertok, "
13717                                                   "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13718                                                   "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13719                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13720                                                   "WHERE a.aggfnoid = p.oid "
13721                                                   "AND p.oid = '%u'::pg_catalog.oid",
13722                                                   agginfo->aggfn.dobj.catId.oid);
13723         }
13724         else if (fout->remoteVersion >= 80400)
13725         {
13726                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13727                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13728                                                   "'-' AS aggcombinefn, '-' AS aggserialfn, "
13729                                                   "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13730                                                   "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13731                                                   "0 AS aggmtranstype, false AS aggfinalextra, "
13732                                                   "false AS aggmfinalextra, "
13733                                                   "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13734                                                   "aggsortop, "
13735                                                   "'n' AS aggkind, "
13736                                                   "0 AS aggtransspace, agginitval, "
13737                                                   "0 AS aggmtransspace, NULL AS aggminitval, "
13738                                                   "true AS convertok, "
13739                                                   "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13740                                                   "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13741                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13742                                                   "WHERE a.aggfnoid = p.oid "
13743                                                   "AND p.oid = '%u'::pg_catalog.oid",
13744                                                   agginfo->aggfn.dobj.catId.oid);
13745         }
13746         else if (fout->remoteVersion >= 80100)
13747         {
13748                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13749                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13750                                                   "'-' AS aggcombinefn, '-' AS aggserialfn, "
13751                                                   "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13752                                                   "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13753                                                   "0 AS aggmtranstype, false AS aggfinalextra, "
13754                                                   "false AS aggmfinalextra, "
13755                                                   "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13756                                                   "aggsortop, "
13757                                                   "'n' AS aggkind, "
13758                                                   "0 AS aggtransspace, agginitval, "
13759                                                   "0 AS aggmtransspace, NULL AS aggminitval, "
13760                                                   "true AS convertok "
13761                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13762                                                   "WHERE a.aggfnoid = p.oid "
13763                                                   "AND p.oid = '%u'::pg_catalog.oid",
13764                                                   agginfo->aggfn.dobj.catId.oid);
13765         }
13766         else
13767         {
13768                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13769                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13770                                                   "'-' AS aggcombinefn, '-' AS aggserialfn, "
13771                                                   "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13772                                                   "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13773                                                   "0 AS aggmtranstype, false AS aggfinalextra, "
13774                                                   "false AS aggmfinalextra, "
13775                                                   "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13776                                                   "0 AS aggsortop, "
13777                                                   "'n' AS aggkind, "
13778                                                   "0 AS aggtransspace, agginitval, "
13779                                                   "0 AS aggmtransspace, NULL AS aggminitval, "
13780                                                   "true AS convertok "
13781                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13782                                                   "WHERE a.aggfnoid = p.oid "
13783                                                   "AND p.oid = '%u'::pg_catalog.oid",
13784                                                   agginfo->aggfn.dobj.catId.oid);
13785         }
13786
13787         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13788
13789         i_aggtransfn = PQfnumber(res, "aggtransfn");
13790         i_aggfinalfn = PQfnumber(res, "aggfinalfn");
13791         i_aggcombinefn = PQfnumber(res, "aggcombinefn");
13792         i_aggserialfn = PQfnumber(res, "aggserialfn");
13793         i_aggdeserialfn = PQfnumber(res, "aggdeserialfn");
13794         i_aggmtransfn = PQfnumber(res, "aggmtransfn");
13795         i_aggminvtransfn = PQfnumber(res, "aggminvtransfn");
13796         i_aggmfinalfn = PQfnumber(res, "aggmfinalfn");
13797         i_aggfinalextra = PQfnumber(res, "aggfinalextra");
13798         i_aggmfinalextra = PQfnumber(res, "aggmfinalextra");
13799         i_aggfinalmodify = PQfnumber(res, "aggfinalmodify");
13800         i_aggmfinalmodify = PQfnumber(res, "aggmfinalmodify");
13801         i_aggsortop = PQfnumber(res, "aggsortop");
13802         i_aggkind = PQfnumber(res, "aggkind");
13803         i_aggtranstype = PQfnumber(res, "aggtranstype");
13804         i_aggtransspace = PQfnumber(res, "aggtransspace");
13805         i_aggmtranstype = PQfnumber(res, "aggmtranstype");
13806         i_aggmtransspace = PQfnumber(res, "aggmtransspace");
13807         i_agginitval = PQfnumber(res, "agginitval");
13808         i_aggminitval = PQfnumber(res, "aggminitval");
13809         i_convertok = PQfnumber(res, "convertok");
13810         i_proparallel = PQfnumber(res, "proparallel");
13811
13812         aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
13813         aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
13814         aggcombinefn = PQgetvalue(res, 0, i_aggcombinefn);
13815         aggserialfn = PQgetvalue(res, 0, i_aggserialfn);
13816         aggdeserialfn = PQgetvalue(res, 0, i_aggdeserialfn);
13817         aggmtransfn = PQgetvalue(res, 0, i_aggmtransfn);
13818         aggminvtransfn = PQgetvalue(res, 0, i_aggminvtransfn);
13819         aggmfinalfn = PQgetvalue(res, 0, i_aggmfinalfn);
13820         aggfinalextra = (PQgetvalue(res, 0, i_aggfinalextra)[0] == 't');
13821         aggmfinalextra = (PQgetvalue(res, 0, i_aggmfinalextra)[0] == 't');
13822         aggfinalmodify = PQgetvalue(res, 0, i_aggfinalmodify)[0];
13823         aggmfinalmodify = PQgetvalue(res, 0, i_aggmfinalmodify)[0];
13824         aggsortop = PQgetvalue(res, 0, i_aggsortop);
13825         aggkind = PQgetvalue(res, 0, i_aggkind)[0];
13826         aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
13827         aggtransspace = PQgetvalue(res, 0, i_aggtransspace);
13828         aggmtranstype = PQgetvalue(res, 0, i_aggmtranstype);
13829         aggmtransspace = PQgetvalue(res, 0, i_aggmtransspace);
13830         agginitval = PQgetvalue(res, 0, i_agginitval);
13831         aggminitval = PQgetvalue(res, 0, i_aggminitval);
13832         convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
13833
13834         if (fout->remoteVersion >= 80400)
13835         {
13836                 /* 8.4 or later; we rely on server-side code for most of the work */
13837                 char       *funcargs;
13838                 char       *funciargs;
13839
13840                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
13841                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
13842                 aggfullsig = format_function_arguments(&agginfo->aggfn, funcargs, true);
13843                 aggsig = format_function_arguments(&agginfo->aggfn, funciargs, true);
13844         }
13845         else
13846                 /* pre-8.4, do it ourselves */
13847                 aggsig = format_aggregate_signature(agginfo, fout, true);
13848
13849         aggsig_tag = format_aggregate_signature(agginfo, fout, false);
13850
13851         if (i_proparallel != -1)
13852                 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
13853         else
13854                 proparallel = NULL;
13855
13856         if (!convertok)
13857         {
13858                 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
13859                                   aggsig);
13860
13861                 if (aggfullsig)
13862                         free(aggfullsig);
13863
13864                 free(aggsig);
13865
13866                 return;
13867         }
13868
13869         /* identify default modify flag for aggkind (must match DefineAggregate) */
13870         defaultfinalmodify = (aggkind == AGGKIND_NORMAL) ? AGGMODIFY_READ_ONLY : AGGMODIFY_READ_WRITE;
13871         /* replace omitted flags for old versions */
13872         if (aggfinalmodify == '0')
13873                 aggfinalmodify = defaultfinalmodify;
13874         if (aggmfinalmodify == '0')
13875                 aggmfinalmodify = defaultfinalmodify;
13876
13877         /* regproc and regtype output is already sufficiently quoted */
13878         appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
13879                                           aggtransfn, aggtranstype);
13880
13881         if (strcmp(aggtransspace, "0") != 0)
13882         {
13883                 appendPQExpBuffer(details, ",\n    SSPACE = %s",
13884                                                   aggtransspace);
13885         }
13886
13887         if (!PQgetisnull(res, 0, i_agginitval))
13888         {
13889                 appendPQExpBufferStr(details, ",\n    INITCOND = ");
13890                 appendStringLiteralAH(details, agginitval, fout);
13891         }
13892
13893         if (strcmp(aggfinalfn, "-") != 0)
13894         {
13895                 appendPQExpBuffer(details, ",\n    FINALFUNC = %s",
13896                                                   aggfinalfn);
13897                 if (aggfinalextra)
13898                         appendPQExpBufferStr(details, ",\n    FINALFUNC_EXTRA");
13899                 if (aggfinalmodify != defaultfinalmodify)
13900                 {
13901                         switch (aggfinalmodify)
13902                         {
13903                                 case AGGMODIFY_READ_ONLY:
13904                                         appendPQExpBufferStr(details, ",\n    FINALFUNC_MODIFY = READ_ONLY");
13905                                         break;
13906                                 case AGGMODIFY_SHAREABLE:
13907                                         appendPQExpBufferStr(details, ",\n    FINALFUNC_MODIFY = SHAREABLE");
13908                                         break;
13909                                 case AGGMODIFY_READ_WRITE:
13910                                         appendPQExpBufferStr(details, ",\n    FINALFUNC_MODIFY = READ_WRITE");
13911                                         break;
13912                                 default:
13913                                         exit_horribly(NULL, "unrecognized aggfinalmodify value for aggregate \"%s\"\n",
13914                                                                   agginfo->aggfn.dobj.name);
13915                                         break;
13916                         }
13917                 }
13918         }
13919
13920         if (strcmp(aggcombinefn, "-") != 0)
13921                 appendPQExpBuffer(details, ",\n    COMBINEFUNC = %s", aggcombinefn);
13922
13923         if (strcmp(aggserialfn, "-") != 0)
13924                 appendPQExpBuffer(details, ",\n    SERIALFUNC = %s", aggserialfn);
13925
13926         if (strcmp(aggdeserialfn, "-") != 0)
13927                 appendPQExpBuffer(details, ",\n    DESERIALFUNC = %s", aggdeserialfn);
13928
13929         if (strcmp(aggmtransfn, "-") != 0)
13930         {
13931                 appendPQExpBuffer(details, ",\n    MSFUNC = %s,\n    MINVFUNC = %s,\n    MSTYPE = %s",
13932                                                   aggmtransfn,
13933                                                   aggminvtransfn,
13934                                                   aggmtranstype);
13935         }
13936
13937         if (strcmp(aggmtransspace, "0") != 0)
13938         {
13939                 appendPQExpBuffer(details, ",\n    MSSPACE = %s",
13940                                                   aggmtransspace);
13941         }
13942
13943         if (!PQgetisnull(res, 0, i_aggminitval))
13944         {
13945                 appendPQExpBufferStr(details, ",\n    MINITCOND = ");
13946                 appendStringLiteralAH(details, aggminitval, fout);
13947         }
13948
13949         if (strcmp(aggmfinalfn, "-") != 0)
13950         {
13951                 appendPQExpBuffer(details, ",\n    MFINALFUNC = %s",
13952                                                   aggmfinalfn);
13953                 if (aggmfinalextra)
13954                         appendPQExpBufferStr(details, ",\n    MFINALFUNC_EXTRA");
13955                 if (aggmfinalmodify != defaultfinalmodify)
13956                 {
13957                         switch (aggmfinalmodify)
13958                         {
13959                                 case AGGMODIFY_READ_ONLY:
13960                                         appendPQExpBufferStr(details, ",\n    MFINALFUNC_MODIFY = READ_ONLY");
13961                                         break;
13962                                 case AGGMODIFY_SHAREABLE:
13963                                         appendPQExpBufferStr(details, ",\n    MFINALFUNC_MODIFY = SHAREABLE");
13964                                         break;
13965                                 case AGGMODIFY_READ_WRITE:
13966                                         appendPQExpBufferStr(details, ",\n    MFINALFUNC_MODIFY = READ_WRITE");
13967                                         break;
13968                                 default:
13969                                         exit_horribly(NULL, "unrecognized aggmfinalmodify value for aggregate \"%s\"\n",
13970                                                                   agginfo->aggfn.dobj.name);
13971                                         break;
13972                         }
13973                 }
13974         }
13975
13976         aggsortconvop = getFormattedOperatorName(fout, aggsortop);
13977         if (aggsortconvop)
13978         {
13979                 appendPQExpBuffer(details, ",\n    SORTOP = %s",
13980                                                   aggsortconvop);
13981                 free(aggsortconvop);
13982         }
13983
13984         if (aggkind == AGGKIND_HYPOTHETICAL)
13985                 appendPQExpBufferStr(details, ",\n    HYPOTHETICAL");
13986
13987         if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
13988         {
13989                 if (proparallel[0] == PROPARALLEL_SAFE)
13990                         appendPQExpBufferStr(details, ",\n    PARALLEL = safe");
13991                 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
13992                         appendPQExpBufferStr(details, ",\n    PARALLEL = restricted");
13993                 else if (proparallel[0] != PROPARALLEL_UNSAFE)
13994                         exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
13995                                                   agginfo->aggfn.dobj.name);
13996         }
13997
13998         appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
13999                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
14000                                           aggsig);
14001
14002         appendPQExpBuffer(q, "CREATE AGGREGATE %s.%s (\n%s\n);\n",
14003                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
14004                                           aggfullsig ? aggfullsig : aggsig, details->data);
14005
14006         if (dopt->binary_upgrade)
14007                 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj,
14008                                                                                 "AGGREGATE", aggsig,
14009                                                                                 agginfo->aggfn.dobj.namespace->dobj.name);
14010
14011         if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_DEFINITION)
14012                 ArchiveEntry(fout, agginfo->aggfn.dobj.catId,
14013                                          agginfo->aggfn.dobj.dumpId,
14014                                          aggsig_tag,
14015                                          agginfo->aggfn.dobj.namespace->dobj.name,
14016                                          NULL,
14017                                          agginfo->aggfn.rolname,
14018                                          false, "AGGREGATE", SECTION_PRE_DATA,
14019                                          q->data, delq->data, NULL,
14020                                          NULL, 0,
14021                                          NULL, NULL);
14022
14023         /* Dump Aggregate Comments */
14024         if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_COMMENT)
14025                 dumpComment(fout, "AGGREGATE", aggsig,
14026                                         agginfo->aggfn.dobj.namespace->dobj.name,
14027                                         agginfo->aggfn.rolname,
14028                                         agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
14029
14030         if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_SECLABEL)
14031                 dumpSecLabel(fout, "AGGREGATE", aggsig,
14032                                          agginfo->aggfn.dobj.namespace->dobj.name,
14033                                          agginfo->aggfn.rolname,
14034                                          agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
14035
14036         /*
14037          * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
14038          * command look like a function's GRANT; in particular this affects the
14039          * syntax for zero-argument aggregates and ordered-set aggregates.
14040          */
14041         free(aggsig);
14042
14043         aggsig = format_function_signature(fout, &agginfo->aggfn, true);
14044
14045         if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_ACL)
14046                 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
14047                                 "FUNCTION", aggsig, NULL,
14048                                 agginfo->aggfn.dobj.namespace->dobj.name,
14049                                 agginfo->aggfn.rolname, agginfo->aggfn.proacl,
14050                                 agginfo->aggfn.rproacl,
14051                                 agginfo->aggfn.initproacl, agginfo->aggfn.initrproacl);
14052
14053         free(aggsig);
14054         if (aggfullsig)
14055                 free(aggfullsig);
14056         free(aggsig_tag);
14057
14058         PQclear(res);
14059
14060         destroyPQExpBuffer(query);
14061         destroyPQExpBuffer(q);
14062         destroyPQExpBuffer(delq);
14063         destroyPQExpBuffer(details);
14064 }
14065
14066 /*
14067  * dumpTSParser
14068  *        write out a single text search parser
14069  */
14070 static void
14071 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
14072 {
14073         DumpOptions *dopt = fout->dopt;
14074         PQExpBuffer q;
14075         PQExpBuffer delq;
14076         char       *qprsname;
14077
14078         /* Skip if not to be dumped */
14079         if (!prsinfo->dobj.dump || dopt->dataOnly)
14080                 return;
14081
14082         q = createPQExpBuffer();
14083         delq = createPQExpBuffer();
14084
14085         qprsname = pg_strdup(fmtId(prsinfo->dobj.name));
14086
14087         appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
14088                                           fmtQualifiedDumpable(prsinfo));
14089
14090         appendPQExpBuffer(q, "    START = %s,\n",
14091                                           convertTSFunction(fout, prsinfo->prsstart));
14092         appendPQExpBuffer(q, "    GETTOKEN = %s,\n",
14093                                           convertTSFunction(fout, prsinfo->prstoken));
14094         appendPQExpBuffer(q, "    END = %s,\n",
14095                                           convertTSFunction(fout, prsinfo->prsend));
14096         if (prsinfo->prsheadline != InvalidOid)
14097                 appendPQExpBuffer(q, "    HEADLINE = %s,\n",
14098                                                   convertTSFunction(fout, prsinfo->prsheadline));
14099         appendPQExpBuffer(q, "    LEXTYPES = %s );\n",
14100                                           convertTSFunction(fout, prsinfo->prslextype));
14101
14102         appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s;\n",
14103                                           fmtQualifiedDumpable(prsinfo));
14104
14105         if (dopt->binary_upgrade)
14106                 binary_upgrade_extension_member(q, &prsinfo->dobj,
14107                                                                                 "TEXT SEARCH PARSER", qprsname,
14108                                                                                 prsinfo->dobj.namespace->dobj.name);
14109
14110         if (prsinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14111                 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
14112                                          prsinfo->dobj.name,
14113                                          prsinfo->dobj.namespace->dobj.name,
14114                                          NULL,
14115                                          "",
14116                                          false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
14117                                          q->data, delq->data, NULL,
14118                                          NULL, 0,
14119                                          NULL, NULL);
14120
14121         /* Dump Parser Comments */
14122         if (prsinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14123                 dumpComment(fout, "TEXT SEARCH PARSER", qprsname,
14124                                         prsinfo->dobj.namespace->dobj.name, "",
14125                                         prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
14126
14127         destroyPQExpBuffer(q);
14128         destroyPQExpBuffer(delq);
14129         free(qprsname);
14130 }
14131
14132 /*
14133  * dumpTSDictionary
14134  *        write out a single text search dictionary
14135  */
14136 static void
14137 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
14138 {
14139         DumpOptions *dopt = fout->dopt;
14140         PQExpBuffer q;
14141         PQExpBuffer delq;
14142         PQExpBuffer query;
14143         char       *qdictname;
14144         PGresult   *res;
14145         char       *nspname;
14146         char       *tmplname;
14147
14148         /* Skip if not to be dumped */
14149         if (!dictinfo->dobj.dump || dopt->dataOnly)
14150                 return;
14151
14152         q = createPQExpBuffer();
14153         delq = createPQExpBuffer();
14154         query = createPQExpBuffer();
14155
14156         qdictname = pg_strdup(fmtId(dictinfo->dobj.name));
14157
14158         /* Fetch name and namespace of the dictionary's template */
14159         appendPQExpBuffer(query, "SELECT nspname, tmplname "
14160                                           "FROM pg_ts_template p, pg_namespace n "
14161                                           "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
14162                                           dictinfo->dicttemplate);
14163         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14164         nspname = PQgetvalue(res, 0, 0);
14165         tmplname = PQgetvalue(res, 0, 1);
14166
14167         appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
14168                                           fmtQualifiedDumpable(dictinfo));
14169
14170         appendPQExpBufferStr(q, "    TEMPLATE = ");
14171         appendPQExpBuffer(q, "%s.", fmtId(nspname));
14172         appendPQExpBufferStr(q, fmtId(tmplname));
14173
14174         PQclear(res);
14175
14176         /* the dictinitoption can be dumped straight into the command */
14177         if (dictinfo->dictinitoption)
14178                 appendPQExpBuffer(q, ",\n    %s", dictinfo->dictinitoption);
14179
14180         appendPQExpBufferStr(q, " );\n");
14181
14182         appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s;\n",
14183                                           fmtQualifiedDumpable(dictinfo));
14184
14185         if (dopt->binary_upgrade)
14186                 binary_upgrade_extension_member(q, &dictinfo->dobj,
14187                                                                                 "TEXT SEARCH DICTIONARY", qdictname,
14188                                                                                 dictinfo->dobj.namespace->dobj.name);
14189
14190         if (dictinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14191                 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
14192                                          dictinfo->dobj.name,
14193                                          dictinfo->dobj.namespace->dobj.name,
14194                                          NULL,
14195                                          dictinfo->rolname,
14196                                          false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
14197                                          q->data, delq->data, NULL,
14198                                          NULL, 0,
14199                                          NULL, NULL);
14200
14201         /* Dump Dictionary Comments */
14202         if (dictinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14203                 dumpComment(fout, "TEXT SEARCH DICTIONARY", qdictname,
14204                                         dictinfo->dobj.namespace->dobj.name, dictinfo->rolname,
14205                                         dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
14206
14207         destroyPQExpBuffer(q);
14208         destroyPQExpBuffer(delq);
14209         destroyPQExpBuffer(query);
14210         free(qdictname);
14211 }
14212
14213 /*
14214  * dumpTSTemplate
14215  *        write out a single text search template
14216  */
14217 static void
14218 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
14219 {
14220         DumpOptions *dopt = fout->dopt;
14221         PQExpBuffer q;
14222         PQExpBuffer delq;
14223         char       *qtmplname;
14224
14225         /* Skip if not to be dumped */
14226         if (!tmplinfo->dobj.dump || dopt->dataOnly)
14227                 return;
14228
14229         q = createPQExpBuffer();
14230         delq = createPQExpBuffer();
14231
14232         qtmplname = pg_strdup(fmtId(tmplinfo->dobj.name));
14233
14234         appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
14235                                           fmtQualifiedDumpable(tmplinfo));
14236
14237         if (tmplinfo->tmplinit != InvalidOid)
14238                 appendPQExpBuffer(q, "    INIT = %s,\n",
14239                                                   convertTSFunction(fout, tmplinfo->tmplinit));
14240         appendPQExpBuffer(q, "    LEXIZE = %s );\n",
14241                                           convertTSFunction(fout, tmplinfo->tmpllexize));
14242
14243         appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s;\n",
14244                                           fmtQualifiedDumpable(tmplinfo));
14245
14246         if (dopt->binary_upgrade)
14247                 binary_upgrade_extension_member(q, &tmplinfo->dobj,
14248                                                                                 "TEXT SEARCH TEMPLATE", qtmplname,
14249                                                                                 tmplinfo->dobj.namespace->dobj.name);
14250
14251         if (tmplinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14252                 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
14253                                          tmplinfo->dobj.name,
14254                                          tmplinfo->dobj.namespace->dobj.name,
14255                                          NULL,
14256                                          "",
14257                                          false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
14258                                          q->data, delq->data, NULL,
14259                                          NULL, 0,
14260                                          NULL, NULL);
14261
14262         /* Dump Template Comments */
14263         if (tmplinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14264                 dumpComment(fout, "TEXT SEARCH TEMPLATE", qtmplname,
14265                                         tmplinfo->dobj.namespace->dobj.name, "",
14266                                         tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
14267
14268         destroyPQExpBuffer(q);
14269         destroyPQExpBuffer(delq);
14270         free(qtmplname);
14271 }
14272
14273 /*
14274  * dumpTSConfig
14275  *        write out a single text search configuration
14276  */
14277 static void
14278 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
14279 {
14280         DumpOptions *dopt = fout->dopt;
14281         PQExpBuffer q;
14282         PQExpBuffer delq;
14283         PQExpBuffer query;
14284         char       *qcfgname;
14285         PGresult   *res;
14286         char       *nspname;
14287         char       *prsname;
14288         int                     ntups,
14289                                 i;
14290         int                     i_tokenname;
14291         int                     i_dictname;
14292
14293         /* Skip if not to be dumped */
14294         if (!cfginfo->dobj.dump || dopt->dataOnly)
14295                 return;
14296
14297         q = createPQExpBuffer();
14298         delq = createPQExpBuffer();
14299         query = createPQExpBuffer();
14300
14301         qcfgname = pg_strdup(fmtId(cfginfo->dobj.name));
14302
14303         /* Fetch name and namespace of the config's parser */
14304         appendPQExpBuffer(query, "SELECT nspname, prsname "
14305                                           "FROM pg_ts_parser p, pg_namespace n "
14306                                           "WHERE p.oid = '%u' AND n.oid = prsnamespace",
14307                                           cfginfo->cfgparser);
14308         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14309         nspname = PQgetvalue(res, 0, 0);
14310         prsname = PQgetvalue(res, 0, 1);
14311
14312         appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
14313                                           fmtQualifiedDumpable(cfginfo));
14314
14315         appendPQExpBuffer(q, "    PARSER = %s.", fmtId(nspname));
14316         appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
14317
14318         PQclear(res);
14319
14320         resetPQExpBuffer(query);
14321         appendPQExpBuffer(query,
14322                                           "SELECT\n"
14323                                           "  ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t\n"
14324                                           "    WHERE t.tokid = m.maptokentype ) AS tokenname,\n"
14325                                           "  m.mapdict::pg_catalog.regdictionary AS dictname\n"
14326                                           "FROM pg_catalog.pg_ts_config_map AS m\n"
14327                                           "WHERE m.mapcfg = '%u'\n"
14328                                           "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
14329                                           cfginfo->cfgparser, cfginfo->dobj.catId.oid);
14330
14331         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14332         ntups = PQntuples(res);
14333
14334         i_tokenname = PQfnumber(res, "tokenname");
14335         i_dictname = PQfnumber(res, "dictname");
14336
14337         for (i = 0; i < ntups; i++)
14338         {
14339                 char       *tokenname = PQgetvalue(res, i, i_tokenname);
14340                 char       *dictname = PQgetvalue(res, i, i_dictname);
14341
14342                 if (i == 0 ||
14343                         strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
14344                 {
14345                         /* starting a new token type, so start a new command */
14346                         if (i > 0)
14347                                 appendPQExpBufferStr(q, ";\n");
14348                         appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
14349                                                           fmtQualifiedDumpable(cfginfo));
14350                         /* tokenname needs quoting, dictname does NOT */
14351                         appendPQExpBuffer(q, "    ADD MAPPING FOR %s WITH %s",
14352                                                           fmtId(tokenname), dictname);
14353                 }
14354                 else
14355                         appendPQExpBuffer(q, ", %s", dictname);
14356         }
14357
14358         if (ntups > 0)
14359                 appendPQExpBufferStr(q, ";\n");
14360
14361         PQclear(res);
14362
14363         appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s;\n",
14364                                           fmtQualifiedDumpable(cfginfo));
14365
14366         if (dopt->binary_upgrade)
14367                 binary_upgrade_extension_member(q, &cfginfo->dobj,
14368                                                                                 "TEXT SEARCH CONFIGURATION", qcfgname,
14369                                                                                 cfginfo->dobj.namespace->dobj.name);
14370
14371         if (cfginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14372                 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
14373                                          cfginfo->dobj.name,
14374                                          cfginfo->dobj.namespace->dobj.name,
14375                                          NULL,
14376                                          cfginfo->rolname,
14377                                          false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
14378                                          q->data, delq->data, NULL,
14379                                          NULL, 0,
14380                                          NULL, NULL);
14381
14382         /* Dump Configuration Comments */
14383         if (cfginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14384                 dumpComment(fout, "TEXT SEARCH CONFIGURATION", qcfgname,
14385                                         cfginfo->dobj.namespace->dobj.name, cfginfo->rolname,
14386                                         cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
14387
14388         destroyPQExpBuffer(q);
14389         destroyPQExpBuffer(delq);
14390         destroyPQExpBuffer(query);
14391         free(qcfgname);
14392 }
14393
14394 /*
14395  * dumpForeignDataWrapper
14396  *        write out a single foreign-data wrapper definition
14397  */
14398 static void
14399 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
14400 {
14401         DumpOptions *dopt = fout->dopt;
14402         PQExpBuffer q;
14403         PQExpBuffer delq;
14404         char       *qfdwname;
14405
14406         /* Skip if not to be dumped */
14407         if (!fdwinfo->dobj.dump || dopt->dataOnly)
14408                 return;
14409
14410         q = createPQExpBuffer();
14411         delq = createPQExpBuffer();
14412
14413         qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
14414
14415         appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
14416                                           qfdwname);
14417
14418         if (strcmp(fdwinfo->fdwhandler, "-") != 0)
14419                 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
14420
14421         if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
14422                 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
14423
14424         if (strlen(fdwinfo->fdwoptions) > 0)
14425                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", fdwinfo->fdwoptions);
14426
14427         appendPQExpBufferStr(q, ";\n");
14428
14429         appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
14430                                           qfdwname);
14431
14432         if (dopt->binary_upgrade)
14433                 binary_upgrade_extension_member(q, &fdwinfo->dobj,
14434                                                                                 "FOREIGN DATA WRAPPER", qfdwname,
14435                                                                                 NULL);
14436
14437         if (fdwinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14438                 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14439                                          fdwinfo->dobj.name,
14440                                          NULL,
14441                                          NULL,
14442                                          fdwinfo->rolname,
14443                                          false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
14444                                          q->data, delq->data, NULL,
14445                                          NULL, 0,
14446                                          NULL, NULL);
14447
14448         /* Dump Foreign Data Wrapper Comments */
14449         if (fdwinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14450                 dumpComment(fout, "FOREIGN DATA WRAPPER", qfdwname,
14451                                         NULL, fdwinfo->rolname,
14452                                         fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
14453
14454         /* Handle the ACL */
14455         if (fdwinfo->dobj.dump & DUMP_COMPONENT_ACL)
14456                 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14457                                 "FOREIGN DATA WRAPPER", qfdwname, NULL,
14458                                 NULL, fdwinfo->rolname,
14459                                 fdwinfo->fdwacl, fdwinfo->rfdwacl,
14460                                 fdwinfo->initfdwacl, fdwinfo->initrfdwacl);
14461
14462         free(qfdwname);
14463
14464         destroyPQExpBuffer(q);
14465         destroyPQExpBuffer(delq);
14466 }
14467
14468 /*
14469  * dumpForeignServer
14470  *        write out a foreign server definition
14471  */
14472 static void
14473 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
14474 {
14475         DumpOptions *dopt = fout->dopt;
14476         PQExpBuffer q;
14477         PQExpBuffer delq;
14478         PQExpBuffer query;
14479         PGresult   *res;
14480         char       *qsrvname;
14481         char       *fdwname;
14482
14483         /* Skip if not to be dumped */
14484         if (!srvinfo->dobj.dump || dopt->dataOnly)
14485                 return;
14486
14487         q = createPQExpBuffer();
14488         delq = createPQExpBuffer();
14489         query = createPQExpBuffer();
14490
14491         qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
14492
14493         /* look up the foreign-data wrapper */
14494         appendPQExpBuffer(query, "SELECT fdwname "
14495                                           "FROM pg_foreign_data_wrapper w "
14496                                           "WHERE w.oid = '%u'",
14497                                           srvinfo->srvfdw);
14498         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14499         fdwname = PQgetvalue(res, 0, 0);
14500
14501         appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
14502         if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
14503         {
14504                 appendPQExpBufferStr(q, " TYPE ");
14505                 appendStringLiteralAH(q, srvinfo->srvtype, fout);
14506         }
14507         if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
14508         {
14509                 appendPQExpBufferStr(q, " VERSION ");
14510                 appendStringLiteralAH(q, srvinfo->srvversion, fout);
14511         }
14512
14513         appendPQExpBufferStr(q, " FOREIGN DATA WRAPPER ");
14514         appendPQExpBufferStr(q, fmtId(fdwname));
14515
14516         if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
14517                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", srvinfo->srvoptions);
14518
14519         appendPQExpBufferStr(q, ";\n");
14520
14521         appendPQExpBuffer(delq, "DROP SERVER %s;\n",
14522                                           qsrvname);
14523
14524         if (dopt->binary_upgrade)
14525                 binary_upgrade_extension_member(q, &srvinfo->dobj,
14526                                                                                 "SERVER", qsrvname, NULL);
14527
14528         if (srvinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14529                 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14530                                          srvinfo->dobj.name,
14531                                          NULL,
14532                                          NULL,
14533                                          srvinfo->rolname,
14534                                          false, "SERVER", SECTION_PRE_DATA,
14535                                          q->data, delq->data, NULL,
14536                                          NULL, 0,
14537                                          NULL, NULL);
14538
14539         /* Dump Foreign Server Comments */
14540         if (srvinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14541                 dumpComment(fout, "SERVER", qsrvname,
14542                                         NULL, srvinfo->rolname,
14543                                         srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
14544
14545         /* Handle the ACL */
14546         if (srvinfo->dobj.dump & DUMP_COMPONENT_ACL)
14547                 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14548                                 "FOREIGN SERVER", qsrvname, NULL,
14549                                 NULL, srvinfo->rolname,
14550                                 srvinfo->srvacl, srvinfo->rsrvacl,
14551                                 srvinfo->initsrvacl, srvinfo->initrsrvacl);
14552
14553         /* Dump user mappings */
14554         if (srvinfo->dobj.dump & DUMP_COMPONENT_USERMAP)
14555                 dumpUserMappings(fout,
14556                                                  srvinfo->dobj.name, NULL,
14557                                                  srvinfo->rolname,
14558                                                  srvinfo->dobj.catId, srvinfo->dobj.dumpId);
14559
14560         free(qsrvname);
14561
14562         destroyPQExpBuffer(q);
14563         destroyPQExpBuffer(delq);
14564         destroyPQExpBuffer(query);
14565 }
14566
14567 /*
14568  * dumpUserMappings
14569  *
14570  * This routine is used to dump any user mappings associated with the
14571  * server handed to this routine. Should be called after ArchiveEntry()
14572  * for the server.
14573  */
14574 static void
14575 dumpUserMappings(Archive *fout,
14576                                  const char *servername, const char *namespace,
14577                                  const char *owner,
14578                                  CatalogId catalogId, DumpId dumpId)
14579 {
14580         PQExpBuffer q;
14581         PQExpBuffer delq;
14582         PQExpBuffer query;
14583         PQExpBuffer tag;
14584         PGresult   *res;
14585         int                     ntups;
14586         int                     i_usename;
14587         int                     i_umoptions;
14588         int                     i;
14589
14590         q = createPQExpBuffer();
14591         tag = createPQExpBuffer();
14592         delq = createPQExpBuffer();
14593         query = createPQExpBuffer();
14594
14595         /*
14596          * We read from the publicly accessible view pg_user_mappings, so as not
14597          * to fail if run by a non-superuser.  Note that the view will show
14598          * umoptions as null if the user hasn't got privileges for the associated
14599          * server; this means that pg_dump will dump such a mapping, but with no
14600          * OPTIONS clause.  A possible alternative is to skip such mappings
14601          * altogether, but it's not clear that that's an improvement.
14602          */
14603         appendPQExpBuffer(query,
14604                                           "SELECT usename, "
14605                                           "array_to_string(ARRAY("
14606                                           "SELECT quote_ident(option_name) || ' ' || "
14607                                           "quote_literal(option_value) "
14608                                           "FROM pg_options_to_table(umoptions) "
14609                                           "ORDER BY option_name"
14610                                           "), E',\n    ') AS umoptions "
14611                                           "FROM pg_user_mappings "
14612                                           "WHERE srvid = '%u' "
14613                                           "ORDER BY usename",
14614                                           catalogId.oid);
14615
14616         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14617
14618         ntups = PQntuples(res);
14619         i_usename = PQfnumber(res, "usename");
14620         i_umoptions = PQfnumber(res, "umoptions");
14621
14622         for (i = 0; i < ntups; i++)
14623         {
14624                 char       *usename;
14625                 char       *umoptions;
14626
14627                 usename = PQgetvalue(res, i, i_usename);
14628                 umoptions = PQgetvalue(res, i, i_umoptions);
14629
14630                 resetPQExpBuffer(q);
14631                 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
14632                 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
14633
14634                 if (umoptions && strlen(umoptions) > 0)
14635                         appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", umoptions);
14636
14637                 appendPQExpBufferStr(q, ";\n");
14638
14639                 resetPQExpBuffer(delq);
14640                 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
14641                 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
14642
14643                 resetPQExpBuffer(tag);
14644                 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
14645                                                   usename, servername);
14646
14647                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14648                                          tag->data,
14649                                          namespace,
14650                                          NULL,
14651                                          owner, false,
14652                                          "USER MAPPING", SECTION_PRE_DATA,
14653                                          q->data, delq->data, NULL,
14654                                          &dumpId, 1,
14655                                          NULL, NULL);
14656         }
14657
14658         PQclear(res);
14659
14660         destroyPQExpBuffer(query);
14661         destroyPQExpBuffer(delq);
14662         destroyPQExpBuffer(tag);
14663         destroyPQExpBuffer(q);
14664 }
14665
14666 /*
14667  * Write out default privileges information
14668  */
14669 static void
14670 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
14671 {
14672         DumpOptions *dopt = fout->dopt;
14673         PQExpBuffer q;
14674         PQExpBuffer tag;
14675         const char *type;
14676
14677         /* Skip if not to be dumped */
14678         if (!daclinfo->dobj.dump || dopt->dataOnly || dopt->aclsSkip)
14679                 return;
14680
14681         q = createPQExpBuffer();
14682         tag = createPQExpBuffer();
14683
14684         switch (daclinfo->defaclobjtype)
14685         {
14686                 case DEFACLOBJ_RELATION:
14687                         type = "TABLES";
14688                         break;
14689                 case DEFACLOBJ_SEQUENCE:
14690                         type = "SEQUENCES";
14691                         break;
14692                 case DEFACLOBJ_FUNCTION:
14693                         type = "FUNCTIONS";
14694                         break;
14695                 case DEFACLOBJ_TYPE:
14696                         type = "TYPES";
14697                         break;
14698                 case DEFACLOBJ_NAMESPACE:
14699                         type = "SCHEMAS";
14700                         break;
14701                 default:
14702                         /* shouldn't get here */
14703                         exit_horribly(NULL,
14704                                                   "unrecognized object type in default privileges: %d\n",
14705                                                   (int) daclinfo->defaclobjtype);
14706                         type = "";                      /* keep compiler quiet */
14707         }
14708
14709         appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
14710
14711         /* build the actual command(s) for this tuple */
14712         if (!buildDefaultACLCommands(type,
14713                                                                  daclinfo->dobj.namespace != NULL ?
14714                                                                  daclinfo->dobj.namespace->dobj.name : NULL,
14715                                                                  daclinfo->defaclacl,
14716                                                                  daclinfo->rdefaclacl,
14717                                                                  daclinfo->initdefaclacl,
14718                                                                  daclinfo->initrdefaclacl,
14719                                                                  daclinfo->defaclrole,
14720                                                                  fout->remoteVersion,
14721                                                                  q))
14722                 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
14723                                           daclinfo->defaclacl);
14724
14725         if (daclinfo->dobj.dump & DUMP_COMPONENT_ACL)
14726                 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
14727                                          tag->data,
14728                                          daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
14729                                          NULL,
14730                                          daclinfo->defaclrole,
14731                                          false, "DEFAULT ACL", SECTION_POST_DATA,
14732                                          q->data, "", NULL,
14733                                          NULL, 0,
14734                                          NULL, NULL);
14735
14736         destroyPQExpBuffer(tag);
14737         destroyPQExpBuffer(q);
14738 }
14739
14740 /*----------
14741  * Write out grant/revoke information
14742  *
14743  * 'objCatId' is the catalog ID of the underlying object.
14744  * 'objDumpId' is the dump ID of the underlying object.
14745  * 'type' must be one of
14746  *              TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
14747  *              FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
14748  * 'name' is the formatted name of the object.  Must be quoted etc. already.
14749  * 'subname' is the formatted name of the sub-object, if any.  Must be quoted.
14750  *              (Currently we assume that subname is only provided for table columns.)
14751  * 'nspname' is the namespace the object is in (NULL if none).
14752  * 'owner' is the owner, NULL if there is no owner (for languages).
14753  * 'acls' contains the ACL string of the object from the appropriate system
14754  *              catalog field; it will be passed to buildACLCommands for building the
14755  *              appropriate GRANT commands.
14756  * 'racls' contains the ACL string of any initial-but-now-revoked ACLs of the
14757  *              object; it will be passed to buildACLCommands for building the
14758  *              appropriate REVOKE commands.
14759  * 'initacls' In binary-upgrade mode, ACL string of the object's initial
14760  *              privileges, to be recorded into pg_init_privs
14761  * 'initracls' In binary-upgrade mode, ACL string of the object's
14762  *              revoked-from-default privileges, to be recorded into pg_init_privs
14763  *
14764  * NB: initacls/initracls are needed because extensions can set privileges on
14765  * an object during the extension's script file and we record those into
14766  * pg_init_privs as that object's initial privileges.
14767  *----------
14768  */
14769 static void
14770 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
14771                 const char *type, const char *name, const char *subname,
14772                 const char *nspname, const char *owner,
14773                 const char *acls, const char *racls,
14774                 const char *initacls, const char *initracls)
14775 {
14776         DumpOptions *dopt = fout->dopt;
14777         PQExpBuffer sql;
14778
14779         /* Do nothing if ACL dump is not enabled */
14780         if (dopt->aclsSkip)
14781                 return;
14782
14783         /* --data-only skips ACLs *except* BLOB ACLs */
14784         if (dopt->dataOnly && strcmp(type, "LARGE OBJECT") != 0)
14785                 return;
14786
14787         sql = createPQExpBuffer();
14788
14789         /*
14790          * Check to see if this object has had any initial ACLs included for it.
14791          * If so, we are in binary upgrade mode and these are the ACLs to turn
14792          * into GRANT and REVOKE statements to set and record the initial
14793          * privileges for an extension object.  Let the backend know that these
14794          * are to be recorded by calling binary_upgrade_set_record_init_privs()
14795          * before and after.
14796          */
14797         if (strlen(initacls) != 0 || strlen(initracls) != 0)
14798         {
14799                 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(true);\n");
14800                 if (!buildACLCommands(name, subname, nspname, type,
14801                                                           initacls, initracls, owner,
14802                                                           "", fout->remoteVersion, sql))
14803                         exit_horribly(NULL,
14804                                                   "could not parse initial GRANT ACL list (%s) or initial REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14805                                                   initacls, initracls, name, type);
14806                 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(false);\n");
14807         }
14808
14809         if (!buildACLCommands(name, subname, nspname, type,
14810                                                   acls, racls, owner,
14811                                                   "", fout->remoteVersion, sql))
14812                 exit_horribly(NULL,
14813                                           "could not parse GRANT ACL list (%s) or REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14814                                           acls, racls, name, type);
14815
14816         if (sql->len > 0)
14817         {
14818                 PQExpBuffer tag = createPQExpBuffer();
14819
14820                 if (subname)
14821                         appendPQExpBuffer(tag, "COLUMN %s.%s", name, subname);
14822                 else
14823                         appendPQExpBuffer(tag, "%s %s", type, name);
14824
14825                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14826                                          tag->data, nspname,
14827                                          NULL,
14828                                          owner ? owner : "",
14829                                          false, "ACL", SECTION_NONE,
14830                                          sql->data, "", NULL,
14831                                          &(objDumpId), 1,
14832                                          NULL, NULL);
14833                 destroyPQExpBuffer(tag);
14834         }
14835
14836         destroyPQExpBuffer(sql);
14837 }
14838
14839 /*
14840  * dumpSecLabel
14841  *
14842  * This routine is used to dump any security labels associated with the
14843  * object handed to this routine. The routine takes the object type
14844  * and object name (ready to print, except for schema decoration), plus
14845  * the namespace and owner of the object (for labeling the ArchiveEntry),
14846  * plus catalog ID and subid which are the lookup key for pg_seclabel,
14847  * plus the dump ID for the object (for setting a dependency).
14848  * If a matching pg_seclabel entry is found, it is dumped.
14849  *
14850  * Note: although this routine takes a dumpId for dependency purposes,
14851  * that purpose is just to mark the dependency in the emitted dump file
14852  * for possible future use by pg_restore.  We do NOT use it for determining
14853  * ordering of the label in the dump file, because this routine is called
14854  * after dependency sorting occurs.  This routine should be called just after
14855  * calling ArchiveEntry() for the specified object.
14856  */
14857 static void
14858 dumpSecLabel(Archive *fout, const char *type, const char *name,
14859                          const char *namespace, const char *owner,
14860                          CatalogId catalogId, int subid, DumpId dumpId)
14861 {
14862         DumpOptions *dopt = fout->dopt;
14863         SecLabelItem *labels;
14864         int                     nlabels;
14865         int                     i;
14866         PQExpBuffer query;
14867
14868         /* do nothing, if --no-security-labels is supplied */
14869         if (dopt->no_security_labels)
14870                 return;
14871
14872         /* Security labels are schema not data ... except blob labels are data */
14873         if (strcmp(type, "LARGE OBJECT") != 0)
14874         {
14875                 if (dopt->dataOnly)
14876                         return;
14877         }
14878         else
14879         {
14880                 /* We do dump blob security labels in binary-upgrade mode */
14881                 if (dopt->schemaOnly && !dopt->binary_upgrade)
14882                         return;
14883         }
14884
14885         /* Search for security labels associated with catalogId, using table */
14886         nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
14887
14888         query = createPQExpBuffer();
14889
14890         for (i = 0; i < nlabels; i++)
14891         {
14892                 /*
14893                  * Ignore label entries for which the subid doesn't match.
14894                  */
14895                 if (labels[i].objsubid != subid)
14896                         continue;
14897
14898                 appendPQExpBuffer(query,
14899                                                   "SECURITY LABEL FOR %s ON %s ",
14900                                                   fmtId(labels[i].provider), type);
14901                 if (namespace && *namespace)
14902                         appendPQExpBuffer(query, "%s.", fmtId(namespace));
14903                 appendPQExpBuffer(query, "%s IS ", name);
14904                 appendStringLiteralAH(query, labels[i].label, fout);
14905                 appendPQExpBufferStr(query, ";\n");
14906         }
14907
14908         if (query->len > 0)
14909         {
14910                 PQExpBuffer tag = createPQExpBuffer();
14911
14912                 appendPQExpBuffer(tag, "%s %s", type, name);
14913                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14914                                          tag->data, namespace, NULL, owner,
14915                                          false, "SECURITY LABEL", SECTION_NONE,
14916                                          query->data, "", NULL,
14917                                          &(dumpId), 1,
14918                                          NULL, NULL);
14919                 destroyPQExpBuffer(tag);
14920         }
14921
14922         destroyPQExpBuffer(query);
14923 }
14924
14925 /*
14926  * dumpTableSecLabel
14927  *
14928  * As above, but dump security label for both the specified table (or view)
14929  * and its columns.
14930  */
14931 static void
14932 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
14933 {
14934         DumpOptions *dopt = fout->dopt;
14935         SecLabelItem *labels;
14936         int                     nlabels;
14937         int                     i;
14938         PQExpBuffer query;
14939         PQExpBuffer target;
14940
14941         /* do nothing, if --no-security-labels is supplied */
14942         if (dopt->no_security_labels)
14943                 return;
14944
14945         /* SecLabel are SCHEMA not data */
14946         if (dopt->dataOnly)
14947                 return;
14948
14949         /* Search for comments associated with relation, using table */
14950         nlabels = findSecLabels(fout,
14951                                                         tbinfo->dobj.catId.tableoid,
14952                                                         tbinfo->dobj.catId.oid,
14953                                                         &labels);
14954
14955         /* If security labels exist, build SECURITY LABEL statements */
14956         if (nlabels <= 0)
14957                 return;
14958
14959         query = createPQExpBuffer();
14960         target = createPQExpBuffer();
14961
14962         for (i = 0; i < nlabels; i++)
14963         {
14964                 const char *colname;
14965                 const char *provider = labels[i].provider;
14966                 const char *label = labels[i].label;
14967                 int                     objsubid = labels[i].objsubid;
14968
14969                 resetPQExpBuffer(target);
14970                 if (objsubid == 0)
14971                 {
14972                         appendPQExpBuffer(target, "%s %s", reltypename,
14973                                                           fmtQualifiedDumpable(tbinfo));
14974                 }
14975                 else
14976                 {
14977                         colname = getAttrName(objsubid, tbinfo);
14978                         /* first fmtXXX result must be consumed before calling again */
14979                         appendPQExpBuffer(target, "COLUMN %s",
14980                                                           fmtQualifiedDumpable(tbinfo));
14981                         appendPQExpBuffer(target, ".%s", fmtId(colname));
14982                 }
14983                 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
14984                                                   fmtId(provider), target->data);
14985                 appendStringLiteralAH(query, label, fout);
14986                 appendPQExpBufferStr(query, ";\n");
14987         }
14988         if (query->len > 0)
14989         {
14990                 resetPQExpBuffer(target);
14991                 appendPQExpBuffer(target, "%s %s", reltypename,
14992                                                   fmtId(tbinfo->dobj.name));
14993                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14994                                          target->data,
14995                                          tbinfo->dobj.namespace->dobj.name,
14996                                          NULL, tbinfo->rolname,
14997                                          false, "SECURITY LABEL", SECTION_NONE,
14998                                          query->data, "", NULL,
14999                                          &(tbinfo->dobj.dumpId), 1,
15000                                          NULL, NULL);
15001         }
15002         destroyPQExpBuffer(query);
15003         destroyPQExpBuffer(target);
15004 }
15005
15006 /*
15007  * findSecLabels
15008  *
15009  * Find the security label(s), if any, associated with the given object.
15010  * All the objsubid values associated with the given classoid/objoid are
15011  * found with one search.
15012  */
15013 static int
15014 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
15015 {
15016         /* static storage for table of security labels */
15017         static SecLabelItem *labels = NULL;
15018         static int      nlabels = -1;
15019
15020         SecLabelItem *middle = NULL;
15021         SecLabelItem *low;
15022         SecLabelItem *high;
15023         int                     nmatch;
15024
15025         /* Get security labels if we didn't already */
15026         if (nlabels < 0)
15027                 nlabels = collectSecLabels(fout, &labels);
15028
15029         if (nlabels <= 0)                       /* no labels, so no match is possible */
15030         {
15031                 *items = NULL;
15032                 return 0;
15033         }
15034
15035         /*
15036          * Do binary search to find some item matching the object.
15037          */
15038         low = &labels[0];
15039         high = &labels[nlabels - 1];
15040         while (low <= high)
15041         {
15042                 middle = low + (high - low) / 2;
15043
15044                 if (classoid < middle->classoid)
15045                         high = middle - 1;
15046                 else if (classoid > middle->classoid)
15047                         low = middle + 1;
15048                 else if (objoid < middle->objoid)
15049                         high = middle - 1;
15050                 else if (objoid > middle->objoid)
15051                         low = middle + 1;
15052                 else
15053                         break;                          /* found a match */
15054         }
15055
15056         if (low > high)                         /* no matches */
15057         {
15058                 *items = NULL;
15059                 return 0;
15060         }
15061
15062         /*
15063          * Now determine how many items match the object.  The search loop
15064          * invariant still holds: only items between low and high inclusive could
15065          * match.
15066          */
15067         nmatch = 1;
15068         while (middle > low)
15069         {
15070                 if (classoid != middle[-1].classoid ||
15071                         objoid != middle[-1].objoid)
15072                         break;
15073                 middle--;
15074                 nmatch++;
15075         }
15076
15077         *items = middle;
15078
15079         middle += nmatch;
15080         while (middle <= high)
15081         {
15082                 if (classoid != middle->classoid ||
15083                         objoid != middle->objoid)
15084                         break;
15085                 middle++;
15086                 nmatch++;
15087         }
15088
15089         return nmatch;
15090 }
15091
15092 /*
15093  * collectSecLabels
15094  *
15095  * Construct a table of all security labels available for database objects.
15096  * It's much faster to pull them all at once.
15097  *
15098  * The table is sorted by classoid/objid/objsubid for speed in lookup.
15099  */
15100 static int
15101 collectSecLabels(Archive *fout, SecLabelItem **items)
15102 {
15103         PGresult   *res;
15104         PQExpBuffer query;
15105         int                     i_label;
15106         int                     i_provider;
15107         int                     i_classoid;
15108         int                     i_objoid;
15109         int                     i_objsubid;
15110         int                     ntups;
15111         int                     i;
15112         SecLabelItem *labels;
15113
15114         query = createPQExpBuffer();
15115
15116         appendPQExpBufferStr(query,
15117                                                  "SELECT label, provider, classoid, objoid, objsubid "
15118                                                  "FROM pg_catalog.pg_seclabel "
15119                                                  "ORDER BY classoid, objoid, objsubid");
15120
15121         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15122
15123         /* Construct lookup table containing OIDs in numeric form */
15124         i_label = PQfnumber(res, "label");
15125         i_provider = PQfnumber(res, "provider");
15126         i_classoid = PQfnumber(res, "classoid");
15127         i_objoid = PQfnumber(res, "objoid");
15128         i_objsubid = PQfnumber(res, "objsubid");
15129
15130         ntups = PQntuples(res);
15131
15132         labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
15133
15134         for (i = 0; i < ntups; i++)
15135         {
15136                 labels[i].label = PQgetvalue(res, i, i_label);
15137                 labels[i].provider = PQgetvalue(res, i, i_provider);
15138                 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
15139                 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
15140                 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
15141         }
15142
15143         /* Do NOT free the PGresult since we are keeping pointers into it */
15144         destroyPQExpBuffer(query);
15145
15146         *items = labels;
15147         return ntups;
15148 }
15149
15150 /*
15151  * dumpTable
15152  *        write out to fout the declarations (not data) of a user-defined table
15153  */
15154 static void
15155 dumpTable(Archive *fout, TableInfo *tbinfo)
15156 {
15157         DumpOptions *dopt = fout->dopt;
15158         char       *namecopy;
15159
15160         /*
15161          * noop if we are not dumping anything about this table, or if we are
15162          * doing a data-only dump
15163          */
15164         if (!tbinfo->dobj.dump || dopt->dataOnly)
15165                 return;
15166
15167         if (tbinfo->relkind == RELKIND_SEQUENCE)
15168                 dumpSequence(fout, tbinfo);
15169         else
15170                 dumpTableSchema(fout, tbinfo);
15171
15172         /* Handle the ACL here */
15173         namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
15174         if (tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15175         {
15176                 const char *objtype =
15177                 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" : "TABLE";
15178
15179                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15180                                 objtype, namecopy, NULL,
15181                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15182                                 tbinfo->relacl, tbinfo->rrelacl,
15183                                 tbinfo->initrelacl, tbinfo->initrrelacl);
15184         }
15185
15186         /*
15187          * Handle column ACLs, if any.  Note: we pull these with a separate query
15188          * rather than trying to fetch them during getTableAttrs, so that we won't
15189          * miss ACLs on system columns.
15190          */
15191         if (fout->remoteVersion >= 80400 && tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15192         {
15193                 PQExpBuffer query = createPQExpBuffer();
15194                 PGresult   *res;
15195                 int                     i;
15196
15197                 if (fout->remoteVersion >= 90600)
15198                 {
15199                         PQExpBuffer acl_subquery = createPQExpBuffer();
15200                         PQExpBuffer racl_subquery = createPQExpBuffer();
15201                         PQExpBuffer initacl_subquery = createPQExpBuffer();
15202                         PQExpBuffer initracl_subquery = createPQExpBuffer();
15203
15204                         buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
15205                                                         initracl_subquery, "at.attacl", "c.relowner", "'c'",
15206                                                         dopt->binary_upgrade);
15207
15208                         appendPQExpBuffer(query,
15209                                                           "SELECT at.attname, "
15210                                                           "%s AS attacl, "
15211                                                           "%s AS rattacl, "
15212                                                           "%s AS initattacl, "
15213                                                           "%s AS initrattacl "
15214                                                           "FROM pg_catalog.pg_attribute at "
15215                                                           "JOIN pg_catalog.pg_class c ON (at.attrelid = c.oid) "
15216                                                           "LEFT JOIN pg_catalog.pg_init_privs pip ON "
15217                                                           "(at.attrelid = pip.objoid "
15218                                                           "AND pip.classoid = 'pg_catalog.pg_class'::pg_catalog.regclass "
15219                                                           "AND at.attnum = pip.objsubid) "
15220                                                           "WHERE at.attrelid = '%u'::pg_catalog.oid AND "
15221                                                           "NOT at.attisdropped "
15222                                                           "AND ("
15223                                                           "%s IS NOT NULL OR "
15224                                                           "%s IS NOT NULL OR "
15225                                                           "%s IS NOT NULL OR "
15226                                                           "%s IS NOT NULL)"
15227                                                           "ORDER BY at.attnum",
15228                                                           acl_subquery->data,
15229                                                           racl_subquery->data,
15230                                                           initacl_subquery->data,
15231                                                           initracl_subquery->data,
15232                                                           tbinfo->dobj.catId.oid,
15233                                                           acl_subquery->data,
15234                                                           racl_subquery->data,
15235                                                           initacl_subquery->data,
15236                                                           initracl_subquery->data);
15237
15238                         destroyPQExpBuffer(acl_subquery);
15239                         destroyPQExpBuffer(racl_subquery);
15240                         destroyPQExpBuffer(initacl_subquery);
15241                         destroyPQExpBuffer(initracl_subquery);
15242                 }
15243                 else
15244                 {
15245                         appendPQExpBuffer(query,
15246                                                           "SELECT attname, attacl, NULL as rattacl, "
15247                                                           "NULL AS initattacl, NULL AS initrattacl "
15248                                                           "FROM pg_catalog.pg_attribute "
15249                                                           "WHERE attrelid = '%u'::pg_catalog.oid AND NOT attisdropped "
15250                                                           "AND attacl IS NOT NULL "
15251                                                           "ORDER BY attnum",
15252                                                           tbinfo->dobj.catId.oid);
15253                 }
15254
15255                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15256
15257                 for (i = 0; i < PQntuples(res); i++)
15258                 {
15259                         char       *attname = PQgetvalue(res, i, 0);
15260                         char       *attacl = PQgetvalue(res, i, 1);
15261                         char       *rattacl = PQgetvalue(res, i, 2);
15262                         char       *initattacl = PQgetvalue(res, i, 3);
15263                         char       *initrattacl = PQgetvalue(res, i, 4);
15264                         char       *attnamecopy;
15265
15266                         attnamecopy = pg_strdup(fmtId(attname));
15267                         /* Column's GRANT type is always TABLE */
15268                         dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15269                                         "TABLE", namecopy, attnamecopy,
15270                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15271                                         attacl, rattacl, initattacl, initrattacl);
15272                         free(attnamecopy);
15273                 }
15274                 PQclear(res);
15275                 destroyPQExpBuffer(query);
15276         }
15277
15278         free(namecopy);
15279
15280         return;
15281 }
15282
15283 /*
15284  * Create the AS clause for a view or materialized view. The semicolon is
15285  * stripped because a materialized view must add a WITH NO DATA clause.
15286  *
15287  * This returns a new buffer which must be freed by the caller.
15288  */
15289 static PQExpBuffer
15290 createViewAsClause(Archive *fout, TableInfo *tbinfo)
15291 {
15292         PQExpBuffer query = createPQExpBuffer();
15293         PQExpBuffer result = createPQExpBuffer();
15294         PGresult   *res;
15295         int                     len;
15296
15297         /* Fetch the view definition */
15298         appendPQExpBuffer(query,
15299                                           "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
15300                                           tbinfo->dobj.catId.oid);
15301
15302         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15303
15304         if (PQntuples(res) != 1)
15305         {
15306                 if (PQntuples(res) < 1)
15307                         exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
15308                                                   tbinfo->dobj.name);
15309                 else
15310                         exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
15311                                                   tbinfo->dobj.name);
15312         }
15313
15314         len = PQgetlength(res, 0, 0);
15315
15316         if (len == 0)
15317                 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
15318                                           tbinfo->dobj.name);
15319
15320         /* Strip off the trailing semicolon so that other things may follow. */
15321         Assert(PQgetvalue(res, 0, 0)[len - 1] == ';');
15322         appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
15323
15324         PQclear(res);
15325         destroyPQExpBuffer(query);
15326
15327         return result;
15328 }
15329
15330 /*
15331  * Create a dummy AS clause for a view.  This is used when the real view
15332  * definition has to be postponed because of circular dependencies.
15333  * We must duplicate the view's external properties -- column names and types
15334  * (including collation) -- so that it works for subsequent references.
15335  *
15336  * This returns a new buffer which must be freed by the caller.
15337  */
15338 static PQExpBuffer
15339 createDummyViewAsClause(Archive *fout, TableInfo *tbinfo)
15340 {
15341         PQExpBuffer result = createPQExpBuffer();
15342         int                     j;
15343
15344         appendPQExpBufferStr(result, "SELECT");
15345
15346         for (j = 0; j < tbinfo->numatts; j++)
15347         {
15348                 if (j > 0)
15349                         appendPQExpBufferChar(result, ',');
15350                 appendPQExpBufferStr(result, "\n    ");
15351
15352                 appendPQExpBuffer(result, "NULL::%s", tbinfo->atttypnames[j]);
15353
15354                 /*
15355                  * Must add collation if not default for the type, because CREATE OR
15356                  * REPLACE VIEW won't change it
15357                  */
15358                 if (OidIsValid(tbinfo->attcollation[j]))
15359                 {
15360                         CollInfo   *coll;
15361
15362                         coll = findCollationByOid(tbinfo->attcollation[j]);
15363                         if (coll)
15364                                 appendPQExpBuffer(result, " COLLATE %s",
15365                                                                   fmtQualifiedDumpable(coll));
15366                 }
15367
15368                 appendPQExpBuffer(result, " AS %s", fmtId(tbinfo->attnames[j]));
15369         }
15370
15371         return result;
15372 }
15373
15374 /*
15375  * dumpTableSchema
15376  *        write the declaration (not data) of one user-defined table or view
15377  */
15378 static void
15379 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
15380 {
15381         DumpOptions *dopt = fout->dopt;
15382         PQExpBuffer q = createPQExpBuffer();
15383         PQExpBuffer delq = createPQExpBuffer();
15384         char       *qrelname;
15385         char       *qualrelname;
15386         int                     numParents;
15387         TableInfo **parents;
15388         int                     actual_atts;    /* number of attrs in this CREATE statement */
15389         const char *reltypename;
15390         char       *storage;
15391         char       *srvname;
15392         char       *ftoptions;
15393         int                     j,
15394                                 k;
15395
15396         qrelname = pg_strdup(fmtId(tbinfo->dobj.name));
15397         qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
15398
15399         if (dopt->binary_upgrade)
15400                 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
15401                                                                                                 tbinfo->dobj.catId.oid);
15402
15403         /* Is it a table or a view? */
15404         if (tbinfo->relkind == RELKIND_VIEW)
15405         {
15406                 PQExpBuffer result;
15407
15408                 /*
15409                  * Note: keep this code in sync with the is_view case in dumpRule()
15410                  */
15411
15412                 reltypename = "VIEW";
15413
15414                 appendPQExpBuffer(delq, "DROP VIEW %s;\n", qualrelname);
15415
15416                 if (dopt->binary_upgrade)
15417                         binary_upgrade_set_pg_class_oids(fout, q,
15418                                                                                          tbinfo->dobj.catId.oid, false);
15419
15420                 appendPQExpBuffer(q, "CREATE VIEW %s", qualrelname);
15421
15422                 if (tbinfo->dummy_view)
15423                         result = createDummyViewAsClause(fout, tbinfo);
15424                 else
15425                 {
15426                         if (nonemptyReloptions(tbinfo->reloptions))
15427                         {
15428                                 appendPQExpBufferStr(q, " WITH (");
15429                                 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15430                                 appendPQExpBufferChar(q, ')');
15431                         }
15432                         result = createViewAsClause(fout, tbinfo);
15433                 }
15434                 appendPQExpBuffer(q, " AS\n%s", result->data);
15435                 destroyPQExpBuffer(result);
15436
15437                 if (tbinfo->checkoption != NULL && !tbinfo->dummy_view)
15438                         appendPQExpBuffer(q, "\n  WITH %s CHECK OPTION", tbinfo->checkoption);
15439                 appendPQExpBufferStr(q, ";\n");
15440         }
15441         else
15442         {
15443                 switch (tbinfo->relkind)
15444                 {
15445                         case RELKIND_FOREIGN_TABLE:
15446                                 {
15447                                         PQExpBuffer query = createPQExpBuffer();
15448                                         PGresult   *res;
15449                                         int                     i_srvname;
15450                                         int                     i_ftoptions;
15451
15452                                         reltypename = "FOREIGN TABLE";
15453
15454                                         /* retrieve name of foreign server and generic options */
15455                                         appendPQExpBuffer(query,
15456                                                                           "SELECT fs.srvname, "
15457                                                                           "pg_catalog.array_to_string(ARRAY("
15458                                                                           "SELECT pg_catalog.quote_ident(option_name) || "
15459                                                                           "' ' || pg_catalog.quote_literal(option_value) "
15460                                                                           "FROM pg_catalog.pg_options_to_table(ftoptions) "
15461                                                                           "ORDER BY option_name"
15462                                                                           "), E',\n    ') AS ftoptions "
15463                                                                           "FROM pg_catalog.pg_foreign_table ft "
15464                                                                           "JOIN pg_catalog.pg_foreign_server fs "
15465                                                                           "ON (fs.oid = ft.ftserver) "
15466                                                                           "WHERE ft.ftrelid = '%u'",
15467                                                                           tbinfo->dobj.catId.oid);
15468                                         res = ExecuteSqlQueryForSingleRow(fout, query->data);
15469                                         i_srvname = PQfnumber(res, "srvname");
15470                                         i_ftoptions = PQfnumber(res, "ftoptions");
15471                                         srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
15472                                         ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
15473                                         PQclear(res);
15474                                         destroyPQExpBuffer(query);
15475                                         break;
15476                                 }
15477                         case RELKIND_MATVIEW:
15478                                 reltypename = "MATERIALIZED VIEW";
15479                                 srvname = NULL;
15480                                 ftoptions = NULL;
15481                                 break;
15482                         default:
15483                                 reltypename = "TABLE";
15484                                 srvname = NULL;
15485                                 ftoptions = NULL;
15486                 }
15487
15488                 numParents = tbinfo->numParents;
15489                 parents = tbinfo->parents;
15490
15491                 appendPQExpBuffer(delq, "DROP %s %s;\n", reltypename, qualrelname);
15492
15493                 if (dopt->binary_upgrade)
15494                         binary_upgrade_set_pg_class_oids(fout, q,
15495                                                                                          tbinfo->dobj.catId.oid, false);
15496
15497                 appendPQExpBuffer(q, "CREATE %s%s %s",
15498                                                   tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
15499                                                   "UNLOGGED " : "",
15500                                                   reltypename,
15501                                                   qualrelname);
15502
15503                 /*
15504                  * Attach to type, if reloftype; except in case of a binary upgrade,
15505                  * we dump the table normally and attach it to the type afterward.
15506                  */
15507                 if (tbinfo->reloftype && !dopt->binary_upgrade)
15508                         appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
15509
15510                 /*
15511                  * If the table is a partition, dump it as such; except in the case of
15512                  * a binary upgrade, we dump the table normally and attach it to the
15513                  * parent afterward.
15514                  */
15515                 if (tbinfo->ispartition && !dopt->binary_upgrade)
15516                 {
15517                         TableInfo  *parentRel = tbinfo->parents[0];
15518
15519                         /*
15520                          * With partitions, unlike inheritance, there can only be one
15521                          * parent.
15522                          */
15523                         if (tbinfo->numParents != 1)
15524                                 exit_horribly(NULL, "invalid number of parents %d for table \"%s\"\n",
15525                                                           tbinfo->numParents, tbinfo->dobj.name);
15526
15527                         appendPQExpBuffer(q, " PARTITION OF %s",
15528                                                           fmtQualifiedDumpable(parentRel));
15529                 }
15530
15531                 if (tbinfo->relkind != RELKIND_MATVIEW)
15532                 {
15533                         /* Dump the attributes */
15534                         actual_atts = 0;
15535                         for (j = 0; j < tbinfo->numatts; j++)
15536                         {
15537                                 /*
15538                                  * Normally, dump if it's locally defined in this table, and
15539                                  * not dropped.  But for binary upgrade, we'll dump all the
15540                                  * columns, and then fix up the dropped and nonlocal cases
15541                                  * below.
15542                                  */
15543                                 if (shouldPrintColumn(dopt, tbinfo, j))
15544                                 {
15545                                         /*
15546                                          * Default value --- suppress if to be printed separately.
15547                                          */
15548                                         bool            has_default = (tbinfo->attrdefs[j] != NULL &&
15549                                                                                            !tbinfo->attrdefs[j]->separate);
15550
15551                                         /*
15552                                          * Not Null constraint --- suppress if inherited, except
15553                                          * in binary-upgrade case where that won't work.
15554                                          */
15555                                         bool            has_notnull = (tbinfo->notnull[j] &&
15556                                                                                            (!tbinfo->inhNotNull[j] ||
15557                                                                                                 dopt->binary_upgrade));
15558
15559                                         /*
15560                                          * Skip column if fully defined by reloftype or the
15561                                          * partition parent.
15562                                          */
15563                                         if ((tbinfo->reloftype || tbinfo->ispartition) &&
15564                                                 !has_default && !has_notnull && !dopt->binary_upgrade)
15565                                                 continue;
15566
15567                                         /* Format properly if not first attr */
15568                                         if (actual_atts == 0)
15569                                                 appendPQExpBufferStr(q, " (");
15570                                         else
15571                                                 appendPQExpBufferChar(q, ',');
15572                                         appendPQExpBufferStr(q, "\n    ");
15573                                         actual_atts++;
15574
15575                                         /* Attribute name */
15576                                         appendPQExpBufferStr(q, fmtId(tbinfo->attnames[j]));
15577
15578                                         if (tbinfo->attisdropped[j])
15579                                         {
15580                                                 /*
15581                                                  * ALTER TABLE DROP COLUMN clears
15582                                                  * pg_attribute.atttypid, so we will not have gotten a
15583                                                  * valid type name; insert INTEGER as a stopgap. We'll
15584                                                  * clean things up later.
15585                                                  */
15586                                                 appendPQExpBufferStr(q, " INTEGER /* dummy */");
15587                                                 /* Skip all the rest, too */
15588                                                 continue;
15589                                         }
15590
15591                                         /*
15592                                          * Attribute type
15593                                          *
15594                                          * In binary-upgrade mode, we always include the type. If
15595                                          * we aren't in binary-upgrade mode, then we skip the type
15596                                          * when creating a typed table ('OF type_name') or a
15597                                          * partition ('PARTITION OF'), since the type comes from
15598                                          * the parent/partitioned table.
15599                                          */
15600                                         if (dopt->binary_upgrade || (!tbinfo->reloftype && !tbinfo->ispartition))
15601                                         {
15602                                                 appendPQExpBuffer(q, " %s",
15603                                                                                   tbinfo->atttypnames[j]);
15604                                         }
15605
15606                                         /* Add collation if not default for the type */
15607                                         if (OidIsValid(tbinfo->attcollation[j]))
15608                                         {
15609                                                 CollInfo   *coll;
15610
15611                                                 coll = findCollationByOid(tbinfo->attcollation[j]);
15612                                                 if (coll)
15613                                                         appendPQExpBuffer(q, " COLLATE %s",
15614                                                                                           fmtQualifiedDumpable(coll));
15615                                         }
15616
15617                                         if (has_default)
15618                                                 appendPQExpBuffer(q, " DEFAULT %s",
15619                                                                                   tbinfo->attrdefs[j]->adef_expr);
15620
15621                                         if (has_notnull)
15622                                                 appendPQExpBufferStr(q, " NOT NULL");
15623                                 }
15624                         }
15625
15626                         /*
15627                          * Add non-inherited CHECK constraints, if any.
15628                          */
15629                         for (j = 0; j < tbinfo->ncheck; j++)
15630                         {
15631                                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
15632
15633                                 if (constr->separate || !constr->conislocal)
15634                                         continue;
15635
15636                                 if (actual_atts == 0)
15637                                         appendPQExpBufferStr(q, " (\n    ");
15638                                 else
15639                                         appendPQExpBufferStr(q, ",\n    ");
15640
15641                                 appendPQExpBuffer(q, "CONSTRAINT %s ",
15642                                                                   fmtId(constr->dobj.name));
15643                                 appendPQExpBufferStr(q, constr->condef);
15644
15645                                 actual_atts++;
15646                         }
15647
15648                         if (actual_atts)
15649                                 appendPQExpBufferStr(q, "\n)");
15650                         else if (!((tbinfo->reloftype || tbinfo->ispartition) &&
15651                                            !dopt->binary_upgrade))
15652                         {
15653                                 /*
15654                                  * We must have a parenthesized attribute list, even though
15655                                  * empty, when not using the OF TYPE or PARTITION OF syntax.
15656                                  */
15657                                 appendPQExpBufferStr(q, " (\n)");
15658                         }
15659
15660                         if (tbinfo->ispartition && !dopt->binary_upgrade)
15661                         {
15662                                 appendPQExpBufferChar(q, '\n');
15663                                 appendPQExpBufferStr(q, tbinfo->partbound);
15664                         }
15665
15666                         /* Emit the INHERITS clause, except if this is a partition. */
15667                         if (numParents > 0 &&
15668                                 !tbinfo->ispartition &&
15669                                 !dopt->binary_upgrade)
15670                         {
15671                                 appendPQExpBufferStr(q, "\nINHERITS (");
15672                                 for (k = 0; k < numParents; k++)
15673                                 {
15674                                         TableInfo  *parentRel = parents[k];
15675
15676                                         if (k > 0)
15677                                                 appendPQExpBufferStr(q, ", ");
15678                                         appendPQExpBufferStr(q, fmtQualifiedDumpable(parentRel));
15679                                 }
15680                                 appendPQExpBufferChar(q, ')');
15681                         }
15682
15683                         if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15684                                 appendPQExpBuffer(q, "\nPARTITION BY %s", tbinfo->partkeydef);
15685
15686                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
15687                                 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
15688                 }
15689
15690                 if (nonemptyReloptions(tbinfo->reloptions) ||
15691                         nonemptyReloptions(tbinfo->toast_reloptions))
15692                 {
15693                         bool            addcomma = false;
15694
15695                         appendPQExpBufferStr(q, "\nWITH (");
15696                         if (nonemptyReloptions(tbinfo->reloptions))
15697                         {
15698                                 addcomma = true;
15699                                 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15700                         }
15701                         if (nonemptyReloptions(tbinfo->toast_reloptions))
15702                         {
15703                                 if (addcomma)
15704                                         appendPQExpBufferStr(q, ", ");
15705                                 appendReloptionsArrayAH(q, tbinfo->toast_reloptions, "toast.",
15706                                                                                 fout);
15707                         }
15708                         appendPQExpBufferChar(q, ')');
15709                 }
15710
15711                 /* Dump generic options if any */
15712                 if (ftoptions && ftoptions[0])
15713                         appendPQExpBuffer(q, "\nOPTIONS (\n    %s\n)", ftoptions);
15714
15715                 /*
15716                  * For materialized views, create the AS clause just like a view. At
15717                  * this point, we always mark the view as not populated.
15718                  */
15719                 if (tbinfo->relkind == RELKIND_MATVIEW)
15720                 {
15721                         PQExpBuffer result;
15722
15723                         result = createViewAsClause(fout, tbinfo);
15724                         appendPQExpBuffer(q, " AS\n%s\n  WITH NO DATA;\n",
15725                                                           result->data);
15726                         destroyPQExpBuffer(result);
15727                 }
15728                 else
15729                         appendPQExpBufferStr(q, ";\n");
15730
15731                 /*
15732                  * in binary upgrade mode, update the catalog with any missing values
15733                  * that might be present.
15734                  */
15735                 if (dopt->binary_upgrade)
15736                 {
15737                         for (j = 0; j < tbinfo->numatts; j++)
15738                         {
15739                                 if (tbinfo->attmissingval[j][0] != '\0')
15740                                 {
15741                                         appendPQExpBufferStr(q, "\n-- set missing value.\n");
15742                                         appendPQExpBufferStr(q,
15743                                                                                  "SELECT pg_catalog.binary_upgrade_set_missing_value(");
15744                                         appendStringLiteralAH(q, qualrelname, fout);
15745                                         appendPQExpBufferStr(q, "::pg_catalog.regclass,");
15746                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15747                                         appendPQExpBufferStr(q, ",");
15748                                         appendStringLiteralAH(q, tbinfo->attmissingval[j], fout);
15749                                         appendPQExpBufferStr(q, ");\n\n");
15750                                 }
15751                         }
15752                 }
15753
15754                 /*
15755                  * To create binary-compatible heap files, we have to ensure the same
15756                  * physical column order, including dropped columns, as in the
15757                  * original.  Therefore, we create dropped columns above and drop them
15758                  * here, also updating their attlen/attalign values so that the
15759                  * dropped column can be skipped properly.  (We do not bother with
15760                  * restoring the original attbyval setting.)  Also, inheritance
15761                  * relationships are set up by doing ALTER TABLE INHERIT rather than
15762                  * using an INHERITS clause --- the latter would possibly mess up the
15763                  * column order.  That also means we have to take care about setting
15764                  * attislocal correctly, plus fix up any inherited CHECK constraints.
15765                  * Analogously, we set up typed tables using ALTER TABLE / OF here.
15766                  *
15767                  * We process foreign and partitioned tables here, even though they
15768                  * lack heap storage, because they can participate in inheritance
15769                  * relationships and we want this stuff to be consistent across the
15770                  * inheritance tree.  We can exclude indexes, toast tables, sequences
15771                  * and matviews, even though they have storage, because we don't
15772                  * support altering or dropping columns in them, nor can they be part
15773                  * of inheritance trees.
15774                  */
15775                 if (dopt->binary_upgrade &&
15776                         (tbinfo->relkind == RELKIND_RELATION ||
15777                          tbinfo->relkind == RELKIND_FOREIGN_TABLE ||
15778                          tbinfo->relkind == RELKIND_PARTITIONED_TABLE))
15779                 {
15780                         for (j = 0; j < tbinfo->numatts; j++)
15781                         {
15782                                 if (tbinfo->attisdropped[j])
15783                                 {
15784                                         appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate dropped column.\n");
15785                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
15786                                                                           "SET attlen = %d, "
15787                                                                           "attalign = '%c', attbyval = false\n"
15788                                                                           "WHERE attname = ",
15789                                                                           tbinfo->attlen[j],
15790                                                                           tbinfo->attalign[j]);
15791                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15792                                         appendPQExpBufferStr(q, "\n  AND attrelid = ");
15793                                         appendStringLiteralAH(q, qualrelname, fout);
15794                                         appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15795
15796                                         if (tbinfo->relkind == RELKIND_RELATION ||
15797                                                 tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15798                                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15799                                                                                   qualrelname);
15800                                         else
15801                                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE ONLY %s ",
15802                                                                                   qualrelname);
15803                                         appendPQExpBuffer(q, "DROP COLUMN %s;\n",
15804                                                                           fmtId(tbinfo->attnames[j]));
15805                                 }
15806                                 else if (!tbinfo->attislocal[j])
15807                                 {
15808                                         appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate inherited column.\n");
15809                                         appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_attribute\n"
15810                                                                                  "SET attislocal = false\n"
15811                                                                                  "WHERE attname = ");
15812                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15813                                         appendPQExpBufferStr(q, "\n  AND attrelid = ");
15814                                         appendStringLiteralAH(q, qualrelname, fout);
15815                                         appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15816                                 }
15817                         }
15818
15819                         for (k = 0; k < tbinfo->ncheck; k++)
15820                         {
15821                                 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
15822
15823                                 if (constr->separate || constr->conislocal)
15824                                         continue;
15825
15826                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inherited constraint.\n");
15827                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15828                                                                   qualrelname);
15829                                 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
15830                                                                   fmtId(constr->dobj.name));
15831                                 appendPQExpBuffer(q, "%s;\n", constr->condef);
15832                                 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_constraint\n"
15833                                                                          "SET conislocal = false\n"
15834                                                                          "WHERE contype = 'c' AND conname = ");
15835                                 appendStringLiteralAH(q, constr->dobj.name, fout);
15836                                 appendPQExpBufferStr(q, "\n  AND conrelid = ");
15837                                 appendStringLiteralAH(q, qualrelname, fout);
15838                                 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15839                         }
15840
15841                         if (numParents > 0)
15842                         {
15843                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inheritance and partitioning this way.\n");
15844                                 for (k = 0; k < numParents; k++)
15845                                 {
15846                                         TableInfo  *parentRel = parents[k];
15847
15848                                         /* In the partitioning case, we alter the parent */
15849                                         if (tbinfo->ispartition)
15850                                                 appendPQExpBuffer(q,
15851                                                                                   "ALTER TABLE ONLY %s ATTACH PARTITION ",
15852                                                                                   fmtQualifiedDumpable(parentRel));
15853                                         else
15854                                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
15855                                                                                   qualrelname);
15856
15857                                         /* Partition needs specifying the bounds */
15858                                         if (tbinfo->ispartition)
15859                                                 appendPQExpBuffer(q, "%s %s;\n",
15860                                                                                   qualrelname,
15861                                                                                   tbinfo->partbound);
15862                                         else
15863                                                 appendPQExpBuffer(q, "%s;\n",
15864                                                                                   fmtQualifiedDumpable(parentRel));
15865                                 }
15866                         }
15867
15868                         if (tbinfo->reloftype)
15869                         {
15870                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up typed tables this way.\n");
15871                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
15872                                                                   qualrelname,
15873                                                                   tbinfo->reloftype);
15874                         }
15875                 }
15876
15877                 /*
15878                  * In binary_upgrade mode, arrange to restore the old relfrozenxid and
15879                  * relminmxid of all vacuumable relations.  (While vacuum.c processes
15880                  * TOAST tables semi-independently, here we see them only as children
15881                  * of other relations; so this "if" lacks RELKIND_TOASTVALUE, and the
15882                  * child toast table is handled below.)
15883                  */
15884                 if (dopt->binary_upgrade &&
15885                         (tbinfo->relkind == RELKIND_RELATION ||
15886                          tbinfo->relkind == RELKIND_MATVIEW))
15887                 {
15888                         appendPQExpBufferStr(q, "\n-- For binary upgrade, set heap's relfrozenxid and relminmxid\n");
15889                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
15890                                                           "SET relfrozenxid = '%u', relminmxid = '%u'\n"
15891                                                           "WHERE oid = ",
15892                                                           tbinfo->frozenxid, tbinfo->minmxid);
15893                         appendStringLiteralAH(q, qualrelname, fout);
15894                         appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15895
15896                         if (tbinfo->toast_oid)
15897                         {
15898                                 /*
15899                                  * The toast table will have the same OID at restore, so we
15900                                  * can safely target it by OID.
15901                                  */
15902                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, set toast's relfrozenxid and relminmxid\n");
15903                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
15904                                                                   "SET relfrozenxid = '%u', relminmxid = '%u'\n"
15905                                                                   "WHERE oid = '%u';\n",
15906                                                                   tbinfo->toast_frozenxid,
15907                                                                   tbinfo->toast_minmxid, tbinfo->toast_oid);
15908                         }
15909                 }
15910
15911                 /*
15912                  * In binary_upgrade mode, restore matviews' populated status by
15913                  * poking pg_class directly.  This is pretty ugly, but we can't use
15914                  * REFRESH MATERIALIZED VIEW since it's possible that some underlying
15915                  * matview is not populated even though this matview is; in any case,
15916                  * we want to transfer the matview's heap storage, not run REFRESH.
15917                  */
15918                 if (dopt->binary_upgrade && tbinfo->relkind == RELKIND_MATVIEW &&
15919                         tbinfo->relispopulated)
15920                 {
15921                         appendPQExpBufferStr(q, "\n-- For binary upgrade, mark materialized view as populated\n");
15922                         appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_class\n"
15923                                                                  "SET relispopulated = 't'\n"
15924                                                                  "WHERE oid = ");
15925                         appendStringLiteralAH(q, qualrelname, fout);
15926                         appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15927                 }
15928
15929                 /*
15930                  * Dump additional per-column properties that we can't handle in the
15931                  * main CREATE TABLE command.
15932                  */
15933                 for (j = 0; j < tbinfo->numatts; j++)
15934                 {
15935                         /* None of this applies to dropped columns */
15936                         if (tbinfo->attisdropped[j])
15937                                 continue;
15938
15939                         /*
15940                          * If we didn't dump the column definition explicitly above, and
15941                          * it is NOT NULL and did not inherit that property from a parent,
15942                          * we have to mark it separately.
15943                          */
15944                         if (!shouldPrintColumn(dopt, tbinfo, j) &&
15945                                 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
15946                         {
15947                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15948                                                                   qualrelname);
15949                                 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
15950                                                                   fmtId(tbinfo->attnames[j]));
15951                         }
15952
15953                         /*
15954                          * Dump per-column statistics information. We only issue an ALTER
15955                          * TABLE statement if the attstattarget entry for this column is
15956                          * non-negative (i.e. it's not the default value)
15957                          */
15958                         if (tbinfo->attstattarget[j] >= 0)
15959                         {
15960                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15961                                                                   qualrelname);
15962                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15963                                                                   fmtId(tbinfo->attnames[j]));
15964                                 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
15965                                                                   tbinfo->attstattarget[j]);
15966                         }
15967
15968                         /*
15969                          * Dump per-column storage information.  The statement is only
15970                          * dumped if the storage has been changed from the type's default.
15971                          */
15972                         if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
15973                         {
15974                                 switch (tbinfo->attstorage[j])
15975                                 {
15976                                         case 'p':
15977                                                 storage = "PLAIN";
15978                                                 break;
15979                                         case 'e':
15980                                                 storage = "EXTERNAL";
15981                                                 break;
15982                                         case 'm':
15983                                                 storage = "MAIN";
15984                                                 break;
15985                                         case 'x':
15986                                                 storage = "EXTENDED";
15987                                                 break;
15988                                         default:
15989                                                 storage = NULL;
15990                                 }
15991
15992                                 /*
15993                                  * Only dump the statement if it's a storage type we recognize
15994                                  */
15995                                 if (storage != NULL)
15996                                 {
15997                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15998                                                                           qualrelname);
15999                                         appendPQExpBuffer(q, "ALTER COLUMN %s ",
16000                                                                           fmtId(tbinfo->attnames[j]));
16001                                         appendPQExpBuffer(q, "SET STORAGE %s;\n",
16002                                                                           storage);
16003                                 }
16004                         }
16005
16006                         /*
16007                          * Dump per-column attributes.
16008                          */
16009                         if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
16010                         {
16011                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16012                                                                   qualrelname);
16013                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16014                                                                   fmtId(tbinfo->attnames[j]));
16015                                 appendPQExpBuffer(q, "SET (%s);\n",
16016                                                                   tbinfo->attoptions[j]);
16017                         }
16018
16019                         /*
16020                          * Dump per-column fdw options.
16021                          */
16022                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
16023                                 tbinfo->attfdwoptions[j] &&
16024                                 tbinfo->attfdwoptions[j][0] != '\0')
16025                         {
16026                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
16027                                                                   qualrelname);
16028                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16029                                                                   fmtId(tbinfo->attnames[j]));
16030                                 appendPQExpBuffer(q, "OPTIONS (\n    %s\n);\n",
16031                                                                   tbinfo->attfdwoptions[j]);
16032                         }
16033                 }
16034         }
16035
16036         /*
16037          * dump properties we only have ALTER TABLE syntax for
16038          */
16039         if ((tbinfo->relkind == RELKIND_RELATION ||
16040                  tbinfo->relkind == RELKIND_PARTITIONED_TABLE ||
16041                  tbinfo->relkind == RELKIND_MATVIEW) &&
16042                 tbinfo->relreplident != REPLICA_IDENTITY_DEFAULT)
16043         {
16044                 if (tbinfo->relreplident == REPLICA_IDENTITY_INDEX)
16045                 {
16046                         /* nothing to do, will be set when the index is dumped */
16047                 }
16048                 else if (tbinfo->relreplident == REPLICA_IDENTITY_NOTHING)
16049                 {
16050                         appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY NOTHING;\n",
16051                                                           qualrelname);
16052                 }
16053                 else if (tbinfo->relreplident == REPLICA_IDENTITY_FULL)
16054                 {
16055                         appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY FULL;\n",
16056                                                           qualrelname);
16057                 }
16058         }
16059
16060         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE && tbinfo->hasoids)
16061                 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s SET WITH OIDS;\n",
16062                                                   qualrelname);
16063
16064         if (tbinfo->forcerowsec)
16065                 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s FORCE ROW LEVEL SECURITY;\n",
16066                                                   qualrelname);
16067
16068         if (dopt->binary_upgrade)
16069                 binary_upgrade_extension_member(q, &tbinfo->dobj,
16070                                                                                 reltypename, qrelname,
16071                                                                                 tbinfo->dobj.namespace->dobj.name);
16072
16073         if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16074                 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
16075                                          tbinfo->dobj.name,
16076                                          tbinfo->dobj.namespace->dobj.name,
16077                                          (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
16078                                          tbinfo->rolname,
16079                                          (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
16080                                          reltypename,
16081                                          tbinfo->postponed_def ?
16082                                          SECTION_POST_DATA : SECTION_PRE_DATA,
16083                                          q->data, delq->data, NULL,
16084                                          NULL, 0,
16085                                          NULL, NULL);
16086
16087
16088         /* Dump Table Comments */
16089         if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16090                 dumpTableComment(fout, tbinfo, reltypename);
16091
16092         /* Dump Table Security Labels */
16093         if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16094                 dumpTableSecLabel(fout, tbinfo, reltypename);
16095
16096         /* Dump comments on inlined table constraints */
16097         for (j = 0; j < tbinfo->ncheck; j++)
16098         {
16099                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
16100
16101                 if (constr->separate || !constr->conislocal)
16102                         continue;
16103
16104                 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16105                         dumpTableConstraintComment(fout, constr);
16106         }
16107
16108         destroyPQExpBuffer(q);
16109         destroyPQExpBuffer(delq);
16110         free(qrelname);
16111         free(qualrelname);
16112 }
16113
16114 /*
16115  * dumpAttrDef --- dump an attribute's default-value declaration
16116  */
16117 static void
16118 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
16119 {
16120         DumpOptions *dopt = fout->dopt;
16121         TableInfo  *tbinfo = adinfo->adtable;
16122         int                     adnum = adinfo->adnum;
16123         PQExpBuffer q;
16124         PQExpBuffer delq;
16125         char       *qualrelname;
16126         char       *tag;
16127
16128         /* Skip if table definition not to be dumped */
16129         if (!tbinfo->dobj.dump || dopt->dataOnly)
16130                 return;
16131
16132         /* Skip if not "separate"; it was dumped in the table's definition */
16133         if (!adinfo->separate)
16134                 return;
16135
16136         q = createPQExpBuffer();
16137         delq = createPQExpBuffer();
16138
16139         qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
16140
16141         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16142                                           qualrelname);
16143         appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
16144                                           fmtId(tbinfo->attnames[adnum - 1]),
16145                                           adinfo->adef_expr);
16146
16147         appendPQExpBuffer(delq, "ALTER TABLE %s ",
16148                                           qualrelname);
16149         appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
16150                                           fmtId(tbinfo->attnames[adnum - 1]));
16151
16152         tag = psprintf("%s %s", tbinfo->dobj.name, tbinfo->attnames[adnum - 1]);
16153
16154         if (adinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16155                 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
16156                                          tag,
16157                                          tbinfo->dobj.namespace->dobj.name,
16158                                          NULL,
16159                                          tbinfo->rolname,
16160                                          false, "DEFAULT", SECTION_PRE_DATA,
16161                                          q->data, delq->data, NULL,
16162                                          NULL, 0,
16163                                          NULL, NULL);
16164
16165         free(tag);
16166         destroyPQExpBuffer(q);
16167         destroyPQExpBuffer(delq);
16168         free(qualrelname);
16169 }
16170
16171 /*
16172  * getAttrName: extract the correct name for an attribute
16173  *
16174  * The array tblInfo->attnames[] only provides names of user attributes;
16175  * if a system attribute number is supplied, we have to fake it.
16176  * We also do a little bit of bounds checking for safety's sake.
16177  */
16178 static const char *
16179 getAttrName(int attrnum, TableInfo *tblInfo)
16180 {
16181         if (attrnum > 0 && attrnum <= tblInfo->numatts)
16182                 return tblInfo->attnames[attrnum - 1];
16183         switch (attrnum)
16184         {
16185                 case SelfItemPointerAttributeNumber:
16186                         return "ctid";
16187                 case ObjectIdAttributeNumber:
16188                         return "oid";
16189                 case MinTransactionIdAttributeNumber:
16190                         return "xmin";
16191                 case MinCommandIdAttributeNumber:
16192                         return "cmin";
16193                 case MaxTransactionIdAttributeNumber:
16194                         return "xmax";
16195                 case MaxCommandIdAttributeNumber:
16196                         return "cmax";
16197                 case TableOidAttributeNumber:
16198                         return "tableoid";
16199         }
16200         exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
16201                                   attrnum, tblInfo->dobj.name);
16202         return NULL;                            /* keep compiler quiet */
16203 }
16204
16205 /*
16206  * dumpIndex
16207  *        write out to fout a user-defined index
16208  */
16209 static void
16210 dumpIndex(Archive *fout, IndxInfo *indxinfo)
16211 {
16212         DumpOptions *dopt = fout->dopt;
16213         TableInfo  *tbinfo = indxinfo->indextable;
16214         bool            is_constraint = (indxinfo->indexconstraint != 0);
16215         PQExpBuffer q;
16216         PQExpBuffer delq;
16217         char       *qindxname;
16218
16219         if (dopt->dataOnly)
16220                 return;
16221
16222         q = createPQExpBuffer();
16223         delq = createPQExpBuffer();
16224
16225         qindxname = pg_strdup(fmtId(indxinfo->dobj.name));
16226
16227         /*
16228          * If there's an associated constraint, don't dump the index per se, but
16229          * do dump any comment for it.  (This is safe because dependency ordering
16230          * will have ensured the constraint is emitted first.)  Note that the
16231          * emitted comment has to be shown as depending on the constraint, not the
16232          * index, in such cases.
16233          */
16234         if (!is_constraint)
16235         {
16236                 if (dopt->binary_upgrade)
16237                         binary_upgrade_set_pg_class_oids(fout, q,
16238                                                                                          indxinfo->dobj.catId.oid, true);
16239
16240                 /* Plain secondary index */
16241                 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
16242
16243                 /*
16244                  * Append ALTER TABLE commands as needed to set properties that we
16245                  * only have ALTER TABLE syntax for.  Keep this in sync with the
16246                  * similar code in dumpConstraint!
16247                  */
16248
16249                 /* If the index is clustered, we need to record that. */
16250                 if (indxinfo->indisclustered)
16251                 {
16252                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16253                                                           fmtQualifiedDumpable(tbinfo));
16254                         /* index name is not qualified in this syntax */
16255                         appendPQExpBuffer(q, " ON %s;\n",
16256                                                           qindxname);
16257                 }
16258
16259                 /* If the index defines identity, we need to record that. */
16260                 if (indxinfo->indisreplident)
16261                 {
16262                         appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
16263                                                           fmtQualifiedDumpable(tbinfo));
16264                         /* index name is not qualified in this syntax */
16265                         appendPQExpBuffer(q, " INDEX %s;\n",
16266                                                           qindxname);
16267                 }
16268
16269                 appendPQExpBuffer(delq, "DROP INDEX %s;\n",
16270                                                   fmtQualifiedDumpable(indxinfo));
16271
16272                 if (indxinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16273                         ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
16274                                                  indxinfo->dobj.name,
16275                                                  tbinfo->dobj.namespace->dobj.name,
16276                                                  indxinfo->tablespace,
16277                                                  tbinfo->rolname, false,
16278                                                  "INDEX", SECTION_POST_DATA,
16279                                                  q->data, delq->data, NULL,
16280                                                  NULL, 0,
16281                                                  NULL, NULL);
16282         }
16283
16284         /* Dump Index Comments */
16285         if (indxinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16286                 dumpComment(fout, "INDEX", qindxname,
16287                                         tbinfo->dobj.namespace->dobj.name,
16288                                         tbinfo->rolname,
16289                                         indxinfo->dobj.catId, 0,
16290                                         is_constraint ? indxinfo->indexconstraint :
16291                                         indxinfo->dobj.dumpId);
16292
16293         destroyPQExpBuffer(q);
16294         destroyPQExpBuffer(delq);
16295         free(qindxname);
16296 }
16297
16298 /*
16299  * dumpIndexAttach
16300  *        write out to fout a partitioned-index attachment clause
16301  */
16302 static void
16303 dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo)
16304 {
16305         if (fout->dopt->dataOnly)
16306                 return;
16307
16308         if (attachinfo->partitionIdx->dobj.dump & DUMP_COMPONENT_DEFINITION)
16309         {
16310                 PQExpBuffer q = createPQExpBuffer();
16311
16312                 appendPQExpBuffer(q, "\nALTER INDEX %s ",
16313                                                   fmtQualifiedDumpable(attachinfo->parentIdx));
16314                 appendPQExpBuffer(q, "ATTACH PARTITION %s;\n",
16315                                                   fmtQualifiedDumpable(attachinfo->partitionIdx));
16316
16317                 ArchiveEntry(fout, attachinfo->dobj.catId, attachinfo->dobj.dumpId,
16318                                          attachinfo->dobj.name,
16319                                          NULL, NULL,
16320                                          "",
16321                                          false, "INDEX ATTACH", SECTION_POST_DATA,
16322                                          q->data, "", NULL,
16323                                          NULL, 0,
16324                                          NULL, NULL);
16325
16326                 destroyPQExpBuffer(q);
16327         }
16328 }
16329
16330 /*
16331  * dumpStatisticsExt
16332  *        write out to fout an extended statistics object
16333  */
16334 static void
16335 dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo)
16336 {
16337         DumpOptions *dopt = fout->dopt;
16338         PQExpBuffer q;
16339         PQExpBuffer delq;
16340         PQExpBuffer query;
16341         char       *qstatsextname;
16342         PGresult   *res;
16343         char       *stxdef;
16344
16345         /* Skip if not to be dumped */
16346         if (!statsextinfo->dobj.dump || dopt->dataOnly)
16347                 return;
16348
16349         q = createPQExpBuffer();
16350         delq = createPQExpBuffer();
16351         query = createPQExpBuffer();
16352
16353         qstatsextname = pg_strdup(fmtId(statsextinfo->dobj.name));
16354
16355         appendPQExpBuffer(query, "SELECT "
16356                                           "pg_catalog.pg_get_statisticsobjdef('%u'::pg_catalog.oid)",
16357                                           statsextinfo->dobj.catId.oid);
16358
16359         res = ExecuteSqlQueryForSingleRow(fout, query->data);
16360
16361         stxdef = PQgetvalue(res, 0, 0);
16362
16363         /* Result of pg_get_statisticsobjdef is complete except for semicolon */
16364         appendPQExpBuffer(q, "%s;\n", stxdef);
16365
16366         appendPQExpBuffer(delq, "DROP STATISTICS %s;\n",
16367                                           fmtQualifiedDumpable(statsextinfo));
16368
16369         if (statsextinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16370                 ArchiveEntry(fout, statsextinfo->dobj.catId,
16371                                          statsextinfo->dobj.dumpId,
16372                                          statsextinfo->dobj.name,
16373                                          statsextinfo->dobj.namespace->dobj.name,
16374                                          NULL,
16375                                          statsextinfo->rolname, false,
16376                                          "STATISTICS", SECTION_POST_DATA,
16377                                          q->data, delq->data, NULL,
16378                                          NULL, 0,
16379                                          NULL, NULL);
16380
16381         /* Dump Statistics Comments */
16382         if (statsextinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16383                 dumpComment(fout, "STATISTICS", qstatsextname,
16384                                         statsextinfo->dobj.namespace->dobj.name,
16385                                         statsextinfo->rolname,
16386                                         statsextinfo->dobj.catId, 0,
16387                                         statsextinfo->dobj.dumpId);
16388
16389         PQclear(res);
16390         destroyPQExpBuffer(q);
16391         destroyPQExpBuffer(delq);
16392         destroyPQExpBuffer(query);
16393         free(qstatsextname);
16394 }
16395
16396 /*
16397  * dumpConstraint
16398  *        write out to fout a user-defined constraint
16399  */
16400 static void
16401 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
16402 {
16403         DumpOptions *dopt = fout->dopt;
16404         TableInfo  *tbinfo = coninfo->contable;
16405         PQExpBuffer q;
16406         PQExpBuffer delq;
16407         char       *tag = NULL;
16408
16409         /* Skip if not to be dumped */
16410         if (!coninfo->dobj.dump || dopt->dataOnly)
16411                 return;
16412
16413         q = createPQExpBuffer();
16414         delq = createPQExpBuffer();
16415
16416         if (coninfo->contype == 'p' ||
16417                 coninfo->contype == 'u' ||
16418                 coninfo->contype == 'x')
16419         {
16420                 /* Index-related constraint */
16421                 IndxInfo   *indxinfo;
16422                 int                     k;
16423
16424                 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
16425
16426                 if (indxinfo == NULL)
16427                         exit_horribly(NULL, "missing index for constraint \"%s\"\n",
16428                                                   coninfo->dobj.name);
16429
16430                 if (dopt->binary_upgrade)
16431                         binary_upgrade_set_pg_class_oids(fout, q,
16432                                                                                          indxinfo->dobj.catId.oid, true);
16433
16434                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
16435                                                   fmtQualifiedDumpable(tbinfo));
16436                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s ",
16437                                                   fmtId(coninfo->dobj.name));
16438
16439                 if (coninfo->condef)
16440                 {
16441                         /* pg_get_constraintdef should have provided everything */
16442                         appendPQExpBuffer(q, "%s;\n", coninfo->condef);
16443                 }
16444                 else
16445                 {
16446                         appendPQExpBuffer(q, "%s (",
16447                                                           coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
16448                         for (k = 0; k < indxinfo->indnkeyattrs; k++)
16449                         {
16450                                 int                     indkey = (int) indxinfo->indkeys[k];
16451                                 const char *attname;
16452
16453                                 if (indkey == InvalidAttrNumber)
16454                                         break;
16455                                 attname = getAttrName(indkey, tbinfo);
16456
16457                                 appendPQExpBuffer(q, "%s%s",
16458                                                                   (k == 0) ? "" : ", ",
16459                                                                   fmtId(attname));
16460                         }
16461
16462                         if (indxinfo->indnkeyattrs < indxinfo->indnattrs)
16463                                 appendPQExpBuffer(q, ") INCLUDE (");
16464
16465                         for (k = indxinfo->indnkeyattrs; k < indxinfo->indnattrs; k++)
16466                         {
16467                                 int                     indkey = (int) indxinfo->indkeys[k];
16468                                 const char *attname;
16469
16470                                 if (indkey == InvalidAttrNumber)
16471                                         break;
16472                                 attname = getAttrName(indkey, tbinfo);
16473
16474                                 appendPQExpBuffer(q, "%s%s",
16475                                                                   (k == indxinfo->indnkeyattrs) ? "" : ", ",
16476                                                                   fmtId(attname));
16477                         }
16478
16479                         appendPQExpBufferChar(q, ')');
16480
16481                         if (nonemptyReloptions(indxinfo->indreloptions))
16482                         {
16483                                 appendPQExpBufferStr(q, " WITH (");
16484                                 appendReloptionsArrayAH(q, indxinfo->indreloptions, "", fout);
16485                                 appendPQExpBufferChar(q, ')');
16486                         }
16487
16488                         if (coninfo->condeferrable)
16489                         {
16490                                 appendPQExpBufferStr(q, " DEFERRABLE");
16491                                 if (coninfo->condeferred)
16492                                         appendPQExpBufferStr(q, " INITIALLY DEFERRED");
16493                         }
16494
16495                         appendPQExpBufferStr(q, ";\n");
16496                 }
16497
16498                 /*
16499                  * Append ALTER TABLE commands as needed to set properties that we
16500                  * only have ALTER TABLE syntax for.  Keep this in sync with the
16501                  * similar code in dumpIndex!
16502                  */
16503
16504                 /* If the index is clustered, we need to record that. */
16505                 if (indxinfo->indisclustered)
16506                 {
16507                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16508                                                           fmtQualifiedDumpable(tbinfo));
16509                         /* index name is not qualified in this syntax */
16510                         appendPQExpBuffer(q, " ON %s;\n",
16511                                                           fmtId(indxinfo->dobj.name));
16512                 }
16513
16514                 /* If the index defines identity, we need to record that. */
16515                 if (indxinfo->indisreplident)
16516                 {
16517                         appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
16518                                                           fmtQualifiedDumpable(tbinfo));
16519                         /* index name is not qualified in this syntax */
16520                         appendPQExpBuffer(q, " INDEX %s;\n",
16521                                                           fmtId(indxinfo->dobj.name));
16522                 }
16523
16524                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s ",
16525                                                   fmtQualifiedDumpable(tbinfo));
16526                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16527                                                   fmtId(coninfo->dobj.name));
16528
16529                 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16530
16531                 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16532                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16533                                                  tag,
16534                                                  tbinfo->dobj.namespace->dobj.name,
16535                                                  indxinfo->tablespace,
16536                                                  tbinfo->rolname, false,
16537                                                  "CONSTRAINT", SECTION_POST_DATA,
16538                                                  q->data, delq->data, NULL,
16539                                                  NULL, 0,
16540                                                  NULL, NULL);
16541         }
16542         else if (coninfo->contype == 'f')
16543         {
16544                 char       *only;
16545
16546                 /*
16547                  * Foreign keys on partitioned tables are always declared as
16548                  * inheriting to partitions; for all other cases, emit them as
16549                  * applying ONLY directly to the named table, because that's how they
16550                  * work for regular inherited tables.
16551                  */
16552                 only = tbinfo->relkind == RELKIND_PARTITIONED_TABLE ? "" : "ONLY ";
16553
16554                 /*
16555                  * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
16556                  * current table data is not processed
16557                  */
16558                 appendPQExpBuffer(q, "ALTER TABLE %s%s\n",
16559                                                   only, fmtQualifiedDumpable(tbinfo));
16560                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
16561                                                   fmtId(coninfo->dobj.name),
16562                                                   coninfo->condef);
16563
16564                 appendPQExpBuffer(delq, "ALTER TABLE %s%s ",
16565                                                   only, fmtQualifiedDumpable(tbinfo));
16566                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16567                                                   fmtId(coninfo->dobj.name));
16568
16569                 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16570
16571                 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16572                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16573                                                  tag,
16574                                                  tbinfo->dobj.namespace->dobj.name,
16575                                                  NULL,
16576                                                  tbinfo->rolname, false,
16577                                                  "FK CONSTRAINT", SECTION_POST_DATA,
16578                                                  q->data, delq->data, NULL,
16579                                                  NULL, 0,
16580                                                  NULL, NULL);
16581         }
16582         else if (coninfo->contype == 'c' && tbinfo)
16583         {
16584                 /* CHECK constraint on a table */
16585
16586                 /* Ignore if not to be dumped separately, or if it was inherited */
16587                 if (coninfo->separate && coninfo->conislocal)
16588                 {
16589                         /* not ONLY since we want it to propagate to children */
16590                         appendPQExpBuffer(q, "ALTER TABLE %s\n",
16591                                                           fmtQualifiedDumpable(tbinfo));
16592                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
16593                                                           fmtId(coninfo->dobj.name),
16594                                                           coninfo->condef);
16595
16596                         appendPQExpBuffer(delq, "ALTER TABLE %s ",
16597                                                           fmtQualifiedDumpable(tbinfo));
16598                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16599                                                           fmtId(coninfo->dobj.name));
16600
16601                         tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16602
16603                         if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16604                                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16605                                                          tag,
16606                                                          tbinfo->dobj.namespace->dobj.name,
16607                                                          NULL,
16608                                                          tbinfo->rolname, false,
16609                                                          "CHECK CONSTRAINT", SECTION_POST_DATA,
16610                                                          q->data, delq->data, NULL,
16611                                                          NULL, 0,
16612                                                          NULL, NULL);
16613                 }
16614         }
16615         else if (coninfo->contype == 'c' && tbinfo == NULL)
16616         {
16617                 /* CHECK constraint on a domain */
16618                 TypeInfo   *tyinfo = coninfo->condomain;
16619
16620                 /* Ignore if not to be dumped separately */
16621                 if (coninfo->separate)
16622                 {
16623                         appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
16624                                                           fmtQualifiedDumpable(tyinfo));
16625                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
16626                                                           fmtId(coninfo->dobj.name),
16627                                                           coninfo->condef);
16628
16629                         appendPQExpBuffer(delq, "ALTER DOMAIN %s ",
16630                                                           fmtQualifiedDumpable(tyinfo));
16631                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16632                                                           fmtId(coninfo->dobj.name));
16633
16634                         tag = psprintf("%s %s", tyinfo->dobj.name, coninfo->dobj.name);
16635
16636                         if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16637                                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16638                                                          tag,
16639                                                          tyinfo->dobj.namespace->dobj.name,
16640                                                          NULL,
16641                                                          tyinfo->rolname, false,
16642                                                          "CHECK CONSTRAINT", SECTION_POST_DATA,
16643                                                          q->data, delq->data, NULL,
16644                                                          NULL, 0,
16645                                                          NULL, NULL);
16646                 }
16647         }
16648         else
16649         {
16650                 exit_horribly(NULL, "unrecognized constraint type: %c\n",
16651                                           coninfo->contype);
16652         }
16653
16654         /* Dump Constraint Comments --- only works for table constraints */
16655         if (tbinfo && coninfo->separate &&
16656                 coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16657                 dumpTableConstraintComment(fout, coninfo);
16658
16659         free(tag);
16660         destroyPQExpBuffer(q);
16661         destroyPQExpBuffer(delq);
16662 }
16663
16664 /*
16665  * dumpTableConstraintComment --- dump a constraint's comment if any
16666  *
16667  * This is split out because we need the function in two different places
16668  * depending on whether the constraint is dumped as part of CREATE TABLE
16669  * or as a separate ALTER command.
16670  */
16671 static void
16672 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
16673 {
16674         TableInfo  *tbinfo = coninfo->contable;
16675         PQExpBuffer conprefix = createPQExpBuffer();
16676         char       *qtabname;
16677
16678         qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
16679
16680         appendPQExpBuffer(conprefix, "CONSTRAINT %s ON",
16681                                           fmtId(coninfo->dobj.name));
16682
16683         if (coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16684                 dumpComment(fout, conprefix->data, qtabname,
16685                                         tbinfo->dobj.namespace->dobj.name,
16686                                         tbinfo->rolname,
16687                                         coninfo->dobj.catId, 0,
16688                                         coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
16689
16690         destroyPQExpBuffer(conprefix);
16691         free(qtabname);
16692 }
16693
16694 /*
16695  * findLastBuiltinOid_V71 -
16696  *
16697  * find the last built in oid
16698  *
16699  * For 7.1 through 8.0, we do this by retrieving datlastsysoid from the
16700  * pg_database entry for the current database.  (Note: current_database()
16701  * requires 7.3; pg_dump requires 8.0 now.)
16702  */
16703 static Oid
16704 findLastBuiltinOid_V71(Archive *fout)
16705 {
16706         PGresult   *res;
16707         Oid                     last_oid;
16708
16709         res = ExecuteSqlQueryForSingleRow(fout,
16710                                                                           "SELECT datlastsysoid FROM pg_database WHERE datname = current_database()");
16711         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
16712         PQclear(res);
16713
16714         return last_oid;
16715 }
16716
16717 /*
16718  * dumpSequence
16719  *        write the declaration (not data) of one user-defined sequence
16720  */
16721 static void
16722 dumpSequence(Archive *fout, TableInfo *tbinfo)
16723 {
16724         DumpOptions *dopt = fout->dopt;
16725         PGresult   *res;
16726         char       *startv,
16727                            *incby,
16728                            *maxv,
16729                            *minv,
16730                            *cache,
16731                            *seqtype;
16732         bool            cycled;
16733         bool            is_ascending;
16734         int64           default_minv,
16735                                 default_maxv;
16736         char            bufm[32],
16737                                 bufx[32];
16738         PQExpBuffer query = createPQExpBuffer();
16739         PQExpBuffer delqry = createPQExpBuffer();
16740         char       *qseqname;
16741
16742         qseqname = pg_strdup(fmtId(tbinfo->dobj.name));
16743
16744         if (fout->remoteVersion >= 100000)
16745         {
16746                 appendPQExpBuffer(query,
16747                                                   "SELECT format_type(seqtypid, NULL), "
16748                                                   "seqstart, seqincrement, "
16749                                                   "seqmax, seqmin, "
16750                                                   "seqcache, seqcycle "
16751                                                   "FROM pg_catalog.pg_sequence "
16752                                                   "WHERE seqrelid = '%u'::oid",
16753                                                   tbinfo->dobj.catId.oid);
16754         }
16755         else if (fout->remoteVersion >= 80400)
16756         {
16757                 /*
16758                  * Before PostgreSQL 10, sequence metadata is in the sequence itself.
16759                  *
16760                  * Note: it might seem that 'bigint' potentially needs to be
16761                  * schema-qualified, but actually that's a keyword.
16762                  */
16763                 appendPQExpBuffer(query,
16764                                                   "SELECT 'bigint' AS sequence_type, "
16765                                                   "start_value, increment_by, max_value, min_value, "
16766                                                   "cache_value, is_cycled FROM %s",
16767                                                   fmtQualifiedDumpable(tbinfo));
16768         }
16769         else
16770         {
16771                 appendPQExpBuffer(query,
16772                                                   "SELECT 'bigint' AS sequence_type, "
16773                                                   "0 AS start_value, increment_by, max_value, min_value, "
16774                                                   "cache_value, is_cycled FROM %s",
16775                                                   fmtQualifiedDumpable(tbinfo));
16776         }
16777
16778         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
16779
16780         if (PQntuples(res) != 1)
16781         {
16782                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
16783                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
16784                                                                  PQntuples(res)),
16785                                   tbinfo->dobj.name, PQntuples(res));
16786                 exit_nicely(1);
16787         }
16788
16789         seqtype = PQgetvalue(res, 0, 0);
16790         startv = PQgetvalue(res, 0, 1);
16791         incby = PQgetvalue(res, 0, 2);
16792         maxv = PQgetvalue(res, 0, 3);
16793         minv = PQgetvalue(res, 0, 4);
16794         cache = PQgetvalue(res, 0, 5);
16795         cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
16796
16797         /* Calculate default limits for a sequence of this type */
16798         is_ascending = (incby[0] != '-');
16799         if (strcmp(seqtype, "smallint") == 0)
16800         {
16801                 default_minv = is_ascending ? 1 : PG_INT16_MIN;
16802                 default_maxv = is_ascending ? PG_INT16_MAX : -1;
16803         }
16804         else if (strcmp(seqtype, "integer") == 0)
16805         {
16806                 default_minv = is_ascending ? 1 : PG_INT32_MIN;
16807                 default_maxv = is_ascending ? PG_INT32_MAX : -1;
16808         }
16809         else if (strcmp(seqtype, "bigint") == 0)
16810         {
16811                 default_minv = is_ascending ? 1 : PG_INT64_MIN;
16812                 default_maxv = is_ascending ? PG_INT64_MAX : -1;
16813         }
16814         else
16815         {
16816                 exit_horribly(NULL, "unrecognized sequence type: %s\n", seqtype);
16817                 default_minv = default_maxv = 0;        /* keep compiler quiet */
16818         }
16819
16820         /*
16821          * 64-bit strtol() isn't very portable, so convert the limits to strings
16822          * and compare that way.
16823          */
16824         snprintf(bufm, sizeof(bufm), INT64_FORMAT, default_minv);
16825         snprintf(bufx, sizeof(bufx), INT64_FORMAT, default_maxv);
16826
16827         /* Don't print minv/maxv if they match the respective default limit */
16828         if (strcmp(minv, bufm) == 0)
16829                 minv = NULL;
16830         if (strcmp(maxv, bufx) == 0)
16831                 maxv = NULL;
16832
16833         /*
16834          * Identity sequences are not to be dropped separately.
16835          */
16836         if (!tbinfo->is_identity_sequence)
16837         {
16838                 appendPQExpBuffer(delqry, "DROP SEQUENCE %s;\n",
16839                                                   fmtQualifiedDumpable(tbinfo));
16840         }
16841
16842         resetPQExpBuffer(query);
16843
16844         if (dopt->binary_upgrade)
16845         {
16846                 binary_upgrade_set_pg_class_oids(fout, query,
16847                                                                                  tbinfo->dobj.catId.oid, false);
16848                 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
16849                                                                                                 tbinfo->dobj.catId.oid);
16850         }
16851
16852         if (tbinfo->is_identity_sequence)
16853         {
16854                 TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
16855
16856                 appendPQExpBuffer(query,
16857                                                   "ALTER TABLE %s ",
16858                                                   fmtQualifiedDumpable(owning_tab));
16859                 appendPQExpBuffer(query,
16860                                                   "ALTER COLUMN %s ADD GENERATED ",
16861                                                   fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16862                 if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_ALWAYS)
16863                         appendPQExpBuffer(query, "ALWAYS");
16864                 else if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_BY_DEFAULT)
16865                         appendPQExpBuffer(query, "BY DEFAULT");
16866                 appendPQExpBuffer(query, " AS IDENTITY (\n    SEQUENCE NAME %s\n",
16867                                                   fmtQualifiedDumpable(tbinfo));
16868         }
16869         else
16870         {
16871                 appendPQExpBuffer(query,
16872                                                   "CREATE SEQUENCE %s\n",
16873                                                   fmtQualifiedDumpable(tbinfo));
16874
16875                 if (strcmp(seqtype, "bigint") != 0)
16876                         appendPQExpBuffer(query, "    AS %s\n", seqtype);
16877         }
16878
16879         if (fout->remoteVersion >= 80400)
16880                 appendPQExpBuffer(query, "    START WITH %s\n", startv);
16881
16882         appendPQExpBuffer(query, "    INCREMENT BY %s\n", incby);
16883
16884         if (minv)
16885                 appendPQExpBuffer(query, "    MINVALUE %s\n", minv);
16886         else
16887                 appendPQExpBufferStr(query, "    NO MINVALUE\n");
16888
16889         if (maxv)
16890                 appendPQExpBuffer(query, "    MAXVALUE %s\n", maxv);
16891         else
16892                 appendPQExpBufferStr(query, "    NO MAXVALUE\n");
16893
16894         appendPQExpBuffer(query,
16895                                           "    CACHE %s%s",
16896                                           cache, (cycled ? "\n    CYCLE" : ""));
16897
16898         if (tbinfo->is_identity_sequence)
16899                 appendPQExpBufferStr(query, "\n);\n");
16900         else
16901                 appendPQExpBufferStr(query, ";\n");
16902
16903         /* binary_upgrade:      no need to clear TOAST table oid */
16904
16905         if (dopt->binary_upgrade)
16906                 binary_upgrade_extension_member(query, &tbinfo->dobj,
16907                                                                                 "SEQUENCE", qseqname,
16908                                                                                 tbinfo->dobj.namespace->dobj.name);
16909
16910         if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16911                 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
16912                                          tbinfo->dobj.name,
16913                                          tbinfo->dobj.namespace->dobj.name,
16914                                          NULL,
16915                                          tbinfo->rolname,
16916                                          false, "SEQUENCE", SECTION_PRE_DATA,
16917                                          query->data, delqry->data, NULL,
16918                                          NULL, 0,
16919                                          NULL, NULL);
16920
16921         /*
16922          * If the sequence is owned by a table column, emit the ALTER for it as a
16923          * separate TOC entry immediately following the sequence's own entry. It's
16924          * OK to do this rather than using full sorting logic, because the
16925          * dependency that tells us it's owned will have forced the table to be
16926          * created first.  We can't just include the ALTER in the TOC entry
16927          * because it will fail if we haven't reassigned the sequence owner to
16928          * match the table's owner.
16929          *
16930          * We need not schema-qualify the table reference because both sequence
16931          * and table must be in the same schema.
16932          */
16933         if (OidIsValid(tbinfo->owning_tab) && !tbinfo->is_identity_sequence)
16934         {
16935                 TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
16936
16937                 if (owning_tab == NULL)
16938                         exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
16939                                                   tbinfo->owning_tab, tbinfo->dobj.catId.oid);
16940
16941                 if (owning_tab->dobj.dump & DUMP_COMPONENT_DEFINITION)
16942                 {
16943                         resetPQExpBuffer(query);
16944                         appendPQExpBuffer(query, "ALTER SEQUENCE %s",
16945                                                           fmtQualifiedDumpable(tbinfo));
16946                         appendPQExpBuffer(query, " OWNED BY %s",
16947                                                           fmtQualifiedDumpable(owning_tab));
16948                         appendPQExpBuffer(query, ".%s;\n",
16949                                                           fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16950
16951                         if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16952                                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
16953                                                          tbinfo->dobj.name,
16954                                                          tbinfo->dobj.namespace->dobj.name,
16955                                                          NULL,
16956                                                          tbinfo->rolname,
16957                                                          false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
16958                                                          query->data, "", NULL,
16959                                                          &(tbinfo->dobj.dumpId), 1,
16960                                                          NULL, NULL);
16961                 }
16962         }
16963
16964         /* Dump Sequence Comments and Security Labels */
16965         if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16966                 dumpComment(fout, "SEQUENCE", qseqname,
16967                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16968                                         tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
16969
16970         if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16971                 dumpSecLabel(fout, "SEQUENCE", qseqname,
16972                                          tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16973                                          tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
16974
16975         PQclear(res);
16976
16977         destroyPQExpBuffer(query);
16978         destroyPQExpBuffer(delqry);
16979         free(qseqname);
16980 }
16981
16982 /*
16983  * dumpSequenceData
16984  *        write the data of one user-defined sequence
16985  */
16986 static void
16987 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
16988 {
16989         TableInfo  *tbinfo = tdinfo->tdtable;
16990         PGresult   *res;
16991         char       *last;
16992         bool            called;
16993         PQExpBuffer query = createPQExpBuffer();
16994
16995         appendPQExpBuffer(query,
16996                                           "SELECT last_value, is_called FROM %s",
16997                                           fmtQualifiedDumpable(tbinfo));
16998
16999         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17000
17001         if (PQntuples(res) != 1)
17002         {
17003                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
17004                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
17005                                                                  PQntuples(res)),
17006                                   tbinfo->dobj.name, PQntuples(res));
17007                 exit_nicely(1);
17008         }
17009
17010         last = PQgetvalue(res, 0, 0);
17011         called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
17012
17013         resetPQExpBuffer(query);
17014         appendPQExpBufferStr(query, "SELECT pg_catalog.setval(");
17015         appendStringLiteralAH(query, fmtQualifiedDumpable(tbinfo), fout);
17016         appendPQExpBuffer(query, ", %s, %s);\n",
17017                                           last, (called ? "true" : "false"));
17018
17019         if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
17020                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
17021                                          tbinfo->dobj.name,
17022                                          tbinfo->dobj.namespace->dobj.name,
17023                                          NULL,
17024                                          tbinfo->rolname,
17025                                          false, "SEQUENCE SET", SECTION_DATA,
17026                                          query->data, "", NULL,
17027                                          &(tbinfo->dobj.dumpId), 1,
17028                                          NULL, NULL);
17029
17030         PQclear(res);
17031
17032         destroyPQExpBuffer(query);
17033 }
17034
17035 /*
17036  * dumpTrigger
17037  *        write the declaration of one user-defined table trigger
17038  */
17039 static void
17040 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
17041 {
17042         DumpOptions *dopt = fout->dopt;
17043         TableInfo  *tbinfo = tginfo->tgtable;
17044         PQExpBuffer query;
17045         PQExpBuffer delqry;
17046         PQExpBuffer trigprefix;
17047         char       *qtabname;
17048         char       *tgargs;
17049         size_t          lentgargs;
17050         const char *p;
17051         int                     findx;
17052         char       *tag;
17053
17054         /*
17055          * we needn't check dobj.dump because TriggerInfo wouldn't have been
17056          * created in the first place for non-dumpable triggers
17057          */
17058         if (dopt->dataOnly)
17059                 return;
17060
17061         query = createPQExpBuffer();
17062         delqry = createPQExpBuffer();
17063         trigprefix = createPQExpBuffer();
17064
17065         qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
17066
17067         appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
17068                                           fmtId(tginfo->dobj.name));
17069         appendPQExpBuffer(delqry, "ON %s;\n",
17070                                           fmtQualifiedDumpable(tbinfo));
17071
17072         if (tginfo->tgdef)
17073         {
17074                 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
17075         }
17076         else
17077         {
17078                 if (tginfo->tgisconstraint)
17079                 {
17080                         appendPQExpBufferStr(query, "CREATE CONSTRAINT TRIGGER ");
17081                         appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
17082                 }
17083                 else
17084                 {
17085                         appendPQExpBufferStr(query, "CREATE TRIGGER ");
17086                         appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
17087                 }
17088                 appendPQExpBufferStr(query, "\n    ");
17089
17090                 /* Trigger type */
17091                 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
17092                         appendPQExpBufferStr(query, "BEFORE");
17093                 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
17094                         appendPQExpBufferStr(query, "AFTER");
17095                 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
17096                         appendPQExpBufferStr(query, "INSTEAD OF");
17097                 else
17098                 {
17099                         write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
17100                         exit_nicely(1);
17101                 }
17102
17103                 findx = 0;
17104                 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
17105                 {
17106                         appendPQExpBufferStr(query, " INSERT");
17107                         findx++;
17108                 }
17109                 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
17110                 {
17111                         if (findx > 0)
17112                                 appendPQExpBufferStr(query, " OR DELETE");
17113                         else
17114                                 appendPQExpBufferStr(query, " DELETE");
17115                         findx++;
17116                 }
17117                 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
17118                 {
17119                         if (findx > 0)
17120                                 appendPQExpBufferStr(query, " OR UPDATE");
17121                         else
17122                                 appendPQExpBufferStr(query, " UPDATE");
17123                         findx++;
17124                 }
17125                 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
17126                 {
17127                         if (findx > 0)
17128                                 appendPQExpBufferStr(query, " OR TRUNCATE");
17129                         else
17130                                 appendPQExpBufferStr(query, " TRUNCATE");
17131                         findx++;
17132                 }
17133                 appendPQExpBuffer(query, " ON %s\n",
17134                                                   fmtQualifiedDumpable(tbinfo));
17135
17136                 if (tginfo->tgisconstraint)
17137                 {
17138                         if (OidIsValid(tginfo->tgconstrrelid))
17139                         {
17140                                 /* regclass output is already quoted */
17141                                 appendPQExpBuffer(query, "    FROM %s\n    ",
17142                                                                   tginfo->tgconstrrelname);
17143                         }
17144                         if (!tginfo->tgdeferrable)
17145                                 appendPQExpBufferStr(query, "NOT ");
17146                         appendPQExpBufferStr(query, "DEFERRABLE INITIALLY ");
17147                         if (tginfo->tginitdeferred)
17148                                 appendPQExpBufferStr(query, "DEFERRED\n");
17149                         else
17150                                 appendPQExpBufferStr(query, "IMMEDIATE\n");
17151                 }
17152
17153                 if (TRIGGER_FOR_ROW(tginfo->tgtype))
17154                         appendPQExpBufferStr(query, "    FOR EACH ROW\n    ");
17155                 else
17156                         appendPQExpBufferStr(query, "    FOR EACH STATEMENT\n    ");
17157
17158                 /* regproc output is already sufficiently quoted */
17159                 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
17160                                                   tginfo->tgfname);
17161
17162                 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
17163                                                                                   &lentgargs);
17164                 p = tgargs;
17165                 for (findx = 0; findx < tginfo->tgnargs; findx++)
17166                 {
17167                         /* find the embedded null that terminates this trigger argument */
17168                         size_t          tlen = strlen(p);
17169
17170                         if (p + tlen >= tgargs + lentgargs)
17171                         {
17172                                 /* hm, not found before end of bytea value... */
17173                                 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
17174                                                   tginfo->tgargs,
17175                                                   tginfo->dobj.name,
17176                                                   tbinfo->dobj.name);
17177                                 exit_nicely(1);
17178                         }
17179
17180                         if (findx > 0)
17181                                 appendPQExpBufferStr(query, ", ");
17182                         appendStringLiteralAH(query, p, fout);
17183                         p += tlen + 1;
17184                 }
17185                 free(tgargs);
17186                 appendPQExpBufferStr(query, ");\n");
17187         }
17188
17189         if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
17190         {
17191                 appendPQExpBuffer(query, "\nALTER TABLE %s ",
17192                                                   fmtQualifiedDumpable(tbinfo));
17193                 switch (tginfo->tgenabled)
17194                 {
17195                         case 'D':
17196                         case 'f':
17197                                 appendPQExpBufferStr(query, "DISABLE");
17198                                 break;
17199                         case 'A':
17200                                 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17201                                 break;
17202                         case 'R':
17203                                 appendPQExpBufferStr(query, "ENABLE REPLICA");
17204                                 break;
17205                         default:
17206                                 appendPQExpBufferStr(query, "ENABLE");
17207                                 break;
17208                 }
17209                 appendPQExpBuffer(query, " TRIGGER %s;\n",
17210                                                   fmtId(tginfo->dobj.name));
17211         }
17212
17213         appendPQExpBuffer(trigprefix, "TRIGGER %s ON",
17214                                           fmtId(tginfo->dobj.name));
17215
17216         tag = psprintf("%s %s", tbinfo->dobj.name, tginfo->dobj.name);
17217
17218         if (tginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17219                 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
17220                                          tag,
17221                                          tbinfo->dobj.namespace->dobj.name,
17222                                          NULL,
17223                                          tbinfo->rolname, false,
17224                                          "TRIGGER", SECTION_POST_DATA,
17225                                          query->data, delqry->data, NULL,
17226                                          NULL, 0,
17227                                          NULL, NULL);
17228
17229         if (tginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17230                 dumpComment(fout, trigprefix->data, qtabname,
17231                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17232                                         tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
17233
17234         free(tag);
17235         destroyPQExpBuffer(query);
17236         destroyPQExpBuffer(delqry);
17237         destroyPQExpBuffer(trigprefix);
17238         free(qtabname);
17239 }
17240
17241 /*
17242  * dumpEventTrigger
17243  *        write the declaration of one user-defined event trigger
17244  */
17245 static void
17246 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
17247 {
17248         DumpOptions *dopt = fout->dopt;
17249         PQExpBuffer query;
17250         PQExpBuffer delqry;
17251         char       *qevtname;
17252
17253         /* Skip if not to be dumped */
17254         if (!evtinfo->dobj.dump || dopt->dataOnly)
17255                 return;
17256
17257         query = createPQExpBuffer();
17258         delqry = createPQExpBuffer();
17259
17260         qevtname = pg_strdup(fmtId(evtinfo->dobj.name));
17261
17262         appendPQExpBufferStr(query, "CREATE EVENT TRIGGER ");
17263         appendPQExpBufferStr(query, qevtname);
17264         appendPQExpBufferStr(query, " ON ");
17265         appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
17266
17267         if (strcmp("", evtinfo->evttags) != 0)
17268         {
17269                 appendPQExpBufferStr(query, "\n         WHEN TAG IN (");
17270                 appendPQExpBufferStr(query, evtinfo->evttags);
17271                 appendPQExpBufferChar(query, ')');
17272         }
17273
17274         appendPQExpBufferStr(query, "\n   EXECUTE PROCEDURE ");
17275         appendPQExpBufferStr(query, evtinfo->evtfname);
17276         appendPQExpBufferStr(query, "();\n");
17277
17278         if (evtinfo->evtenabled != 'O')
17279         {
17280                 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
17281                                                   qevtname);
17282                 switch (evtinfo->evtenabled)
17283                 {
17284                         case 'D':
17285                                 appendPQExpBufferStr(query, "DISABLE");
17286                                 break;
17287                         case 'A':
17288                                 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17289                                 break;
17290                         case 'R':
17291                                 appendPQExpBufferStr(query, "ENABLE REPLICA");
17292                                 break;
17293                         default:
17294                                 appendPQExpBufferStr(query, "ENABLE");
17295                                 break;
17296                 }
17297                 appendPQExpBufferStr(query, ";\n");
17298         }
17299
17300         appendPQExpBuffer(delqry, "DROP EVENT TRIGGER %s;\n",
17301                                           qevtname);
17302
17303         if (dopt->binary_upgrade)
17304                 binary_upgrade_extension_member(query, &evtinfo->dobj,
17305                                                                                 "EVENT TRIGGER", qevtname, NULL);
17306
17307         if (evtinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17308                 ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
17309                                          evtinfo->dobj.name, NULL, NULL,
17310                                          evtinfo->evtowner, false,
17311                                          "EVENT TRIGGER", SECTION_POST_DATA,
17312                                          query->data, delqry->data, NULL,
17313                                          NULL, 0,
17314                                          NULL, NULL);
17315
17316         if (evtinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17317                 dumpComment(fout, "EVENT TRIGGER", qevtname,
17318                                         NULL, evtinfo->evtowner,
17319                                         evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
17320
17321         destroyPQExpBuffer(query);
17322         destroyPQExpBuffer(delqry);
17323         free(qevtname);
17324 }
17325
17326 /*
17327  * dumpRule
17328  *              Dump a rule
17329  */
17330 static void
17331 dumpRule(Archive *fout, RuleInfo *rinfo)
17332 {
17333         DumpOptions *dopt = fout->dopt;
17334         TableInfo  *tbinfo = rinfo->ruletable;
17335         bool            is_view;
17336         PQExpBuffer query;
17337         PQExpBuffer cmd;
17338         PQExpBuffer delcmd;
17339         PQExpBuffer ruleprefix;
17340         char       *qtabname;
17341         PGresult   *res;
17342         char       *tag;
17343
17344         /* Skip if not to be dumped */
17345         if (!rinfo->dobj.dump || dopt->dataOnly)
17346                 return;
17347
17348         /*
17349          * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
17350          * we do not want to dump it as a separate object.
17351          */
17352         if (!rinfo->separate)
17353                 return;
17354
17355         /*
17356          * If it's an ON SELECT rule, we want to print it as a view definition,
17357          * instead of a rule.
17358          */
17359         is_view = (rinfo->ev_type == '1' && rinfo->is_instead);
17360
17361         query = createPQExpBuffer();
17362         cmd = createPQExpBuffer();
17363         delcmd = createPQExpBuffer();
17364         ruleprefix = createPQExpBuffer();
17365
17366         qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
17367
17368         if (is_view)
17369         {
17370                 PQExpBuffer result;
17371
17372                 /*
17373                  * We need OR REPLACE here because we'll be replacing a dummy view.
17374                  * Otherwise this should look largely like the regular view dump code.
17375                  */
17376                 appendPQExpBuffer(cmd, "CREATE OR REPLACE VIEW %s",
17377                                                   fmtQualifiedDumpable(tbinfo));
17378                 if (nonemptyReloptions(tbinfo->reloptions))
17379                 {
17380                         appendPQExpBufferStr(cmd, " WITH (");
17381                         appendReloptionsArrayAH(cmd, tbinfo->reloptions, "", fout);
17382                         appendPQExpBufferChar(cmd, ')');
17383                 }
17384                 result = createViewAsClause(fout, tbinfo);
17385                 appendPQExpBuffer(cmd, " AS\n%s", result->data);
17386                 destroyPQExpBuffer(result);
17387                 if (tbinfo->checkoption != NULL)
17388                         appendPQExpBuffer(cmd, "\n  WITH %s CHECK OPTION",
17389                                                           tbinfo->checkoption);
17390                 appendPQExpBufferStr(cmd, ";\n");
17391         }
17392         else
17393         {
17394                 /* In the rule case, just print pg_get_ruledef's result verbatim */
17395                 appendPQExpBuffer(query,
17396                                                   "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid)",
17397                                                   rinfo->dobj.catId.oid);
17398
17399                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17400
17401                 if (PQntuples(res) != 1)
17402                 {
17403                         write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
17404                                           rinfo->dobj.name, tbinfo->dobj.name);
17405                         exit_nicely(1);
17406                 }
17407
17408                 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
17409
17410                 PQclear(res);
17411         }
17412
17413         /*
17414          * Add the command to alter the rules replication firing semantics if it
17415          * differs from the default.
17416          */
17417         if (rinfo->ev_enabled != 'O')
17418         {
17419                 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtQualifiedDumpable(tbinfo));
17420                 switch (rinfo->ev_enabled)
17421                 {
17422                         case 'A':
17423                                 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
17424                                                                   fmtId(rinfo->dobj.name));
17425                                 break;
17426                         case 'R':
17427                                 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
17428                                                                   fmtId(rinfo->dobj.name));
17429                                 break;
17430                         case 'D':
17431                                 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
17432                                                                   fmtId(rinfo->dobj.name));
17433                                 break;
17434                 }
17435         }
17436
17437         if (is_view)
17438         {
17439                 /*
17440                  * We can't DROP a view's ON SELECT rule.  Instead, use CREATE OR
17441                  * REPLACE VIEW to replace the rule with something with minimal
17442                  * dependencies.
17443                  */
17444                 PQExpBuffer result;
17445
17446                 appendPQExpBuffer(delcmd, "CREATE OR REPLACE VIEW %s",
17447                                                   fmtQualifiedDumpable(tbinfo));
17448                 result = createDummyViewAsClause(fout, tbinfo);
17449                 appendPQExpBuffer(delcmd, " AS\n%s;\n", result->data);
17450                 destroyPQExpBuffer(result);
17451         }
17452         else
17453         {
17454                 appendPQExpBuffer(delcmd, "DROP RULE %s ",
17455                                                   fmtId(rinfo->dobj.name));
17456                 appendPQExpBuffer(delcmd, "ON %s;\n",
17457                                                   fmtQualifiedDumpable(tbinfo));
17458         }
17459
17460         appendPQExpBuffer(ruleprefix, "RULE %s ON",
17461                                           fmtId(rinfo->dobj.name));
17462
17463         tag = psprintf("%s %s", tbinfo->dobj.name, rinfo->dobj.name);
17464
17465         if (rinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17466                 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
17467                                          tag,
17468                                          tbinfo->dobj.namespace->dobj.name,
17469                                          NULL,
17470                                          tbinfo->rolname, false,
17471                                          "RULE", SECTION_POST_DATA,
17472                                          cmd->data, delcmd->data, NULL,
17473                                          NULL, 0,
17474                                          NULL, NULL);
17475
17476         /* Dump rule comments */
17477         if (rinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17478                 dumpComment(fout, ruleprefix->data, qtabname,
17479                                         tbinfo->dobj.namespace->dobj.name,
17480                                         tbinfo->rolname,
17481                                         rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
17482
17483         free(tag);
17484         destroyPQExpBuffer(query);
17485         destroyPQExpBuffer(cmd);
17486         destroyPQExpBuffer(delcmd);
17487         destroyPQExpBuffer(ruleprefix);
17488         free(qtabname);
17489 }
17490
17491 /*
17492  * getExtensionMembership --- obtain extension membership data
17493  *
17494  * We need to identify objects that are extension members as soon as they're
17495  * loaded, so that we can correctly determine whether they need to be dumped.
17496  * Generally speaking, extension member objects will get marked as *not* to
17497  * be dumped, as they will be recreated by the single CREATE EXTENSION
17498  * command.  However, in binary upgrade mode we still need to dump the members
17499  * individually.
17500  */
17501 void
17502 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
17503                                            int numExtensions)
17504 {
17505         PQExpBuffer query;
17506         PGresult   *res;
17507         int                     ntups,
17508                                 nextmembers,
17509                                 i;
17510         int                     i_classid,
17511                                 i_objid,
17512                                 i_refobjid;
17513         ExtensionMemberId *extmembers;
17514         ExtensionInfo *ext;
17515
17516         /* Nothing to do if no extensions */
17517         if (numExtensions == 0)
17518                 return;
17519
17520         query = createPQExpBuffer();
17521
17522         /* refclassid constraint is redundant but may speed the search */
17523         appendPQExpBufferStr(query, "SELECT "
17524                                                  "classid, objid, refobjid "
17525                                                  "FROM pg_depend "
17526                                                  "WHERE refclassid = 'pg_extension'::regclass "
17527                                                  "AND deptype = 'e' "
17528                                                  "ORDER BY 3");
17529
17530         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17531
17532         ntups = PQntuples(res);
17533
17534         i_classid = PQfnumber(res, "classid");
17535         i_objid = PQfnumber(res, "objid");
17536         i_refobjid = PQfnumber(res, "refobjid");
17537
17538         extmembers = (ExtensionMemberId *) pg_malloc(ntups * sizeof(ExtensionMemberId));
17539         nextmembers = 0;
17540
17541         /*
17542          * Accumulate data into extmembers[].
17543          *
17544          * Since we ordered the SELECT by referenced ID, we can expect that
17545          * multiple entries for the same extension will appear together; this
17546          * saves on searches.
17547          */
17548         ext = NULL;
17549
17550         for (i = 0; i < ntups; i++)
17551         {
17552                 CatalogId       objId;
17553                 Oid                     extId;
17554
17555                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17556                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17557                 extId = atooid(PQgetvalue(res, i, i_refobjid));
17558
17559                 if (ext == NULL ||
17560                         ext->dobj.catId.oid != extId)
17561                         ext = findExtensionByOid(extId);
17562
17563                 if (ext == NULL)
17564                 {
17565                         /* shouldn't happen */
17566                         fprintf(stderr, "could not find referenced extension %u\n", extId);
17567                         continue;
17568                 }
17569
17570                 extmembers[nextmembers].catId = objId;
17571                 extmembers[nextmembers].ext = ext;
17572                 nextmembers++;
17573         }
17574
17575         PQclear(res);
17576
17577         /* Remember the data for use later */
17578         setExtensionMembership(extmembers, nextmembers);
17579
17580         destroyPQExpBuffer(query);
17581 }
17582
17583 /*
17584  * processExtensionTables --- deal with extension configuration tables
17585  *
17586  * There are two parts to this process:
17587  *
17588  * 1. Identify and create dump records for extension configuration tables.
17589  *
17590  *        Extensions can mark tables as "configuration", which means that the user
17591  *        is able and expected to modify those tables after the extension has been
17592  *        loaded.  For these tables, we dump out only the data- the structure is
17593  *        expected to be handled at CREATE EXTENSION time, including any indexes or
17594  *        foreign keys, which brings us to-
17595  *
17596  * 2. Record FK dependencies between configuration tables.
17597  *
17598  *        Due to the FKs being created at CREATE EXTENSION time and therefore before
17599  *        the data is loaded, we have to work out what the best order for reloading
17600  *        the data is, to avoid FK violations when the tables are restored.  This is
17601  *        not perfect- we can't handle circular dependencies and if any exist they
17602  *        will cause an invalid dump to be produced (though at least all of the data
17603  *        is included for a user to manually restore).  This is currently documented
17604  *        but perhaps we can provide a better solution in the future.
17605  */
17606 void
17607 processExtensionTables(Archive *fout, ExtensionInfo extinfo[],
17608                                            int numExtensions)
17609 {
17610         DumpOptions *dopt = fout->dopt;
17611         PQExpBuffer query;
17612         PGresult   *res;
17613         int                     ntups,
17614                                 i;
17615         int                     i_conrelid,
17616                                 i_confrelid;
17617
17618         /* Nothing to do if no extensions */
17619         if (numExtensions == 0)
17620                 return;
17621
17622         /*
17623          * Identify extension configuration tables and create TableDataInfo
17624          * objects for them, ensuring their data will be dumped even though the
17625          * tables themselves won't be.
17626          *
17627          * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
17628          * user data in a configuration table is treated like schema data. This
17629          * seems appropriate since system data in a config table would get
17630          * reloaded by CREATE EXTENSION.
17631          */
17632         for (i = 0; i < numExtensions; i++)
17633         {
17634                 ExtensionInfo *curext = &(extinfo[i]);
17635                 char       *extconfig = curext->extconfig;
17636                 char       *extcondition = curext->extcondition;
17637                 char      **extconfigarray = NULL;
17638                 char      **extconditionarray = NULL;
17639                 int                     nconfigitems;
17640                 int                     nconditionitems;
17641
17642                 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
17643                         parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
17644                         nconfigitems == nconditionitems)
17645                 {
17646                         int                     j;
17647
17648                         for (j = 0; j < nconfigitems; j++)
17649                         {
17650                                 TableInfo  *configtbl;
17651                                 Oid                     configtbloid = atooid(extconfigarray[j]);
17652                                 bool            dumpobj =
17653                                 curext->dobj.dump & DUMP_COMPONENT_DEFINITION;
17654
17655                                 configtbl = findTableByOid(configtbloid);
17656                                 if (configtbl == NULL)
17657                                         continue;
17658
17659                                 /*
17660                                  * Tables of not-to-be-dumped extensions shouldn't be dumped
17661                                  * unless the table or its schema is explicitly included
17662                                  */
17663                                 if (!(curext->dobj.dump & DUMP_COMPONENT_DEFINITION))
17664                                 {
17665                                         /* check table explicitly requested */
17666                                         if (table_include_oids.head != NULL &&
17667                                                 simple_oid_list_member(&table_include_oids,
17668                                                                                            configtbloid))
17669                                                 dumpobj = true;
17670
17671                                         /* check table's schema explicitly requested */
17672                                         if (configtbl->dobj.namespace->dobj.dump &
17673                                                 DUMP_COMPONENT_DATA)
17674                                                 dumpobj = true;
17675                                 }
17676
17677                                 /* check table excluded by an exclusion switch */
17678                                 if (table_exclude_oids.head != NULL &&
17679                                         simple_oid_list_member(&table_exclude_oids,
17680                                                                                    configtbloid))
17681                                         dumpobj = false;
17682
17683                                 /* check schema excluded by an exclusion switch */
17684                                 if (simple_oid_list_member(&schema_exclude_oids,
17685                                                                                    configtbl->dobj.namespace->dobj.catId.oid))
17686                                         dumpobj = false;
17687
17688                                 if (dumpobj)
17689                                 {
17690                                         /*
17691                                          * Note: config tables are dumped without OIDs regardless
17692                                          * of the --oids setting.  This is because row filtering
17693                                          * conditions aren't compatible with dumping OIDs.
17694                                          */
17695                                         makeTableDataInfo(dopt, configtbl, false);
17696                                         if (configtbl->dataObj != NULL)
17697                                         {
17698                                                 if (strlen(extconditionarray[j]) > 0)
17699                                                         configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
17700                                         }
17701                                 }
17702                         }
17703                 }
17704                 if (extconfigarray)
17705                         free(extconfigarray);
17706                 if (extconditionarray)
17707                         free(extconditionarray);
17708         }
17709
17710         /*
17711          * Now that all the TableInfoData objects have been created for all the
17712          * extensions, check their FK dependencies and register them to try and
17713          * dump the data out in an order that they can be restored in.
17714          *
17715          * Note that this is not a problem for user tables as their FKs are
17716          * recreated after the data has been loaded.
17717          */
17718
17719         query = createPQExpBuffer();
17720
17721         printfPQExpBuffer(query,
17722                                           "SELECT conrelid, confrelid "
17723                                           "FROM pg_constraint "
17724                                           "JOIN pg_depend ON (objid = confrelid) "
17725                                           "WHERE contype = 'f' "
17726                                           "AND refclassid = 'pg_extension'::regclass "
17727                                           "AND classid = 'pg_class'::regclass;");
17728
17729         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17730         ntups = PQntuples(res);
17731
17732         i_conrelid = PQfnumber(res, "conrelid");
17733         i_confrelid = PQfnumber(res, "confrelid");
17734
17735         /* Now get the dependencies and register them */
17736         for (i = 0; i < ntups; i++)
17737         {
17738                 Oid                     conrelid,
17739                                         confrelid;
17740                 TableInfo  *reftable,
17741                                    *contable;
17742
17743                 conrelid = atooid(PQgetvalue(res, i, i_conrelid));
17744                 confrelid = atooid(PQgetvalue(res, i, i_confrelid));
17745                 contable = findTableByOid(conrelid);
17746                 reftable = findTableByOid(confrelid);
17747
17748                 if (reftable == NULL ||
17749                         reftable->dataObj == NULL ||
17750                         contable == NULL ||
17751                         contable->dataObj == NULL)
17752                         continue;
17753
17754                 /*
17755                  * Make referencing TABLE_DATA object depend on the referenced table's
17756                  * TABLE_DATA object.
17757                  */
17758                 addObjectDependency(&contable->dataObj->dobj,
17759                                                         reftable->dataObj->dobj.dumpId);
17760         }
17761         PQclear(res);
17762         destroyPQExpBuffer(query);
17763 }
17764
17765 /*
17766  * getDependencies --- obtain available dependency data
17767  */
17768 static void
17769 getDependencies(Archive *fout)
17770 {
17771         PQExpBuffer query;
17772         PGresult   *res;
17773         int                     ntups,
17774                                 i;
17775         int                     i_classid,
17776                                 i_objid,
17777                                 i_refclassid,
17778                                 i_refobjid,
17779                                 i_deptype;
17780         DumpableObject *dobj,
17781                            *refdobj;
17782
17783         if (g_verbose)
17784                 write_msg(NULL, "reading dependency data\n");
17785
17786         query = createPQExpBuffer();
17787
17788         /*
17789          * PIN dependencies aren't interesting, and EXTENSION dependencies were
17790          * already processed by getExtensionMembership.
17791          */
17792         appendPQExpBufferStr(query, "SELECT "
17793                                                  "classid, objid, refclassid, refobjid, deptype "
17794                                                  "FROM pg_depend "
17795                                                  "WHERE deptype != 'p' AND deptype != 'e' "
17796                                                  "ORDER BY 1,2");
17797
17798         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17799
17800         ntups = PQntuples(res);
17801
17802         i_classid = PQfnumber(res, "classid");
17803         i_objid = PQfnumber(res, "objid");
17804         i_refclassid = PQfnumber(res, "refclassid");
17805         i_refobjid = PQfnumber(res, "refobjid");
17806         i_deptype = PQfnumber(res, "deptype");
17807
17808         /*
17809          * Since we ordered the SELECT by referencing ID, we can expect that
17810          * multiple entries for the same object will appear together; this saves
17811          * on searches.
17812          */
17813         dobj = NULL;
17814
17815         for (i = 0; i < ntups; i++)
17816         {
17817                 CatalogId       objId;
17818                 CatalogId       refobjId;
17819                 char            deptype;
17820
17821                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17822                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17823                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
17824                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
17825                 deptype = *(PQgetvalue(res, i, i_deptype));
17826
17827                 if (dobj == NULL ||
17828                         dobj->catId.tableoid != objId.tableoid ||
17829                         dobj->catId.oid != objId.oid)
17830                         dobj = findObjectByCatalogId(objId);
17831
17832                 /*
17833                  * Failure to find objects mentioned in pg_depend is not unexpected,
17834                  * since for example we don't collect info about TOAST tables.
17835                  */
17836                 if (dobj == NULL)
17837                 {
17838 #ifdef NOT_USED
17839                         fprintf(stderr, "no referencing object %u %u\n",
17840                                         objId.tableoid, objId.oid);
17841 #endif
17842                         continue;
17843                 }
17844
17845                 refdobj = findObjectByCatalogId(refobjId);
17846
17847                 if (refdobj == NULL)
17848                 {
17849 #ifdef NOT_USED
17850                         fprintf(stderr, "no referenced object %u %u\n",
17851                                         refobjId.tableoid, refobjId.oid);
17852 #endif
17853                         continue;
17854                 }
17855
17856                 /*
17857                  * Ordinarily, table rowtypes have implicit dependencies on their
17858                  * tables.  However, for a composite type the implicit dependency goes
17859                  * the other way in pg_depend; which is the right thing for DROP but
17860                  * it doesn't produce the dependency ordering we need. So in that one
17861                  * case, we reverse the direction of the dependency.
17862                  */
17863                 if (deptype == 'i' &&
17864                         dobj->objType == DO_TABLE &&
17865                         refdobj->objType == DO_TYPE)
17866                         addObjectDependency(refdobj, dobj->dumpId);
17867                 else
17868                         /* normal case */
17869                         addObjectDependency(dobj, refdobj->dumpId);
17870         }
17871
17872         PQclear(res);
17873
17874         destroyPQExpBuffer(query);
17875 }
17876
17877
17878 /*
17879  * createBoundaryObjects - create dummy DumpableObjects to represent
17880  * dump section boundaries.
17881  */
17882 static DumpableObject *
17883 createBoundaryObjects(void)
17884 {
17885         DumpableObject *dobjs;
17886
17887         dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
17888
17889         dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
17890         dobjs[0].catId = nilCatalogId;
17891         AssignDumpId(dobjs + 0);
17892         dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
17893
17894         dobjs[1].objType = DO_POST_DATA_BOUNDARY;
17895         dobjs[1].catId = nilCatalogId;
17896         AssignDumpId(dobjs + 1);
17897         dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
17898
17899         return dobjs;
17900 }
17901
17902 /*
17903  * addBoundaryDependencies - add dependencies as needed to enforce the dump
17904  * section boundaries.
17905  */
17906 static void
17907 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
17908                                                 DumpableObject *boundaryObjs)
17909 {
17910         DumpableObject *preDataBound = boundaryObjs + 0;
17911         DumpableObject *postDataBound = boundaryObjs + 1;
17912         int                     i;
17913
17914         for (i = 0; i < numObjs; i++)
17915         {
17916                 DumpableObject *dobj = dobjs[i];
17917
17918                 /*
17919                  * The classification of object types here must match the SECTION_xxx
17920                  * values assigned during subsequent ArchiveEntry calls!
17921                  */
17922                 switch (dobj->objType)
17923                 {
17924                         case DO_NAMESPACE:
17925                         case DO_EXTENSION:
17926                         case DO_TYPE:
17927                         case DO_SHELL_TYPE:
17928                         case DO_FUNC:
17929                         case DO_AGG:
17930                         case DO_OPERATOR:
17931                         case DO_ACCESS_METHOD:
17932                         case DO_OPCLASS:
17933                         case DO_OPFAMILY:
17934                         case DO_COLLATION:
17935                         case DO_CONVERSION:
17936                         case DO_TABLE:
17937                         case DO_ATTRDEF:
17938                         case DO_PROCLANG:
17939                         case DO_CAST:
17940                         case DO_DUMMY_TYPE:
17941                         case DO_TSPARSER:
17942                         case DO_TSDICT:
17943                         case DO_TSTEMPLATE:
17944                         case DO_TSCONFIG:
17945                         case DO_FDW:
17946                         case DO_FOREIGN_SERVER:
17947                         case DO_TRANSFORM:
17948                         case DO_BLOB:
17949                                 /* Pre-data objects: must come before the pre-data boundary */
17950                                 addObjectDependency(preDataBound, dobj->dumpId);
17951                                 break;
17952                         case DO_TABLE_DATA:
17953                         case DO_SEQUENCE_SET:
17954                         case DO_BLOB_DATA:
17955                                 /* Data objects: must come between the boundaries */
17956                                 addObjectDependency(dobj, preDataBound->dumpId);
17957                                 addObjectDependency(postDataBound, dobj->dumpId);
17958                                 break;
17959                         case DO_INDEX:
17960                         case DO_INDEX_ATTACH:
17961                         case DO_STATSEXT:
17962                         case DO_REFRESH_MATVIEW:
17963                         case DO_TRIGGER:
17964                         case DO_EVENT_TRIGGER:
17965                         case DO_DEFAULT_ACL:
17966                         case DO_POLICY:
17967                         case DO_PUBLICATION:
17968                         case DO_PUBLICATION_REL:
17969                         case DO_SUBSCRIPTION:
17970                                 /* Post-data objects: must come after the post-data boundary */
17971                                 addObjectDependency(dobj, postDataBound->dumpId);
17972                                 break;
17973                         case DO_RULE:
17974                                 /* Rules are post-data, but only if dumped separately */
17975                                 if (((RuleInfo *) dobj)->separate)
17976                                         addObjectDependency(dobj, postDataBound->dumpId);
17977                                 break;
17978                         case DO_CONSTRAINT:
17979                         case DO_FK_CONSTRAINT:
17980                                 /* Constraints are post-data, but only if dumped separately */
17981                                 if (((ConstraintInfo *) dobj)->separate)
17982                                         addObjectDependency(dobj, postDataBound->dumpId);
17983                                 break;
17984                         case DO_PRE_DATA_BOUNDARY:
17985                                 /* nothing to do */
17986                                 break;
17987                         case DO_POST_DATA_BOUNDARY:
17988                                 /* must come after the pre-data boundary */
17989                                 addObjectDependency(dobj, preDataBound->dumpId);
17990                                 break;
17991                 }
17992         }
17993 }
17994
17995
17996 /*
17997  * BuildArchiveDependencies - create dependency data for archive TOC entries
17998  *
17999  * The raw dependency data obtained by getDependencies() is not terribly
18000  * useful in an archive dump, because in many cases there are dependency
18001  * chains linking through objects that don't appear explicitly in the dump.
18002  * For example, a view will depend on its _RETURN rule while the _RETURN rule
18003  * will depend on other objects --- but the rule will not appear as a separate
18004  * object in the dump.  We need to adjust the view's dependencies to include
18005  * whatever the rule depends on that is included in the dump.
18006  *
18007  * Just to make things more complicated, there are also "special" dependencies
18008  * such as the dependency of a TABLE DATA item on its TABLE, which we must
18009  * not rearrange because pg_restore knows that TABLE DATA only depends on
18010  * its table.  In these cases we must leave the dependencies strictly as-is
18011  * even if they refer to not-to-be-dumped objects.
18012  *
18013  * To handle this, the convention is that "special" dependencies are created
18014  * during ArchiveEntry calls, and an archive TOC item that has any such
18015  * entries will not be touched here.  Otherwise, we recursively search the
18016  * DumpableObject data structures to build the correct dependencies for each
18017  * archive TOC item.
18018  */
18019 static void
18020 BuildArchiveDependencies(Archive *fout)
18021 {
18022         ArchiveHandle *AH = (ArchiveHandle *) fout;
18023         TocEntry   *te;
18024
18025         /* Scan all TOC entries in the archive */
18026         for (te = AH->toc->next; te != AH->toc; te = te->next)
18027         {
18028                 DumpableObject *dobj;
18029                 DumpId     *dependencies;
18030                 int                     nDeps;
18031                 int                     allocDeps;
18032
18033                 /* No need to process entries that will not be dumped */
18034                 if (te->reqs == 0)
18035                         continue;
18036                 /* Ignore entries that already have "special" dependencies */
18037                 if (te->nDeps > 0)
18038                         continue;
18039                 /* Otherwise, look up the item's original DumpableObject, if any */
18040                 dobj = findObjectByDumpId(te->dumpId);
18041                 if (dobj == NULL)
18042                         continue;
18043                 /* No work if it has no dependencies */
18044                 if (dobj->nDeps <= 0)
18045                         continue;
18046                 /* Set up work array */
18047                 allocDeps = 64;
18048                 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
18049                 nDeps = 0;
18050                 /* Recursively find all dumpable dependencies */
18051                 findDumpableDependencies(AH, dobj,
18052                                                                  &dependencies, &nDeps, &allocDeps);
18053                 /* And save 'em ... */
18054                 if (nDeps > 0)
18055                 {
18056                         dependencies = (DumpId *) pg_realloc(dependencies,
18057                                                                                                  nDeps * sizeof(DumpId));
18058                         te->dependencies = dependencies;
18059                         te->nDeps = nDeps;
18060                 }
18061                 else
18062                         free(dependencies);
18063         }
18064 }
18065
18066 /* Recursive search subroutine for BuildArchiveDependencies */
18067 static void
18068 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
18069                                                  DumpId **dependencies, int *nDeps, int *allocDeps)
18070 {
18071         int                     i;
18072
18073         /*
18074          * Ignore section boundary objects: if we search through them, we'll
18075          * report lots of bogus dependencies.
18076          */
18077         if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
18078                 dobj->objType == DO_POST_DATA_BOUNDARY)
18079                 return;
18080
18081         for (i = 0; i < dobj->nDeps; i++)
18082         {
18083                 DumpId          depid = dobj->dependencies[i];
18084
18085                 if (TocIDRequired(AH, depid) != 0)
18086                 {
18087                         /* Object will be dumped, so just reference it as a dependency */
18088                         if (*nDeps >= *allocDeps)
18089                         {
18090                                 *allocDeps *= 2;
18091                                 *dependencies = (DumpId *) pg_realloc(*dependencies,
18092                                                                                                           *allocDeps * sizeof(DumpId));
18093                         }
18094                         (*dependencies)[*nDeps] = depid;
18095                         (*nDeps)++;
18096                 }
18097                 else
18098                 {
18099                         /*
18100                          * Object will not be dumped, so recursively consider its deps. We
18101                          * rely on the assumption that sortDumpableObjects already broke
18102                          * any dependency loops, else we might recurse infinitely.
18103                          */
18104                         DumpableObject *otherdobj = findObjectByDumpId(depid);
18105
18106                         if (otherdobj)
18107                                 findDumpableDependencies(AH, otherdobj,
18108                                                                                  dependencies, nDeps, allocDeps);
18109                 }
18110         }
18111 }
18112
18113
18114 /*
18115  * getFormattedTypeName - retrieve a nicely-formatted type name for the
18116  * given type OID.
18117  *
18118  * This does not guarantee to schema-qualify the output, so it should not
18119  * be used to create the target object name for CREATE or ALTER commands.
18120  *
18121  * TODO: there might be some value in caching the results.
18122  */
18123 static char *
18124 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
18125 {
18126         char       *result;
18127         PQExpBuffer query;
18128         PGresult   *res;
18129
18130         if (oid == 0)
18131         {
18132                 if ((opts & zeroAsOpaque) != 0)
18133                         return pg_strdup(g_opaque_type);
18134                 else if ((opts & zeroAsAny) != 0)
18135                         return pg_strdup("'any'");
18136                 else if ((opts & zeroAsStar) != 0)
18137                         return pg_strdup("*");
18138                 else if ((opts & zeroAsNone) != 0)
18139                         return pg_strdup("NONE");
18140         }
18141
18142         query = createPQExpBuffer();
18143         appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
18144                                           oid);
18145
18146         res = ExecuteSqlQueryForSingleRow(fout, query->data);
18147
18148         /* result of format_type is already quoted */
18149         result = pg_strdup(PQgetvalue(res, 0, 0));
18150
18151         PQclear(res);
18152         destroyPQExpBuffer(query);
18153
18154         return result;
18155 }
18156
18157 /*
18158  * Return a column list clause for the given relation.
18159  *
18160  * Special case: if there are no undropped columns in the relation, return
18161  * "", not an invalid "()" column list.
18162  */
18163 static const char *
18164 fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer)
18165 {
18166         int                     numatts = ti->numatts;
18167         char      **attnames = ti->attnames;
18168         bool       *attisdropped = ti->attisdropped;
18169         bool            needComma;
18170         int                     i;
18171
18172         appendPQExpBufferChar(buffer, '(');
18173         needComma = false;
18174         for (i = 0; i < numatts; i++)
18175         {
18176                 if (attisdropped[i])
18177                         continue;
18178                 if (needComma)
18179                         appendPQExpBufferStr(buffer, ", ");
18180                 appendPQExpBufferStr(buffer, fmtId(attnames[i]));
18181                 needComma = true;
18182         }
18183
18184         if (!needComma)
18185                 return "";                              /* no undropped columns */
18186
18187         appendPQExpBufferChar(buffer, ')');
18188         return buffer->data;
18189 }
18190
18191 /*
18192  * Check if a reloptions array is nonempty.
18193  */
18194 static bool
18195 nonemptyReloptions(const char *reloptions)
18196 {
18197         /* Don't want to print it if it's just "{}" */
18198         return (reloptions != NULL && strlen(reloptions) > 2);
18199 }
18200
18201 /*
18202  * Format a reloptions array and append it to the given buffer.
18203  *
18204  * "prefix" is prepended to the option names; typically it's "" or "toast.".
18205  */
18206 static void
18207 appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
18208                                                 const char *prefix, Archive *fout)
18209 {
18210         bool            res;
18211
18212         res = appendReloptionsArray(buffer, reloptions, prefix, fout->encoding,
18213                                                                 fout->std_strings);
18214         if (!res)
18215                 write_msg(NULL, "WARNING: could not parse reloptions array\n");
18216 }