]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_dump.c
Fix a boatload of typos in C comments.
[postgresql] / src / bin / pg_dump / pg_dump.c
1 /*-------------------------------------------------------------------------
2  *
3  * pg_dump.c
4  *        pg_dump is a utility for dumping out a postgres database
5  *        into a script file.
6  *
7  * Portions Copyright (c) 1996-2018, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  *      pg_dump will read the system catalogs in a database and dump out a
11  *      script that reproduces the schema in terms of SQL that is understood
12  *      by PostgreSQL
13  *
14  *      Note that pg_dump runs in a transaction-snapshot mode transaction,
15  *      so it sees a consistent snapshot of the database including system
16  *      catalogs. However, it relies in part on various specialized backend
17  *      functions like pg_get_indexdef(), and those things tend to look at
18  *      the currently committed state.  So it is possible to get 'cache
19  *      lookup failed' error if someone performs DDL changes while a dump is
20  *      happening. The window for this sort of thing is from the acquisition
21  *      of the transaction snapshot to getSchemaData() (when pg_dump acquires
22  *      AccessShareLock on every table it intends to dump). It isn't very large,
23  *      but it can happen.
24  *
25  *      http://archives.postgresql.org/pgsql-bugs/2010-02/msg00187.php
26  *
27  * IDENTIFICATION
28  *        src/bin/pg_dump/pg_dump.c
29  *
30  *-------------------------------------------------------------------------
31  */
32 #include "postgres_fe.h"
33
34 #include <unistd.h>
35 #include <ctype.h>
36 #ifdef HAVE_TERMIOS_H
37 #include <termios.h>
38 #endif
39
40 #include "getopt_long.h"
41
42 #include "access/attnum.h"
43 #include "access/sysattr.h"
44 #include "access/transam.h"
45 #include "catalog/pg_aggregate.h"
46 #include "catalog/pg_am.h"
47 #include "catalog/pg_attribute.h"
48 #include "catalog/pg_cast.h"
49 #include "catalog/pg_class.h"
50 #include "catalog/pg_default_acl.h"
51 #include "catalog/pg_largeobject.h"
52 #include "catalog/pg_largeobject_metadata.h"
53 #include "catalog/pg_proc.h"
54 #include "catalog/pg_trigger.h"
55 #include "catalog/pg_type.h"
56 #include "libpq/libpq-fs.h"
57
58 #include "dumputils.h"
59 #include "parallel.h"
60 #include "pg_backup_db.h"
61 #include "pg_backup_utils.h"
62 #include "pg_dump.h"
63 #include "fe_utils/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  * Note implicit dependence on "fout"; we should get rid of that argument.
139  */
140 #define fmtQualifiedDumpable(obj) \
141         fmtQualifiedId(fout->remoteVersion, \
142                                    (obj)->dobj.namespace->dobj.name, \
143                                    (obj)->dobj.name)
144
145 static void help(const char *progname);
146 static void setup_connection(Archive *AH,
147                                  const char *dumpencoding, const char *dumpsnapshot,
148                                  char *use_role);
149 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
150 static void expand_schema_name_patterns(Archive *fout,
151                                                         SimpleStringList *patterns,
152                                                         SimpleOidList *oids,
153                                                         bool strict_names);
154 static void expand_table_name_patterns(Archive *fout,
155                                                    SimpleStringList *patterns,
156                                                    SimpleOidList *oids,
157                                                    bool strict_names);
158 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid);
159 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
160 static void refreshMatViewData(Archive *fout, TableDataInfo *tdinfo);
161 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
162 static void dumpComment(Archive *fout, const char *type, const char *name,
163                         const char *namespace, const char *owner,
164                         CatalogId catalogId, int subid, DumpId dumpId);
165 static int findComments(Archive *fout, Oid classoid, Oid objoid,
166                          CommentItem **items);
167 static int      collectComments(Archive *fout, CommentItem **items);
168 static void dumpSecLabel(Archive *fout, const char *type, const char *name,
169                          const char *namespace, const char *owner,
170                          CatalogId catalogId, int subid, DumpId dumpId);
171 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
172                           SecLabelItem **items);
173 static int      collectSecLabels(Archive *fout, SecLabelItem **items);
174 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
175 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
176 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
177 static void dumpType(Archive *fout, TypeInfo *tyinfo);
178 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
179 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
180 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
181 static void dumpUndefinedType(Archive *fout, TypeInfo *tyinfo);
182 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
183 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
184 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
185 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
186 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
187 static void dumpFunc(Archive *fout, FuncInfo *finfo);
188 static void dumpCast(Archive *fout, CastInfo *cast);
189 static void dumpTransform(Archive *fout, TransformInfo *transform);
190 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
191 static void dumpAccessMethod(Archive *fout, AccessMethodInfo *oprinfo);
192 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
193 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
194 static void dumpCollation(Archive *fout, CollInfo *collinfo);
195 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
196 static void dumpRule(Archive *fout, RuleInfo *rinfo);
197 static void dumpAgg(Archive *fout, AggInfo *agginfo);
198 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
199 static void dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo);
200 static void dumpTable(Archive *fout, TableInfo *tbinfo);
201 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
202 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
203 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
204 static void dumpSequenceData(Archive *fout, TableDataInfo *tdinfo);
205 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
206 static void dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo);
207 static void dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo);
208 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
209 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
210 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
211 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
212 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
213 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
214 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
215 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
216 static void dumpUserMappings(Archive *fout,
217                                  const char *servername, const char *namespace,
218                                  const char *owner, CatalogId catalogId, DumpId dumpId);
219 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
220
221 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
222                 const char *type, const char *name, const char *subname,
223                 const char *nspname, const char *owner,
224                 const char *acls, const char *racls,
225                 const char *initacls, const char *initracls);
226
227 static void getDependencies(Archive *fout);
228 static void BuildArchiveDependencies(Archive *fout);
229 static void findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
230                                                  DumpId **dependencies, int *nDeps, int *allocDeps);
231
232 static DumpableObject *createBoundaryObjects(void);
233 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
234                                                 DumpableObject *boundaryObjs);
235
236 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
237 static void getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, bool oids, char relkind);
238 static void makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo, bool oids);
239 static void buildMatViewRefreshDependencies(Archive *fout);
240 static void getTableDataFKConstraints(void);
241 static char *format_function_arguments(FuncInfo *finfo, char *funcargs,
242                                                   bool is_agg);
243 static char *format_function_arguments_old(Archive *fout,
244                                                           FuncInfo *finfo, int nallargs,
245                                                           char **allargtypes,
246                                                           char **argmodes,
247                                                           char **argnames);
248 static char *format_function_signature(Archive *fout,
249                                                   FuncInfo *finfo, bool honor_quotes);
250 static char *convertRegProcReference(Archive *fout,
251                                                 const char *proc);
252 static char *getFormattedOperatorName(Archive *fout, const char *oproid);
253 static char *convertTSFunction(Archive *fout, Oid funcOid);
254 static Oid      findLastBuiltinOid_V71(Archive *fout, const char *);
255 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
256 static void getBlobs(Archive *fout);
257 static void dumpBlob(Archive *fout, BlobInfo *binfo);
258 static int      dumpBlobs(Archive *fout, void *arg);
259 static void dumpPolicy(Archive *fout, PolicyInfo *polinfo);
260 static void dumpPublication(Archive *fout, PublicationInfo *pubinfo);
261 static void dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo);
262 static void dumpSubscription(Archive *fout, SubscriptionInfo *subinfo);
263 static void dumpDatabase(Archive *AH);
264 static void dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
265                                    const char *dbname, Oid dboid);
266 static void dumpEncoding(Archive *AH);
267 static void dumpStdStrings(Archive *AH);
268 static void dumpSearchPath(Archive *AH);
269 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
270                                                                                  PQExpBuffer upgrade_buffer,
271                                                                                  Oid pg_type_oid,
272                                                                                  bool force_array_type);
273 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
274                                                                                 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
275 static void binary_upgrade_set_pg_class_oids(Archive *fout,
276                                                                  PQExpBuffer upgrade_buffer,
277                                                                  Oid pg_class_oid, bool is_index);
278 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
279                                                                 DumpableObject *dobj,
280                                                                 const char *objtype,
281                                                                 const char *objname,
282                                                                 const char *objnamespace);
283 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
284 static const char *fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer);
285 static bool nonemptyReloptions(const char *reloptions);
286 static void appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
287                                                 const char *prefix, Archive *fout);
288 static char *get_synchronized_snapshot(Archive *fout);
289 static void setupDumpWorker(Archive *AHX);
290 static TableInfo *getRootTableInfo(TableInfo *tbinfo);
291
292
293 int
294 main(int argc, char **argv)
295 {
296         int                     c;
297         const char *filename = NULL;
298         const char *format = "p";
299         TableInfo  *tblinfo;
300         int                     numTables;
301         DumpableObject **dobjs;
302         int                     numObjs;
303         DumpableObject *boundaryObjs;
304         int                     i;
305         int                     optindex;
306         RestoreOptions *ropt;
307         Archive    *fout;                       /* the script file */
308         const char *dumpencoding = NULL;
309         const char *dumpsnapshot = NULL;
310         char       *use_role = NULL;
311         int                     numWorkers = 1;
312         trivalue        prompt_password = TRI_DEFAULT;
313         int                     compressLevel = -1;
314         int                     plainText = 0;
315         ArchiveFormat archiveFormat = archUnknown;
316         ArchiveMode archiveMode;
317
318         static DumpOptions dopt;
319
320         static struct option long_options[] = {
321                 {"data-only", no_argument, NULL, 'a'},
322                 {"blobs", no_argument, NULL, 'b'},
323                 {"no-blobs", no_argument, NULL, 'B'},
324                 {"clean", no_argument, NULL, 'c'},
325                 {"create", no_argument, NULL, 'C'},
326                 {"dbname", required_argument, NULL, 'd'},
327                 {"file", required_argument, NULL, 'f'},
328                 {"format", required_argument, NULL, 'F'},
329                 {"host", required_argument, NULL, 'h'},
330                 {"jobs", 1, NULL, 'j'},
331                 {"no-reconnect", no_argument, NULL, 'R'},
332                 {"oids", no_argument, NULL, 'o'},
333                 {"no-owner", no_argument, NULL, 'O'},
334                 {"port", required_argument, NULL, 'p'},
335                 {"schema", required_argument, NULL, 'n'},
336                 {"exclude-schema", required_argument, NULL, 'N'},
337                 {"schema-only", no_argument, NULL, 's'},
338                 {"superuser", required_argument, NULL, 'S'},
339                 {"table", required_argument, NULL, 't'},
340                 {"exclude-table", required_argument, NULL, 'T'},
341                 {"no-password", no_argument, NULL, 'w'},
342                 {"password", no_argument, NULL, 'W'},
343                 {"username", required_argument, NULL, 'U'},
344                 {"verbose", no_argument, NULL, 'v'},
345                 {"no-privileges", no_argument, NULL, 'x'},
346                 {"no-acl", no_argument, NULL, 'x'},
347                 {"compress", required_argument, NULL, 'Z'},
348                 {"encoding", required_argument, NULL, 'E'},
349                 {"help", no_argument, NULL, '?'},
350                 {"version", no_argument, NULL, 'V'},
351
352                 /*
353                  * the following options don't have an equivalent short option letter
354                  */
355                 {"attribute-inserts", no_argument, &dopt.column_inserts, 1},
356                 {"binary-upgrade", no_argument, &dopt.binary_upgrade, 1},
357                 {"column-inserts", no_argument, &dopt.column_inserts, 1},
358                 {"disable-dollar-quoting", no_argument, &dopt.disable_dollar_quoting, 1},
359                 {"disable-triggers", no_argument, &dopt.disable_triggers, 1},
360                 {"enable-row-security", no_argument, &dopt.enable_row_security, 1},
361                 {"exclude-table-data", required_argument, NULL, 4},
362                 {"if-exists", no_argument, &dopt.if_exists, 1},
363                 {"inserts", no_argument, &dopt.dump_inserts, 1},
364                 {"lock-wait-timeout", required_argument, NULL, 2},
365                 {"no-tablespaces", no_argument, &dopt.outputNoTablespaces, 1},
366                 {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
367                 {"load-via-partition-root", no_argument, &dopt.load_via_partition_root, 1},
368                 {"role", required_argument, NULL, 3},
369                 {"section", required_argument, NULL, 5},
370                 {"serializable-deferrable", no_argument, &dopt.serializable_deferrable, 1},
371                 {"snapshot", required_argument, NULL, 6},
372                 {"strict-names", no_argument, &strict_names, 1},
373                 {"use-set-session-authorization", no_argument, &dopt.use_setsessauth, 1},
374                 {"no-comments", no_argument, &dopt.no_comments, 1},
375                 {"no-publications", no_argument, &dopt.no_publications, 1},
376                 {"no-security-labels", no_argument, &dopt.no_security_labels, 1},
377                 {"no-synchronized-snapshots", no_argument, &dopt.no_synchronized_snapshots, 1},
378                 {"no-unlogged-table-data", no_argument, &dopt.no_unlogged_table_data, 1},
379                 {"no-subscriptions", no_argument, &dopt.no_subscriptions, 1},
380                 {"no-sync", no_argument, NULL, 7},
381
382                 {NULL, 0, NULL, 0}
383         };
384
385         set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
386
387         /*
388          * Initialize what we need for parallel execution, especially for thread
389          * support on Windows.
390          */
391         init_parallel_dump_utils();
392
393         g_verbose = false;
394
395         strcpy(g_comment_start, "-- ");
396         g_comment_end[0] = '\0';
397         strcpy(g_opaque_type, "opaque");
398
399         progname = get_progname(argv[0]);
400
401         if (argc > 1)
402         {
403                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
404                 {
405                         help(progname);
406                         exit_nicely(0);
407                 }
408                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
409                 {
410                         puts("pg_dump (PostgreSQL) " PG_VERSION);
411                         exit_nicely(0);
412                 }
413         }
414
415         InitDumpOptions(&dopt);
416
417         while ((c = getopt_long(argc, argv, "abBcCd:E:f:F:h:j:n:N:oOp:RsS:t:T:U:vwWxZ:",
418                                                         long_options, &optindex)) != -1)
419         {
420                 switch (c)
421                 {
422                         case 'a':                       /* Dump data only */
423                                 dopt.dataOnly = true;
424                                 break;
425
426                         case 'b':                       /* Dump blobs */
427                                 dopt.outputBlobs = true;
428                                 break;
429
430                         case 'B':                       /* Don't dump blobs */
431                                 dopt.dontOutputBlobs = true;
432                                 break;
433
434                         case 'c':                       /* clean (i.e., drop) schema prior to create */
435                                 dopt.outputClean = 1;
436                                 break;
437
438                         case 'C':                       /* Create DB */
439                                 dopt.outputCreateDB = 1;
440                                 break;
441
442                         case 'd':                       /* database name */
443                                 dopt.dbname = pg_strdup(optarg);
444                                 break;
445
446                         case 'E':                       /* Dump encoding */
447                                 dumpencoding = pg_strdup(optarg);
448                                 break;
449
450                         case 'f':
451                                 filename = pg_strdup(optarg);
452                                 break;
453
454                         case 'F':
455                                 format = pg_strdup(optarg);
456                                 break;
457
458                         case 'h':                       /* server host */
459                                 dopt.pghost = pg_strdup(optarg);
460                                 break;
461
462                         case 'j':                       /* number of dump jobs */
463                                 numWorkers = atoi(optarg);
464                                 break;
465
466                         case 'n':                       /* include schema(s) */
467                                 simple_string_list_append(&schema_include_patterns, optarg);
468                                 dopt.include_everything = false;
469                                 break;
470
471                         case 'N':                       /* exclude schema(s) */
472                                 simple_string_list_append(&schema_exclude_patterns, optarg);
473                                 break;
474
475                         case 'o':                       /* Dump oids */
476                                 dopt.oids = true;
477                                 break;
478
479                         case 'O':                       /* Don't reconnect to match owner */
480                                 dopt.outputNoOwner = 1;
481                                 break;
482
483                         case 'p':                       /* server port */
484                                 dopt.pgport = pg_strdup(optarg);
485                                 break;
486
487                         case 'R':
488                                 /* no-op, still accepted for backwards compatibility */
489                                 break;
490
491                         case 's':                       /* dump schema only */
492                                 dopt.schemaOnly = true;
493                                 break;
494
495                         case 'S':                       /* Username for superuser in plain text output */
496                                 dopt.outputSuperuser = pg_strdup(optarg);
497                                 break;
498
499                         case 't':                       /* include table(s) */
500                                 simple_string_list_append(&table_include_patterns, optarg);
501                                 dopt.include_everything = false;
502                                 break;
503
504                         case 'T':                       /* exclude table(s) */
505                                 simple_string_list_append(&table_exclude_patterns, optarg);
506                                 break;
507
508                         case 'U':
509                                 dopt.username = pg_strdup(optarg);
510                                 break;
511
512                         case 'v':                       /* verbose */
513                                 g_verbose = true;
514                                 break;
515
516                         case 'w':
517                                 prompt_password = TRI_NO;
518                                 break;
519
520                         case 'W':
521                                 prompt_password = TRI_YES;
522                                 break;
523
524                         case 'x':                       /* skip ACL dump */
525                                 dopt.aclsSkip = true;
526                                 break;
527
528                         case 'Z':                       /* Compression Level */
529                                 compressLevel = atoi(optarg);
530                                 if (compressLevel < 0 || compressLevel > 9)
531                                 {
532                                         write_msg(NULL, "compression level must be in range 0..9\n");
533                                         exit_nicely(1);
534                                 }
535                                 break;
536
537                         case 0:
538                                 /* This covers the long options. */
539                                 break;
540
541                         case 2:                         /* lock-wait-timeout */
542                                 dopt.lockWaitTimeout = pg_strdup(optarg);
543                                 break;
544
545                         case 3:                         /* SET ROLE */
546                                 use_role = pg_strdup(optarg);
547                                 break;
548
549                         case 4:                         /* exclude table(s) data */
550                                 simple_string_list_append(&tabledata_exclude_patterns, optarg);
551                                 break;
552
553                         case 5:                         /* section */
554                                 set_dump_section(optarg, &dopt.dumpSections);
555                                 break;
556
557                         case 6:                         /* snapshot */
558                                 dumpsnapshot = pg_strdup(optarg);
559                                 break;
560
561                         case 7:                         /* no-sync */
562                                 dosync = false;
563                                 break;
564
565                         default:
566                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
567                                 exit_nicely(1);
568                 }
569         }
570
571         /*
572          * Non-option argument specifies database name as long as it wasn't
573          * already specified with -d / --dbname
574          */
575         if (optind < argc && dopt.dbname == NULL)
576                 dopt.dbname = argv[optind++];
577
578         /* Complain if any arguments remain */
579         if (optind < argc)
580         {
581                 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
582                                 progname, argv[optind]);
583                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
584                                 progname);
585                 exit_nicely(1);
586         }
587
588         /* --column-inserts implies --inserts */
589         if (dopt.column_inserts)
590                 dopt.dump_inserts = 1;
591
592         /*
593          * Binary upgrade mode implies dumping sequence data even in schema-only
594          * mode.  This is not exposed as a separate option, but kept separate
595          * internally for clarity.
596          */
597         if (dopt.binary_upgrade)
598                 dopt.sequence_data = 1;
599
600         if (dopt.dataOnly && dopt.schemaOnly)
601         {
602                 write_msg(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
603                 exit_nicely(1);
604         }
605
606         if (dopt.dataOnly && dopt.outputClean)
607         {
608                 write_msg(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
609                 exit_nicely(1);
610         }
611
612         if (dopt.dump_inserts && dopt.oids)
613         {
614                 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
615                 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
616                 exit_nicely(1);
617         }
618
619         if (dopt.if_exists && !dopt.outputClean)
620                 exit_horribly(NULL, "option --if-exists requires option -c/--clean\n");
621
622         /* Identify archive format to emit */
623         archiveFormat = parseArchiveFormat(format, &archiveMode);
624
625         /* archiveFormat specific setup */
626         if (archiveFormat == archNull)
627                 plainText = 1;
628
629         /* Custom and directory formats are compressed by default, others not */
630         if (compressLevel == -1)
631         {
632 #ifdef HAVE_LIBZ
633                 if (archiveFormat == archCustom || archiveFormat == archDirectory)
634                         compressLevel = Z_DEFAULT_COMPRESSION;
635                 else
636 #endif
637                         compressLevel = 0;
638         }
639
640 #ifndef HAVE_LIBZ
641         if (compressLevel != 0)
642                 write_msg(NULL, "WARNING: requested compression not available in this "
643                                   "installation -- archive will be uncompressed\n");
644         compressLevel = 0;
645 #endif
646
647         /*
648          * If emitting an archive format, we always want to emit a DATABASE item,
649          * in case --create is specified at pg_restore time.
650          */
651         if (!plainText)
652                 dopt.outputCreateDB = 1;
653
654         /*
655          * On Windows we can only have at most MAXIMUM_WAIT_OBJECTS (= 64 usually)
656          * parallel jobs because that's the maximum limit for the
657          * WaitForMultipleObjects() call.
658          */
659         if (numWorkers <= 0
660 #ifdef WIN32
661                 || numWorkers > MAXIMUM_WAIT_OBJECTS
662 #endif
663                 )
664                 exit_horribly(NULL, "invalid number of parallel jobs\n");
665
666         /* Parallel backup only in the directory archive format so far */
667         if (archiveFormat != archDirectory && numWorkers > 1)
668                 exit_horribly(NULL, "parallel backup only supported by the directory format\n");
669
670         /* Open the output file */
671         fout = CreateArchive(filename, archiveFormat, compressLevel, dosync,
672                                                  archiveMode, setupDumpWorker);
673
674         /* Make dump options accessible right away */
675         SetArchiveOptions(fout, &dopt, NULL);
676
677         /* Register the cleanup hook */
678         on_exit_close_archive(fout);
679
680         /* Let the archiver know how noisy to be */
681         fout->verbose = g_verbose;
682
683         /*
684          * We allow the server to be back to 8.0, and up to any minor release of
685          * our own major version.  (See also version check in pg_dumpall.c.)
686          */
687         fout->minRemoteVersion = 80000;
688         fout->maxRemoteVersion = (PG_VERSION_NUM / 100) * 100 + 99;
689
690         fout->numWorkers = numWorkers;
691
692         /*
693          * Open the database using the Archiver, so it knows about it. Errors mean
694          * death.
695          */
696         ConnectDatabase(fout, dopt.dbname, dopt.pghost, dopt.pgport, dopt.username, prompt_password);
697         setup_connection(fout, dumpencoding, dumpsnapshot, use_role);
698
699         /*
700          * Disable security label support if server version < v9.1.x (prevents
701          * access to nonexistent pg_seclabel catalog)
702          */
703         if (fout->remoteVersion < 90100)
704                 dopt.no_security_labels = 1;
705
706         /*
707          * On hot standbys, never try to dump unlogged table data, since it will
708          * just throw an error.
709          */
710         if (fout->isStandby)
711                 dopt.no_unlogged_table_data = true;
712
713         /* Select the appropriate subquery to convert user IDs to names */
714         if (fout->remoteVersion >= 80100)
715                 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
716         else
717                 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
718
719         /* check the version for the synchronized snapshots feature */
720         if (numWorkers > 1 && fout->remoteVersion < 90200
721                 && !dopt.no_synchronized_snapshots)
722                 exit_horribly(NULL,
723                                           "Synchronized snapshots are not supported by this server version.\n"
724                                           "Run with --no-synchronized-snapshots instead if you do not need\n"
725                                           "synchronized snapshots.\n");
726
727         /* check the version when a snapshot is explicitly specified by user */
728         if (dumpsnapshot && fout->remoteVersion < 90200)
729                 exit_horribly(NULL,
730                                           "Exported snapshots are not supported by this server version.\n");
731
732         /*
733          * Find the last built-in OID, if needed (prior to 8.1)
734          *
735          * With 8.1 and above, we can just use FirstNormalObjectId - 1.
736          */
737         if (fout->remoteVersion < 80100)
738                 g_last_builtin_oid = findLastBuiltinOid_V71(fout,
739                                                                                                         PQdb(GetConnection(fout)));
740         else
741                 g_last_builtin_oid = FirstNormalObjectId - 1;
742
743         if (g_verbose)
744                 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
745
746         /* Expand schema selection patterns into OID lists */
747         if (schema_include_patterns.head != NULL)
748         {
749                 expand_schema_name_patterns(fout, &schema_include_patterns,
750                                                                         &schema_include_oids,
751                                                                         strict_names);
752                 if (schema_include_oids.head == NULL)
753                         exit_horribly(NULL, "no matching schemas were found\n");
754         }
755         expand_schema_name_patterns(fout, &schema_exclude_patterns,
756                                                                 &schema_exclude_oids,
757                                                                 false);
758         /* non-matching exclusion patterns aren't an error */
759
760         /* Expand table selection patterns into OID lists */
761         if (table_include_patterns.head != NULL)
762         {
763                 expand_table_name_patterns(fout, &table_include_patterns,
764                                                                    &table_include_oids,
765                                                                    strict_names);
766                 if (table_include_oids.head == NULL)
767                         exit_horribly(NULL, "no matching tables were found\n");
768         }
769         expand_table_name_patterns(fout, &table_exclude_patterns,
770                                                            &table_exclude_oids,
771                                                            false);
772
773         expand_table_name_patterns(fout, &tabledata_exclude_patterns,
774                                                            &tabledata_exclude_oids,
775                                                            false);
776
777         /* non-matching exclusion patterns aren't an error */
778
779         /*
780          * Dumping blobs is the default for dumps where an inclusion switch is not
781          * used (an "include everything" dump).  -B can be used to exclude blobs
782          * from those dumps.  -b can be used to include blobs even when an
783          * inclusion switch is used.
784          *
785          * -s means "schema only" and blobs are data, not schema, so we never
786          * include blobs when -s is used.
787          */
788         if (dopt.include_everything && !dopt.schemaOnly && !dopt.dontOutputBlobs)
789                 dopt.outputBlobs = true;
790
791         /*
792          * Now scan the database and create DumpableObject structs for all the
793          * objects we intend to dump.
794          */
795         tblinfo = getSchemaData(fout, &numTables);
796
797         if (fout->remoteVersion < 80400)
798                 guessConstraintInheritance(tblinfo, numTables);
799
800         if (!dopt.schemaOnly)
801         {
802                 getTableData(&dopt, tblinfo, numTables, dopt.oids, 0);
803                 buildMatViewRefreshDependencies(fout);
804                 if (dopt.dataOnly)
805                         getTableDataFKConstraints();
806         }
807
808         if (dopt.schemaOnly && dopt.sequence_data)
809                 getTableData(&dopt, tblinfo, numTables, dopt.oids, RELKIND_SEQUENCE);
810
811         /*
812          * In binary-upgrade mode, we do not have to worry about the actual blob
813          * data or the associated metadata that resides in the pg_largeobject and
814          * pg_largeobject_metadata tables, respectively.
815          *
816          * However, we do need to collect blob information as there may be
817          * comments or other information on blobs that we do need to dump out.
818          */
819         if (dopt.outputBlobs || dopt.binary_upgrade)
820                 getBlobs(fout);
821
822         /*
823          * Collect dependency data to assist in ordering the objects.
824          */
825         getDependencies(fout);
826
827         /* Lastly, create dummy objects to represent the section boundaries */
828         boundaryObjs = createBoundaryObjects();
829
830         /* Get pointers to all the known DumpableObjects */
831         getDumpableObjects(&dobjs, &numObjs);
832
833         /*
834          * Add dummy dependencies to enforce the dump section ordering.
835          */
836         addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
837
838         /*
839          * Sort the objects into a safe dump order (no forward references).
840          *
841          * We rely on dependency information to help us determine a safe order, so
842          * the initial sort is mostly for cosmetic purposes: we sort by name to
843          * ensure that logically identical schemas will dump identically.
844          */
845         sortDumpableObjectsByTypeName(dobjs, numObjs);
846
847         /* If we do a parallel dump, we want the largest tables to go first */
848         if (archiveFormat == archDirectory && numWorkers > 1)
849                 sortDataAndIndexObjectsBySize(dobjs, numObjs);
850
851         sortDumpableObjects(dobjs, numObjs,
852                                                 boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
853
854         /*
855          * Create archive TOC entries for all the objects to be dumped, in a safe
856          * order.
857          */
858
859         /* First the special ENCODING, STDSTRINGS, and SEARCHPATH entries. */
860         dumpEncoding(fout);
861         dumpStdStrings(fout);
862         dumpSearchPath(fout);
863
864         /* The database items are always next, unless we don't want them at all */
865         if (dopt.outputCreateDB)
866                 dumpDatabase(fout);
867
868         /* Now the rearrangeable objects. */
869         for (i = 0; i < numObjs; i++)
870                 dumpDumpableObject(fout, dobjs[i]);
871
872         /*
873          * Set up options info to ensure we dump what we want.
874          */
875         ropt = NewRestoreOptions();
876         ropt->filename = filename;
877
878         /* if you change this list, see dumpOptionsFromRestoreOptions */
879         ropt->dropSchema = dopt.outputClean;
880         ropt->dataOnly = dopt.dataOnly;
881         ropt->schemaOnly = dopt.schemaOnly;
882         ropt->if_exists = dopt.if_exists;
883         ropt->column_inserts = dopt.column_inserts;
884         ropt->dumpSections = dopt.dumpSections;
885         ropt->aclsSkip = dopt.aclsSkip;
886         ropt->superuser = dopt.outputSuperuser;
887         ropt->createDB = dopt.outputCreateDB;
888         ropt->noOwner = dopt.outputNoOwner;
889         ropt->noTablespace = dopt.outputNoTablespaces;
890         ropt->disable_triggers = dopt.disable_triggers;
891         ropt->use_setsessauth = dopt.use_setsessauth;
892         ropt->disable_dollar_quoting = dopt.disable_dollar_quoting;
893         ropt->dump_inserts = dopt.dump_inserts;
894         ropt->no_comments = dopt.no_comments;
895         ropt->no_publications = dopt.no_publications;
896         ropt->no_security_labels = dopt.no_security_labels;
897         ropt->no_subscriptions = dopt.no_subscriptions;
898         ropt->lockWaitTimeout = dopt.lockWaitTimeout;
899         ropt->include_everything = dopt.include_everything;
900         ropt->enable_row_security = dopt.enable_row_security;
901         ropt->sequence_data = dopt.sequence_data;
902         ropt->binary_upgrade = dopt.binary_upgrade;
903
904         if (compressLevel == -1)
905                 ropt->compression = 0;
906         else
907                 ropt->compression = compressLevel;
908
909         ropt->suppressDumpWarnings = true;      /* We've already shown them */
910
911         SetArchiveOptions(fout, &dopt, ropt);
912
913         /* Mark which entries should be output */
914         ProcessArchiveRestoreOptions(fout);
915
916         /*
917          * The archive's TOC entries are now marked as to which ones will actually
918          * be output, so we can set up their dependency lists properly. This isn't
919          * necessary for plain-text output, though.
920          */
921         if (!plainText)
922                 BuildArchiveDependencies(fout);
923
924         /*
925          * And finally we can do the actual output.
926          *
927          * Note: for non-plain-text output formats, the output file is written
928          * inside CloseArchive().  This is, um, bizarre; but not worth changing
929          * right now.
930          */
931         if (plainText)
932                 RestoreArchive(fout);
933
934         CloseArchive(fout);
935
936         exit_nicely(0);
937 }
938
939
940 static void
941 help(const char *progname)
942 {
943         printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
944         printf(_("Usage:\n"));
945         printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
946
947         printf(_("\nGeneral options:\n"));
948         printf(_("  -f, --file=FILENAME          output file or directory name\n"));
949         printf(_("  -F, --format=c|d|t|p         output file format (custom, directory, tar,\n"
950                          "                               plain text (default))\n"));
951         printf(_("  -j, --jobs=NUM               use this many parallel jobs to dump\n"));
952         printf(_("  -v, --verbose                verbose mode\n"));
953         printf(_("  -V, --version                output version information, then exit\n"));
954         printf(_("  -Z, --compress=0-9           compression level for compressed formats\n"));
955         printf(_("  --lock-wait-timeout=TIMEOUT  fail after waiting TIMEOUT for a table lock\n"));
956         printf(_("  --no-sync                    do not wait for changes to be written safely to disk\n"));
957         printf(_("  -?, --help                   show this help, then exit\n"));
958
959         printf(_("\nOptions controlling the output content:\n"));
960         printf(_("  -a, --data-only              dump only the data, not the schema\n"));
961         printf(_("  -b, --blobs                  include large objects in dump\n"));
962         printf(_("  -B, --no-blobs               exclude large objects in dump\n"));
963         printf(_("  -c, --clean                  clean (drop) database objects before recreating\n"));
964         printf(_("  -C, --create                 include commands to create database in dump\n"));
965         printf(_("  -E, --encoding=ENCODING      dump the data in encoding ENCODING\n"));
966         printf(_("  -n, --schema=SCHEMA          dump the named schema(s) only\n"));
967         printf(_("  -N, --exclude-schema=SCHEMA  do NOT dump the named schema(s)\n"));
968         printf(_("  -o, --oids                   include OIDs in dump\n"));
969         printf(_("  -O, --no-owner               skip restoration of object ownership in\n"
970                          "                               plain-text format\n"));
971         printf(_("  -s, --schema-only            dump only the schema, no data\n"));
972         printf(_("  -S, --superuser=NAME         superuser user name to use in plain-text format\n"));
973         printf(_("  -t, --table=TABLE            dump the named table(s) only\n"));
974         printf(_("  -T, --exclude-table=TABLE    do NOT dump the named table(s)\n"));
975         printf(_("  -x, --no-privileges          do not dump privileges (grant/revoke)\n"));
976         printf(_("  --binary-upgrade             for use by upgrade utilities only\n"));
977         printf(_("  --column-inserts             dump data as INSERT commands with column names\n"));
978         printf(_("  --disable-dollar-quoting     disable dollar quoting, use SQL standard quoting\n"));
979         printf(_("  --disable-triggers           disable triggers during data-only restore\n"));
980         printf(_("  --enable-row-security        enable row security (dump only content user has\n"
981                          "                               access to)\n"));
982         printf(_("  --exclude-table-data=TABLE   do NOT dump data for the named table(s)\n"));
983         printf(_("  --if-exists                  use IF EXISTS when dropping objects\n"));
984         printf(_("  --inserts                    dump data as INSERT commands, rather than COPY\n"));
985         printf(_("  --no-comments                do not dump comments\n"));
986         printf(_("  --no-publications            do not dump publications\n"));
987         printf(_("  --no-security-labels         do not dump security label assignments\n"));
988         printf(_("  --no-subscriptions           do not dump subscriptions\n"));
989         printf(_("  --no-synchronized-snapshots  do not use synchronized snapshots in parallel jobs\n"));
990         printf(_("  --no-tablespaces             do not dump tablespace assignments\n"));
991         printf(_("  --no-unlogged-table-data     do not dump unlogged table data\n"));
992         printf(_("  --quote-all-identifiers      quote all identifiers, even if not key words\n"));
993         printf(_("  --load-via-partition-root    load partitions via the root table\n"));
994         printf(_("  --section=SECTION            dump named section (pre-data, data, or post-data)\n"));
995         printf(_("  --serializable-deferrable    wait until the dump can run without anomalies\n"));
996         printf(_("  --snapshot=SNAPSHOT          use given snapshot for the dump\n"));
997         printf(_("  --strict-names               require table and/or schema include patterns to\n"
998                          "                               match at least one entity each\n"));
999         printf(_("  --use-set-session-authorization\n"
1000                          "                               use SET SESSION AUTHORIZATION commands instead of\n"
1001                          "                               ALTER OWNER commands to set ownership\n"));
1002
1003         printf(_("\nConnection options:\n"));
1004         printf(_("  -d, --dbname=DBNAME      database to dump\n"));
1005         printf(_("  -h, --host=HOSTNAME      database server host or socket directory\n"));
1006         printf(_("  -p, --port=PORT          database server port number\n"));
1007         printf(_("  -U, --username=NAME      connect as specified database user\n"));
1008         printf(_("  -w, --no-password        never prompt for password\n"));
1009         printf(_("  -W, --password           force password prompt (should happen automatically)\n"));
1010         printf(_("  --role=ROLENAME          do SET ROLE before dump\n"));
1011
1012         printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
1013                          "variable value is used.\n\n"));
1014         printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
1015 }
1016
1017 static void
1018 setup_connection(Archive *AH, const char *dumpencoding,
1019                                  const char *dumpsnapshot, char *use_role)
1020 {
1021         DumpOptions *dopt = AH->dopt;
1022         PGconn     *conn = GetConnection(AH);
1023         const char *std_strings;
1024
1025         PQclear(ExecuteSqlQueryForSingleRow(AH, ALWAYS_SECURE_SEARCH_PATH_SQL));
1026
1027         /*
1028          * Set the client encoding if requested.
1029          */
1030         if (dumpencoding)
1031         {
1032                 if (PQsetClientEncoding(conn, dumpencoding) < 0)
1033                         exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
1034                                                   dumpencoding);
1035         }
1036
1037         /*
1038          * Get the active encoding and the standard_conforming_strings setting, so
1039          * we know how to escape strings.
1040          */
1041         AH->encoding = PQclientEncoding(conn);
1042
1043         std_strings = PQparameterStatus(conn, "standard_conforming_strings");
1044         AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
1045
1046         /*
1047          * Set the role if requested.  In a parallel dump worker, we'll be passed
1048          * use_role == NULL, but AH->use_role is already set (if user specified it
1049          * originally) and we should use that.
1050          */
1051         if (!use_role && AH->use_role)
1052                 use_role = AH->use_role;
1053
1054         /* Set the role if requested */
1055         if (use_role && AH->remoteVersion >= 80100)
1056         {
1057                 PQExpBuffer query = createPQExpBuffer();
1058
1059                 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
1060                 ExecuteSqlStatement(AH, query->data);
1061                 destroyPQExpBuffer(query);
1062
1063                 /* save it for possible later use by parallel workers */
1064                 if (!AH->use_role)
1065                         AH->use_role = pg_strdup(use_role);
1066         }
1067
1068         /* Set the datestyle to ISO to ensure the dump's portability */
1069         ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
1070
1071         /* Likewise, avoid using sql_standard intervalstyle */
1072         if (AH->remoteVersion >= 80400)
1073                 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
1074
1075         /*
1076          * Set extra_float_digits so that we can dump float data exactly (given
1077          * correctly implemented float I/O code, anyway)
1078          */
1079         if (AH->remoteVersion >= 90000)
1080                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
1081         else
1082                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
1083
1084         /*
1085          * If synchronized scanning is supported, disable it, to prevent
1086          * unpredictable changes in row ordering across a dump and reload.
1087          */
1088         if (AH->remoteVersion >= 80300)
1089                 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
1090
1091         /*
1092          * Disable timeouts if supported.
1093          */
1094         ExecuteSqlStatement(AH, "SET statement_timeout = 0");
1095         if (AH->remoteVersion >= 90300)
1096                 ExecuteSqlStatement(AH, "SET lock_timeout = 0");
1097         if (AH->remoteVersion >= 90600)
1098                 ExecuteSqlStatement(AH, "SET idle_in_transaction_session_timeout = 0");
1099
1100         /*
1101          * Quote all identifiers, if requested.
1102          */
1103         if (quote_all_identifiers && AH->remoteVersion >= 90100)
1104                 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
1105
1106         /*
1107          * Adjust row-security mode, if supported.
1108          */
1109         if (AH->remoteVersion >= 90500)
1110         {
1111                 if (dopt->enable_row_security)
1112                         ExecuteSqlStatement(AH, "SET row_security = on");
1113                 else
1114                         ExecuteSqlStatement(AH, "SET row_security = off");
1115         }
1116
1117         /*
1118          * Start transaction-snapshot mode transaction to dump consistent data.
1119          */
1120         ExecuteSqlStatement(AH, "BEGIN");
1121         if (AH->remoteVersion >= 90100)
1122         {
1123                 /*
1124                  * To support the combination of serializable_deferrable with the jobs
1125                  * option we use REPEATABLE READ for the worker connections that are
1126                  * passed a snapshot.  As long as the snapshot is acquired in a
1127                  * SERIALIZABLE, READ ONLY, DEFERRABLE transaction, its use within a
1128                  * REPEATABLE READ transaction provides the appropriate integrity
1129                  * guarantees.  This is a kluge, but safe for back-patching.
1130                  */
1131                 if (dopt->serializable_deferrable && AH->sync_snapshot_id == NULL)
1132                         ExecuteSqlStatement(AH,
1133                                                                 "SET TRANSACTION ISOLATION LEVEL "
1134                                                                 "SERIALIZABLE, READ ONLY, DEFERRABLE");
1135                 else
1136                         ExecuteSqlStatement(AH,
1137                                                                 "SET TRANSACTION ISOLATION LEVEL "
1138                                                                 "REPEATABLE READ, READ ONLY");
1139         }
1140         else
1141         {
1142                 ExecuteSqlStatement(AH,
1143                                                         "SET TRANSACTION ISOLATION LEVEL "
1144                                                         "SERIALIZABLE, READ ONLY");
1145         }
1146
1147         /*
1148          * If user specified a snapshot to use, select that.  In a parallel dump
1149          * worker, we'll be passed dumpsnapshot == NULL, but AH->sync_snapshot_id
1150          * is already set (if the server can handle it) and we should use that.
1151          */
1152         if (dumpsnapshot)
1153                 AH->sync_snapshot_id = pg_strdup(dumpsnapshot);
1154
1155         if (AH->sync_snapshot_id)
1156         {
1157                 PQExpBuffer query = createPQExpBuffer();
1158
1159                 appendPQExpBuffer(query, "SET TRANSACTION SNAPSHOT ");
1160                 appendStringLiteralConn(query, AH->sync_snapshot_id, conn);
1161                 ExecuteSqlStatement(AH, query->data);
1162                 destroyPQExpBuffer(query);
1163         }
1164         else if (AH->numWorkers > 1 &&
1165                          AH->remoteVersion >= 90200 &&
1166                          !dopt->no_synchronized_snapshots)
1167         {
1168                 if (AH->isStandby && AH->remoteVersion < 100000)
1169                         exit_horribly(NULL,
1170                                                   "Synchronized snapshots on standby servers are not supported by this server version.\n"
1171                                                   "Run with --no-synchronized-snapshots instead if you do not need\n"
1172                                                   "synchronized snapshots.\n");
1173
1174
1175                 AH->sync_snapshot_id = get_synchronized_snapshot(AH);
1176         }
1177 }
1178
1179 /* Set up connection for a parallel worker process */
1180 static void
1181 setupDumpWorker(Archive *AH)
1182 {
1183         /*
1184          * We want to re-select all the same values the master connection is
1185          * using.  We'll have inherited directly-usable values in
1186          * AH->sync_snapshot_id and AH->use_role, but we need to translate the
1187          * inherited encoding value back to a string to pass to setup_connection.
1188          */
1189         setup_connection(AH,
1190                                          pg_encoding_to_char(AH->encoding),
1191                                          NULL,
1192                                          NULL);
1193 }
1194
1195 static char *
1196 get_synchronized_snapshot(Archive *fout)
1197 {
1198         char       *query = "SELECT pg_catalog.pg_export_snapshot()";
1199         char       *result;
1200         PGresult   *res;
1201
1202         res = ExecuteSqlQueryForSingleRow(fout, query);
1203         result = pg_strdup(PQgetvalue(res, 0, 0));
1204         PQclear(res);
1205
1206         return result;
1207 }
1208
1209 static ArchiveFormat
1210 parseArchiveFormat(const char *format, ArchiveMode *mode)
1211 {
1212         ArchiveFormat archiveFormat;
1213
1214         *mode = archModeWrite;
1215
1216         if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
1217         {
1218                 /* This is used by pg_dumpall, and is not documented */
1219                 archiveFormat = archNull;
1220                 *mode = archModeAppend;
1221         }
1222         else if (pg_strcasecmp(format, "c") == 0)
1223                 archiveFormat = archCustom;
1224         else if (pg_strcasecmp(format, "custom") == 0)
1225                 archiveFormat = archCustom;
1226         else if (pg_strcasecmp(format, "d") == 0)
1227                 archiveFormat = archDirectory;
1228         else if (pg_strcasecmp(format, "directory") == 0)
1229                 archiveFormat = archDirectory;
1230         else if (pg_strcasecmp(format, "p") == 0)
1231                 archiveFormat = archNull;
1232         else if (pg_strcasecmp(format, "plain") == 0)
1233                 archiveFormat = archNull;
1234         else if (pg_strcasecmp(format, "t") == 0)
1235                 archiveFormat = archTar;
1236         else if (pg_strcasecmp(format, "tar") == 0)
1237                 archiveFormat = archTar;
1238         else
1239                 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
1240         return archiveFormat;
1241 }
1242
1243 /*
1244  * Find the OIDs of all schemas matching the given list of patterns,
1245  * and append them to the given OID list.
1246  */
1247 static void
1248 expand_schema_name_patterns(Archive *fout,
1249                                                         SimpleStringList *patterns,
1250                                                         SimpleOidList *oids,
1251                                                         bool strict_names)
1252 {
1253         PQExpBuffer query;
1254         PGresult   *res;
1255         SimpleStringListCell *cell;
1256         int                     i;
1257
1258         if (patterns->head == NULL)
1259                 return;                                 /* nothing to do */
1260
1261         query = createPQExpBuffer();
1262
1263         /*
1264          * The loop below runs multiple SELECTs might sometimes result in
1265          * duplicate entries in the OID list, but we don't care.
1266          */
1267
1268         for (cell = patterns->head; cell; cell = cell->next)
1269         {
1270                 appendPQExpBuffer(query,
1271                                                   "SELECT oid FROM pg_catalog.pg_namespace n\n");
1272                 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1273                                                           false, NULL, "n.nspname", NULL, NULL);
1274
1275                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1276                 if (strict_names && PQntuples(res) == 0)
1277                         exit_horribly(NULL, "no matching schemas were found for pattern \"%s\"\n", cell->val);
1278
1279                 for (i = 0; i < PQntuples(res); i++)
1280                 {
1281                         simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1282                 }
1283
1284                 PQclear(res);
1285                 resetPQExpBuffer(query);
1286         }
1287
1288         destroyPQExpBuffer(query);
1289 }
1290
1291 /*
1292  * Find the OIDs of all tables matching the given list of patterns,
1293  * and append them to the given OID list.
1294  */
1295 static void
1296 expand_table_name_patterns(Archive *fout,
1297                                                    SimpleStringList *patterns, SimpleOidList *oids,
1298                                                    bool strict_names)
1299 {
1300         PQExpBuffer query;
1301         PGresult   *res;
1302         SimpleStringListCell *cell;
1303         int                     i;
1304
1305         if (patterns->head == NULL)
1306                 return;                                 /* nothing to do */
1307
1308         query = createPQExpBuffer();
1309
1310         /*
1311          * this might sometimes result in duplicate entries in the OID list, but
1312          * we don't care.
1313          */
1314
1315         for (cell = patterns->head; cell; cell = cell->next)
1316         {
1317                 /*
1318                  * Query must remain ABSOLUTELY devoid of unqualified names.  This
1319                  * would be unnecessary given a pg_table_is_visible() variant taking a
1320                  * search_path argument.
1321                  */
1322                 appendPQExpBuffer(query,
1323                                                   "SELECT c.oid"
1324                                                   "\nFROM pg_catalog.pg_class c"
1325                                                   "\n     LEFT JOIN pg_catalog.pg_namespace n"
1326                                                   "\n     ON n.oid OPERATOR(pg_catalog.=) c.relnamespace"
1327                                                   "\nWHERE c.relkind OPERATOR(pg_catalog.=) ANY"
1328                                                   "\n    (array['%c', '%c', '%c', '%c', '%c', '%c'])\n",
1329                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1330                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
1331                                                   RELKIND_PARTITIONED_TABLE);
1332                 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1333                                                           false, "n.nspname", "c.relname", NULL,
1334                                                           "pg_catalog.pg_table_is_visible(c.oid)");
1335
1336                 ExecuteSqlStatement(fout, "RESET search_path");
1337                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1338                 PQclear(ExecuteSqlQueryForSingleRow(fout,
1339                                                                                         ALWAYS_SECURE_SEARCH_PATH_SQL));
1340                 if (strict_names && PQntuples(res) == 0)
1341                         exit_horribly(NULL, "no matching tables were found for pattern \"%s\"\n", cell->val);
1342
1343                 for (i = 0; i < PQntuples(res); i++)
1344                 {
1345                         simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1346                 }
1347
1348                 PQclear(res);
1349                 resetPQExpBuffer(query);
1350         }
1351
1352         destroyPQExpBuffer(query);
1353 }
1354
1355 /*
1356  * checkExtensionMembership
1357  *              Determine whether object is an extension member, and if so,
1358  *              record an appropriate dependency and set the object's dump flag.
1359  *
1360  * It's important to call this for each object that could be an extension
1361  * member.  Generally, we integrate this with determining the object's
1362  * to-be-dumped-ness, since extension membership overrides other rules for that.
1363  *
1364  * Returns true if object is an extension member, else false.
1365  */
1366 static bool
1367 checkExtensionMembership(DumpableObject *dobj, Archive *fout)
1368 {
1369         ExtensionInfo *ext = findOwningExtension(dobj->catId);
1370
1371         if (ext == NULL)
1372                 return false;
1373
1374         dobj->ext_member = true;
1375
1376         /* Record dependency so that getDependencies needn't deal with that */
1377         addObjectDependency(dobj, ext->dobj.dumpId);
1378
1379         /*
1380          * In 9.6 and above, mark the member object to have any non-initial ACL,
1381          * policies, and security labels dumped.
1382          *
1383          * Note that any initial ACLs (see pg_init_privs) will be removed when we
1384          * extract the information about the object.  We don't provide support for
1385          * initial policies and security labels and it seems unlikely for those to
1386          * ever exist, but we may have to revisit this later.
1387          *
1388          * Prior to 9.6, we do not include any extension member components.
1389          *
1390          * In binary upgrades, we still dump all components of the members
1391          * individually, since the idea is to exactly reproduce the database
1392          * contents rather than replace the extension contents with something
1393          * different.
1394          */
1395         if (fout->dopt->binary_upgrade)
1396                 dobj->dump = ext->dobj.dump;
1397         else
1398         {
1399                 if (fout->remoteVersion < 90600)
1400                         dobj->dump = DUMP_COMPONENT_NONE;
1401                 else
1402                         dobj->dump = ext->dobj.dump_contains & (DUMP_COMPONENT_ACL |
1403                                                                                                         DUMP_COMPONENT_SECLABEL |
1404                                                                                                         DUMP_COMPONENT_POLICY);
1405         }
1406
1407         return true;
1408 }
1409
1410 /*
1411  * selectDumpableNamespace: policy-setting subroutine
1412  *              Mark a namespace as to be dumped or not
1413  */
1414 static void
1415 selectDumpableNamespace(NamespaceInfo *nsinfo, Archive *fout)
1416 {
1417         /*
1418          * If specific tables are being dumped, do not dump any complete
1419          * namespaces. If specific namespaces are being dumped, dump just those
1420          * namespaces. Otherwise, dump all non-system namespaces.
1421          */
1422         if (table_include_oids.head != NULL)
1423                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1424         else if (schema_include_oids.head != NULL)
1425                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump =
1426                         simple_oid_list_member(&schema_include_oids,
1427                                                                    nsinfo->dobj.catId.oid) ?
1428                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1429         else if (fout->remoteVersion >= 90600 &&
1430                          strcmp(nsinfo->dobj.name, "pg_catalog") == 0)
1431         {
1432                 /*
1433                  * In 9.6 and above, we dump out any ACLs defined in pg_catalog, if
1434                  * they are interesting (and not the original ACLs which were set at
1435                  * initdb time, see pg_init_privs).
1436                  */
1437                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1438         }
1439         else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1440                          strcmp(nsinfo->dobj.name, "information_schema") == 0)
1441         {
1442                 /* Other system schemas don't get dumped */
1443                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1444         }
1445         else if (strcmp(nsinfo->dobj.name, "public") == 0)
1446         {
1447                 /*
1448                  * The public schema is a strange beast that sits in a sort of
1449                  * no-mans-land between being a system object and a user object.  We
1450                  * don't want to dump creation or comment commands for it, because
1451                  * that complicates matters for non-superuser use of pg_dump.  But we
1452                  * should dump any ACL changes that have occurred for it, and of
1453                  * course we should dump contained objects.
1454                  */
1455                 nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1456                 nsinfo->dobj.dump_contains = DUMP_COMPONENT_ALL;
1457         }
1458         else
1459                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ALL;
1460
1461         /*
1462          * In any case, a namespace can be excluded by an exclusion switch
1463          */
1464         if (nsinfo->dobj.dump_contains &&
1465                 simple_oid_list_member(&schema_exclude_oids,
1466                                                            nsinfo->dobj.catId.oid))
1467                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1468
1469         /*
1470          * If the schema belongs to an extension, allow extension membership to
1471          * override the dump decision for the schema itself.  However, this does
1472          * not change dump_contains, so this won't change what we do with objects
1473          * within the schema.  (If they belong to the extension, they'll get
1474          * suppressed by it, otherwise not.)
1475          */
1476         (void) checkExtensionMembership(&nsinfo->dobj, fout);
1477 }
1478
1479 /*
1480  * selectDumpableTable: policy-setting subroutine
1481  *              Mark a table as to be dumped or not
1482  */
1483 static void
1484 selectDumpableTable(TableInfo *tbinfo, Archive *fout)
1485 {
1486         if (checkExtensionMembership(&tbinfo->dobj, fout))
1487                 return;                                 /* extension membership overrides all else */
1488
1489         /*
1490          * If specific tables are being dumped, dump just those tables; else, dump
1491          * according to the parent namespace's dump flag.
1492          */
1493         if (table_include_oids.head != NULL)
1494                 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1495                                                                                                    tbinfo->dobj.catId.oid) ?
1496                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1497         else
1498                 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump_contains;
1499
1500         /*
1501          * In any case, a table can be excluded by an exclusion switch
1502          */
1503         if (tbinfo->dobj.dump &&
1504                 simple_oid_list_member(&table_exclude_oids,
1505                                                            tbinfo->dobj.catId.oid))
1506                 tbinfo->dobj.dump = DUMP_COMPONENT_NONE;
1507 }
1508
1509 /*
1510  * selectDumpableType: policy-setting subroutine
1511  *              Mark a type as to be dumped or not
1512  *
1513  * If it's a table's rowtype or an autogenerated array type, we also apply a
1514  * special type code to facilitate sorting into the desired order.  (We don't
1515  * want to consider those to be ordinary types because that would bring tables
1516  * up into the datatype part of the dump order.)  We still set the object's
1517  * dump flag; that's not going to cause the dummy type to be dumped, but we
1518  * need it so that casts involving such types will be dumped correctly -- see
1519  * dumpCast.  This means the flag should be set the same as for the underlying
1520  * object (the table or base type).
1521  */
1522 static void
1523 selectDumpableType(TypeInfo *tyinfo, Archive *fout)
1524 {
1525         /* skip complex types, except for standalone composite types */
1526         if (OidIsValid(tyinfo->typrelid) &&
1527                 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1528         {
1529                 TableInfo  *tytable = findTableByOid(tyinfo->typrelid);
1530
1531                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1532                 if (tytable != NULL)
1533                         tyinfo->dobj.dump = tytable->dobj.dump;
1534                 else
1535                         tyinfo->dobj.dump = DUMP_COMPONENT_NONE;
1536                 return;
1537         }
1538
1539         /* skip auto-generated array types */
1540         if (tyinfo->isArray)
1541         {
1542                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1543
1544                 /*
1545                  * Fall through to set the dump flag; we assume that the subsequent
1546                  * rules will do the same thing as they would for the array's base
1547                  * type.  (We cannot reliably look up the base type here, since
1548                  * getTypes may not have processed it yet.)
1549                  */
1550         }
1551
1552         if (checkExtensionMembership(&tyinfo->dobj, fout))
1553                 return;                                 /* extension membership overrides all else */
1554
1555         /* Dump based on if the contents of the namespace are being dumped */
1556         tyinfo->dobj.dump = tyinfo->dobj.namespace->dobj.dump_contains;
1557 }
1558
1559 /*
1560  * selectDumpableDefaultACL: policy-setting subroutine
1561  *              Mark a default ACL as to be dumped or not
1562  *
1563  * For per-schema default ACLs, dump if the schema is to be dumped.
1564  * Otherwise dump if we are dumping "everything".  Note that dataOnly
1565  * and aclsSkip are checked separately.
1566  */
1567 static void
1568 selectDumpableDefaultACL(DefaultACLInfo *dinfo, DumpOptions *dopt)
1569 {
1570         /* Default ACLs can't be extension members */
1571
1572         if (dinfo->dobj.namespace)
1573                 /* default ACLs are considered part of the namespace */
1574                 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump_contains;
1575         else
1576                 dinfo->dobj.dump = dopt->include_everything ?
1577                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1578 }
1579
1580 /*
1581  * selectDumpableCast: policy-setting subroutine
1582  *              Mark a cast as to be dumped or not
1583  *
1584  * Casts do not belong to any particular namespace (since they haven't got
1585  * names), nor do they have identifiable owners.  To distinguish user-defined
1586  * casts from built-in ones, we must resort to checking whether the cast's
1587  * OID is in the range reserved for initdb.
1588  */
1589 static void
1590 selectDumpableCast(CastInfo *cast, Archive *fout)
1591 {
1592         if (checkExtensionMembership(&cast->dobj, fout))
1593                 return;                                 /* extension membership overrides all else */
1594
1595         /*
1596          * This would be DUMP_COMPONENT_ACL for from-initdb casts, but they do not
1597          * support ACLs currently.
1598          */
1599         if (cast->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1600                 cast->dobj.dump = DUMP_COMPONENT_NONE;
1601         else
1602                 cast->dobj.dump = fout->dopt->include_everything ?
1603                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1604 }
1605
1606 /*
1607  * selectDumpableProcLang: policy-setting subroutine
1608  *              Mark a procedural language as to be dumped or not
1609  *
1610  * Procedural languages do not belong to any particular namespace.  To
1611  * identify built-in languages, we must resort to checking whether the
1612  * language's OID is in the range reserved for initdb.
1613  */
1614 static void
1615 selectDumpableProcLang(ProcLangInfo *plang, Archive *fout)
1616 {
1617         if (checkExtensionMembership(&plang->dobj, fout))
1618                 return;                                 /* extension membership overrides all else */
1619
1620         /*
1621          * Only include procedural languages when we are dumping everything.
1622          *
1623          * For from-initdb procedural languages, only include ACLs, as we do for
1624          * the pg_catalog namespace.  We need this because procedural languages do
1625          * not live in any namespace.
1626          */
1627         if (!fout->dopt->include_everything)
1628                 plang->dobj.dump = DUMP_COMPONENT_NONE;
1629         else
1630         {
1631                 if (plang->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1632                         plang->dobj.dump = fout->remoteVersion < 90600 ?
1633                                 DUMP_COMPONENT_NONE : DUMP_COMPONENT_ACL;
1634                 else
1635                         plang->dobj.dump = DUMP_COMPONENT_ALL;
1636         }
1637 }
1638
1639 /*
1640  * selectDumpableAccessMethod: policy-setting subroutine
1641  *              Mark an access method as to be dumped or not
1642  *
1643  * Access methods do not belong to any particular namespace.  To identify
1644  * built-in access methods, we must resort to checking whether the
1645  * method's OID is in the range reserved for initdb.
1646  */
1647 static void
1648 selectDumpableAccessMethod(AccessMethodInfo *method, Archive *fout)
1649 {
1650         if (checkExtensionMembership(&method->dobj, fout))
1651                 return;                                 /* extension membership overrides all else */
1652
1653         /*
1654          * This would be DUMP_COMPONENT_ACL for from-initdb access methods, but
1655          * they do not support ACLs currently.
1656          */
1657         if (method->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1658                 method->dobj.dump = DUMP_COMPONENT_NONE;
1659         else
1660                 method->dobj.dump = fout->dopt->include_everything ?
1661                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1662 }
1663
1664 /*
1665  * selectDumpableExtension: policy-setting subroutine
1666  *              Mark an extension as to be dumped or not
1667  *
1668  * Built-in extensions should be skipped except for checking ACLs, since we
1669  * assume those will already be installed in the target database.  We identify
1670  * such extensions by their having OIDs in the range reserved for initdb.
1671  * We dump all user-added extensions by default, or none of them if
1672  * include_everything is false (i.e., a --schema or --table switch was given).
1673  */
1674 static void
1675 selectDumpableExtension(ExtensionInfo *extinfo, DumpOptions *dopt)
1676 {
1677         /*
1678          * Use DUMP_COMPONENT_ACL for built-in extensions, to allow users to
1679          * change permissions on their member objects, if they wish to, and have
1680          * those changes preserved.
1681          */
1682         if (extinfo->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1683                 extinfo->dobj.dump = extinfo->dobj.dump_contains = DUMP_COMPONENT_ACL;
1684         else
1685                 extinfo->dobj.dump = extinfo->dobj.dump_contains =
1686                         dopt->include_everything ? DUMP_COMPONENT_ALL :
1687                         DUMP_COMPONENT_NONE;
1688 }
1689
1690 /*
1691  * selectDumpablePublicationTable: policy-setting subroutine
1692  *              Mark a publication table as to be dumped or not
1693  *
1694  * Publication tables have schemas, but those are ignored in decision making,
1695  * because publications are only dumped when we are dumping everything.
1696  */
1697 static void
1698 selectDumpablePublicationTable(DumpableObject *dobj, Archive *fout)
1699 {
1700         if (checkExtensionMembership(dobj, fout))
1701                 return;                                 /* extension membership overrides all else */
1702
1703         dobj->dump = fout->dopt->include_everything ?
1704                 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1705 }
1706
1707 /*
1708  * selectDumpableObject: policy-setting subroutine
1709  *              Mark a generic dumpable object as to be dumped or not
1710  *
1711  * Use this only for object types without a special-case routine above.
1712  */
1713 static void
1714 selectDumpableObject(DumpableObject *dobj, Archive *fout)
1715 {
1716         if (checkExtensionMembership(dobj, fout))
1717                 return;                                 /* extension membership overrides all else */
1718
1719         /*
1720          * Default policy is to dump if parent namespace is dumpable, or for
1721          * non-namespace-associated items, dump if we're dumping "everything".
1722          */
1723         if (dobj->namespace)
1724                 dobj->dump = dobj->namespace->dobj.dump_contains;
1725         else
1726                 dobj->dump = fout->dopt->include_everything ?
1727                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1728 }
1729
1730 /*
1731  *      Dump a table's contents for loading using the COPY command
1732  *      - this routine is called by the Archiver when it wants the table
1733  *        to be dumped.
1734  */
1735
1736 static int
1737 dumpTableData_copy(Archive *fout, void *dcontext)
1738 {
1739         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1740         TableInfo  *tbinfo = tdinfo->tdtable;
1741         const char *classname = tbinfo->dobj.name;
1742         const bool      hasoids = tbinfo->hasoids;
1743         const bool      oids = tdinfo->oids;
1744         PQExpBuffer q = createPQExpBuffer();
1745
1746         /*
1747          * Note: can't use getThreadLocalPQExpBuffer() here, we're calling fmtId
1748          * which uses it already.
1749          */
1750         PQExpBuffer clistBuf = createPQExpBuffer();
1751         PGconn     *conn = GetConnection(fout);
1752         PGresult   *res;
1753         int                     ret;
1754         char       *copybuf;
1755         const char *column_list;
1756
1757         if (g_verbose)
1758                 write_msg(NULL, "dumping contents of table \"%s.%s\"\n",
1759                                   tbinfo->dobj.namespace->dobj.name, classname);
1760
1761         /*
1762          * Specify the column list explicitly so that we have no possibility of
1763          * retrieving data in the wrong column order.  (The default column
1764          * ordering of COPY will not be what we want in certain corner cases
1765          * involving ADD COLUMN and inheritance.)
1766          */
1767         column_list = fmtCopyColumnList(tbinfo, clistBuf);
1768
1769         if (oids && hasoids)
1770         {
1771                 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1772                                                   fmtQualifiedDumpable(tbinfo),
1773                                                   column_list);
1774         }
1775         else if (tdinfo->filtercond)
1776         {
1777                 /* Note: this syntax is only supported in 8.2 and up */
1778                 appendPQExpBufferStr(q, "COPY (SELECT ");
1779                 /* klugery to get rid of parens in column list */
1780                 if (strlen(column_list) > 2)
1781                 {
1782                         appendPQExpBufferStr(q, column_list + 1);
1783                         q->data[q->len - 1] = ' ';
1784                 }
1785                 else
1786                         appendPQExpBufferStr(q, "* ");
1787                 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1788                                                   fmtQualifiedDumpable(tbinfo),
1789                                                   tdinfo->filtercond);
1790         }
1791         else
1792         {
1793                 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1794                                                   fmtQualifiedDumpable(tbinfo),
1795                                                   column_list);
1796         }
1797         res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1798         PQclear(res);
1799         destroyPQExpBuffer(clistBuf);
1800
1801         for (;;)
1802         {
1803                 ret = PQgetCopyData(conn, &copybuf, 0);
1804
1805                 if (ret < 0)
1806                         break;                          /* done or error */
1807
1808                 if (copybuf)
1809                 {
1810                         WriteData(fout, copybuf, ret);
1811                         PQfreemem(copybuf);
1812                 }
1813
1814                 /* ----------
1815                  * THROTTLE:
1816                  *
1817                  * There was considerable discussion in late July, 2000 regarding
1818                  * slowing down pg_dump when backing up large tables. Users with both
1819                  * slow & fast (multi-processor) machines experienced performance
1820                  * degradation when doing a backup.
1821                  *
1822                  * Initial attempts based on sleeping for a number of ms for each ms
1823                  * of work were deemed too complex, then a simple 'sleep in each loop'
1824                  * implementation was suggested. The latter failed because the loop
1825                  * was too tight. Finally, the following was implemented:
1826                  *
1827                  * If throttle is non-zero, then
1828                  *              See how long since the last sleep.
1829                  *              Work out how long to sleep (based on ratio).
1830                  *              If sleep is more than 100ms, then
1831                  *                      sleep
1832                  *                      reset timer
1833                  *              EndIf
1834                  * EndIf
1835                  *
1836                  * where the throttle value was the number of ms to sleep per ms of
1837                  * work. The calculation was done in each loop.
1838                  *
1839                  * Most of the hard work is done in the backend, and this solution
1840                  * still did not work particularly well: on slow machines, the ratio
1841                  * was 50:1, and on medium paced machines, 1:1, and on fast
1842                  * multi-processor machines, it had little or no effect, for reasons
1843                  * that were unclear.
1844                  *
1845                  * Further discussion ensued, and the proposal was dropped.
1846                  *
1847                  * For those people who want this feature, it can be implemented using
1848                  * gettimeofday in each loop, calculating the time since last sleep,
1849                  * multiplying that by the sleep ratio, then if the result is more
1850                  * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1851                  * function to sleep for a subsecond period ie.
1852                  *
1853                  * select(0, NULL, NULL, NULL, &tvi);
1854                  *
1855                  * This will return after the interval specified in the structure tvi.
1856                  * Finally, call gettimeofday again to save the 'last sleep time'.
1857                  * ----------
1858                  */
1859         }
1860         archprintf(fout, "\\.\n\n\n");
1861
1862         if (ret == -2)
1863         {
1864                 /* copy data transfer failed */
1865                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1866                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1867                 write_msg(NULL, "The command was: %s\n", q->data);
1868                 exit_nicely(1);
1869         }
1870
1871         /* Check command status and return to normal libpq state */
1872         res = PQgetResult(conn);
1873         if (PQresultStatus(res) != PGRES_COMMAND_OK)
1874         {
1875                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1876                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1877                 write_msg(NULL, "The command was: %s\n", q->data);
1878                 exit_nicely(1);
1879         }
1880         PQclear(res);
1881
1882         /* Do this to ensure we've pumped libpq back to idle state */
1883         if (PQgetResult(conn) != NULL)
1884                 write_msg(NULL, "WARNING: unexpected extra results during COPY of table \"%s\"\n",
1885                                   classname);
1886
1887         destroyPQExpBuffer(q);
1888         return 1;
1889 }
1890
1891 /*
1892  * Dump table data using INSERT commands.
1893  *
1894  * Caution: when we restore from an archive file direct to database, the
1895  * INSERT commands emitted by this function have to be parsed by
1896  * pg_backup_db.c's ExecuteSimpleCommands(), which will not handle comments,
1897  * E'' strings, or dollar-quoted strings.  So don't emit anything like that.
1898  */
1899 static int
1900 dumpTableData_insert(Archive *fout, void *dcontext)
1901 {
1902         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1903         TableInfo  *tbinfo = tdinfo->tdtable;
1904         DumpOptions *dopt = fout->dopt;
1905         PQExpBuffer q = createPQExpBuffer();
1906         PQExpBuffer insertStmt = NULL;
1907         PGresult   *res;
1908         int                     tuple;
1909         int                     nfields;
1910         int                     field;
1911
1912         appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1913                                           "SELECT * FROM ONLY %s",
1914                                           fmtQualifiedDumpable(tbinfo));
1915         if (tdinfo->filtercond)
1916                 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1917
1918         ExecuteSqlStatement(fout, q->data);
1919
1920         while (1)
1921         {
1922                 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1923                                                           PGRES_TUPLES_OK);
1924                 nfields = PQnfields(res);
1925                 for (tuple = 0; tuple < PQntuples(res); tuple++)
1926                 {
1927                         /*
1928                          * First time through, we build as much of the INSERT statement as
1929                          * possible in "insertStmt", which we can then just print for each
1930                          * line. If the table happens to have zero columns then this will
1931                          * be a complete statement, otherwise it will end in "VALUES(" and
1932                          * be ready to have the row's column values appended.
1933                          */
1934                         if (insertStmt == NULL)
1935                         {
1936                                 TableInfo  *targettab;
1937
1938                                 insertStmt = createPQExpBuffer();
1939
1940                                 /*
1941                                  * When load-via-partition-root is set, get the root table
1942                                  * name for the partition table, so that we can reload data
1943                                  * through the root table.
1944                                  */
1945                                 if (dopt->load_via_partition_root && tbinfo->ispartition)
1946                                         targettab = getRootTableInfo(tbinfo);
1947                                 else
1948                                         targettab = tbinfo;
1949
1950                                 appendPQExpBuffer(insertStmt, "INSERT INTO %s ",
1951                                                                   fmtQualifiedDumpable(targettab));
1952
1953                                 /* corner case for zero-column table */
1954                                 if (nfields == 0)
1955                                 {
1956                                         appendPQExpBufferStr(insertStmt, "DEFAULT VALUES;\n");
1957                                 }
1958                                 else
1959                                 {
1960                                         /* append the list of column names if required */
1961                                         if (dopt->column_inserts)
1962                                         {
1963                                                 appendPQExpBufferChar(insertStmt, '(');
1964                                                 for (field = 0; field < nfields; field++)
1965                                                 {
1966                                                         if (field > 0)
1967                                                                 appendPQExpBufferStr(insertStmt, ", ");
1968                                                         appendPQExpBufferStr(insertStmt,
1969                                                                                                  fmtId(PQfname(res, field)));
1970                                                 }
1971                                                 appendPQExpBufferStr(insertStmt, ") ");
1972                                         }
1973
1974                                         if (tbinfo->needs_override)
1975                                                 appendPQExpBufferStr(insertStmt, "OVERRIDING SYSTEM VALUE ");
1976
1977                                         appendPQExpBufferStr(insertStmt, "VALUES (");
1978                                 }
1979                         }
1980
1981                         archputs(insertStmt->data, fout);
1982
1983                         /* if it is zero-column table then we're done */
1984                         if (nfields == 0)
1985                                 continue;
1986
1987                         for (field = 0; field < nfields; field++)
1988                         {
1989                                 if (field > 0)
1990                                         archputs(", ", fout);
1991                                 if (PQgetisnull(res, tuple, field))
1992                                 {
1993                                         archputs("NULL", fout);
1994                                         continue;
1995                                 }
1996
1997                                 /* XXX This code is partially duplicated in ruleutils.c */
1998                                 switch (PQftype(res, field))
1999                                 {
2000                                         case INT2OID:
2001                                         case INT4OID:
2002                                         case INT8OID:
2003                                         case OIDOID:
2004                                         case FLOAT4OID:
2005                                         case FLOAT8OID:
2006                                         case NUMERICOID:
2007                                                 {
2008                                                         /*
2009                                                          * These types are printed without quotes unless
2010                                                          * they contain values that aren't accepted by the
2011                                                          * scanner unquoted (e.g., 'NaN').  Note that
2012                                                          * strtod() and friends might accept NaN, so we
2013                                                          * can't use that to test.
2014                                                          *
2015                                                          * In reality we only need to defend against
2016                                                          * infinity and NaN, so we need not get too crazy
2017                                                          * about pattern matching here.
2018                                                          */
2019                                                         const char *s = PQgetvalue(res, tuple, field);
2020
2021                                                         if (strspn(s, "0123456789 +-eE.") == strlen(s))
2022                                                                 archputs(s, fout);
2023                                                         else
2024                                                                 archprintf(fout, "'%s'", s);
2025                                                 }
2026                                                 break;
2027
2028                                         case BITOID:
2029                                         case VARBITOID:
2030                                                 archprintf(fout, "B'%s'",
2031                                                                    PQgetvalue(res, tuple, field));
2032                                                 break;
2033
2034                                         case BOOLOID:
2035                                                 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
2036                                                         archputs("true", fout);
2037                                                 else
2038                                                         archputs("false", fout);
2039                                                 break;
2040
2041                                         default:
2042                                                 /* All other types are printed as string literals. */
2043                                                 resetPQExpBuffer(q);
2044                                                 appendStringLiteralAH(q,
2045                                                                                           PQgetvalue(res, tuple, field),
2046                                                                                           fout);
2047                                                 archputs(q->data, fout);
2048                                                 break;
2049                                 }
2050                         }
2051                         archputs(");\n", fout);
2052                 }
2053
2054                 if (PQntuples(res) <= 0)
2055                 {
2056                         PQclear(res);
2057                         break;
2058                 }
2059                 PQclear(res);
2060         }
2061
2062         archputs("\n\n", fout);
2063
2064         ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
2065
2066         destroyPQExpBuffer(q);
2067         if (insertStmt != NULL)
2068                 destroyPQExpBuffer(insertStmt);
2069
2070         return 1;
2071 }
2072
2073 /*
2074  * getRootTableInfo:
2075  *     get the root TableInfo for the given partition table.
2076  */
2077 static TableInfo *
2078 getRootTableInfo(TableInfo *tbinfo)
2079 {
2080         TableInfo  *parentTbinfo;
2081
2082         Assert(tbinfo->ispartition);
2083         Assert(tbinfo->numParents == 1);
2084
2085         parentTbinfo = tbinfo->parents[0];
2086         while (parentTbinfo->ispartition)
2087         {
2088                 Assert(parentTbinfo->numParents == 1);
2089                 parentTbinfo = parentTbinfo->parents[0];
2090         }
2091
2092         return parentTbinfo;
2093 }
2094
2095 /*
2096  * dumpTableData -
2097  *        dump the contents of a single table
2098  *
2099  * Actually, this just makes an ArchiveEntry for the table contents.
2100  */
2101 static void
2102 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
2103 {
2104         DumpOptions *dopt = fout->dopt;
2105         TableInfo  *tbinfo = tdinfo->tdtable;
2106         PQExpBuffer copyBuf = createPQExpBuffer();
2107         PQExpBuffer clistBuf = createPQExpBuffer();
2108         DataDumperPtr dumpFn;
2109         char       *copyStmt;
2110         const char *copyFrom;
2111
2112         if (!dopt->dump_inserts)
2113         {
2114                 /* Dump/restore using COPY */
2115                 dumpFn = dumpTableData_copy;
2116
2117                 /*
2118                  * When load-via-partition-root is set, get the root table name for
2119                  * the partition table, so that we can reload data through the root
2120                  * table.
2121                  */
2122                 if (dopt->load_via_partition_root && tbinfo->ispartition)
2123                 {
2124                         TableInfo  *parentTbinfo;
2125
2126                         parentTbinfo = getRootTableInfo(tbinfo);
2127                         copyFrom = fmtQualifiedDumpable(parentTbinfo);
2128                 }
2129                 else
2130                         copyFrom = fmtQualifiedDumpable(tbinfo);
2131
2132                 /* must use 2 steps here 'cause fmtId is nonreentrant */
2133                 appendPQExpBuffer(copyBuf, "COPY %s ",
2134                                                   copyFrom);
2135                 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
2136                                                   fmtCopyColumnList(tbinfo, clistBuf),
2137                                                   (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
2138                 copyStmt = copyBuf->data;
2139         }
2140         else
2141         {
2142                 /* Restore using INSERT */
2143                 dumpFn = dumpTableData_insert;
2144                 copyStmt = NULL;
2145         }
2146
2147         /*
2148          * Note: although the TableDataInfo is a full DumpableObject, we treat its
2149          * dependency on its table as "special" and pass it to ArchiveEntry now.
2150          * See comments for BuildArchiveDependencies.
2151          */
2152         if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2153                 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
2154                                          tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
2155                                          NULL, tbinfo->rolname,
2156                                          false, "TABLE DATA", SECTION_DATA,
2157                                          "", "", copyStmt,
2158                                          &(tbinfo->dobj.dumpId), 1,
2159                                          dumpFn, tdinfo);
2160
2161         destroyPQExpBuffer(copyBuf);
2162         destroyPQExpBuffer(clistBuf);
2163 }
2164
2165 /*
2166  * refreshMatViewData -
2167  *        load or refresh the contents of a single materialized view
2168  *
2169  * Actually, this just makes an ArchiveEntry for the REFRESH MATERIALIZED VIEW
2170  * statement.
2171  */
2172 static void
2173 refreshMatViewData(Archive *fout, TableDataInfo *tdinfo)
2174 {
2175         TableInfo  *tbinfo = tdinfo->tdtable;
2176         PQExpBuffer q;
2177
2178         /* If the materialized view is not flagged as populated, skip this. */
2179         if (!tbinfo->relispopulated)
2180                 return;
2181
2182         q = createPQExpBuffer();
2183
2184         appendPQExpBuffer(q, "REFRESH MATERIALIZED VIEW %s;\n",
2185                                           fmtQualifiedDumpable(tbinfo));
2186
2187         if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2188                 ArchiveEntry(fout,
2189                                          tdinfo->dobj.catId,    /* catalog ID */
2190                                          tdinfo->dobj.dumpId,   /* dump ID */
2191                                          tbinfo->dobj.name, /* Name */
2192                                          tbinfo->dobj.namespace->dobj.name, /* Namespace */
2193                                          NULL,          /* Tablespace */
2194                                          tbinfo->rolname,       /* Owner */
2195                                          false,         /* with oids */
2196                                          "MATERIALIZED VIEW DATA",      /* Desc */
2197                                          SECTION_POST_DATA, /* Section */
2198                                          q->data,       /* Create */
2199                                          "",            /* Del */
2200                                          NULL,          /* Copy */
2201                                          tdinfo->dobj.dependencies, /* Deps */
2202                                          tdinfo->dobj.nDeps,    /* # Deps */
2203                                          NULL,          /* Dumper */
2204                                          NULL);         /* Dumper Arg */
2205
2206         destroyPQExpBuffer(q);
2207 }
2208
2209 /*
2210  * getTableData -
2211  *        set up dumpable objects representing the contents of tables
2212  */
2213 static void
2214 getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, bool oids, char relkind)
2215 {
2216         int                     i;
2217
2218         for (i = 0; i < numTables; i++)
2219         {
2220                 if (tblinfo[i].dobj.dump & DUMP_COMPONENT_DATA &&
2221                         (!relkind || tblinfo[i].relkind == relkind))
2222                         makeTableDataInfo(dopt, &(tblinfo[i]), oids);
2223         }
2224 }
2225
2226 /*
2227  * Make a dumpable object for the data of this specific table
2228  *
2229  * Note: we make a TableDataInfo if and only if we are going to dump the
2230  * table data; the "dump" flag in such objects isn't used.
2231  */
2232 static void
2233 makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo, bool oids)
2234 {
2235         TableDataInfo *tdinfo;
2236
2237         /*
2238          * Nothing to do if we already decided to dump the table.  This will
2239          * happen for "config" tables.
2240          */
2241         if (tbinfo->dataObj != NULL)
2242                 return;
2243
2244         /* Skip VIEWs (no data to dump) */
2245         if (tbinfo->relkind == RELKIND_VIEW)
2246                 return;
2247         /* Skip FOREIGN TABLEs (no data to dump) */
2248         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
2249                 return;
2250         /* Skip partitioned tables (data in partitions) */
2251         if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
2252                 return;
2253
2254         /* Don't dump data in unlogged tables, if so requested */
2255         if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
2256                 dopt->no_unlogged_table_data)
2257                 return;
2258
2259         /* Check that the data is not explicitly excluded */
2260         if (simple_oid_list_member(&tabledata_exclude_oids,
2261                                                            tbinfo->dobj.catId.oid))
2262                 return;
2263
2264         /* OK, let's dump it */
2265         tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
2266
2267         if (tbinfo->relkind == RELKIND_MATVIEW)
2268                 tdinfo->dobj.objType = DO_REFRESH_MATVIEW;
2269         else if (tbinfo->relkind == RELKIND_SEQUENCE)
2270                 tdinfo->dobj.objType = DO_SEQUENCE_SET;
2271         else
2272                 tdinfo->dobj.objType = DO_TABLE_DATA;
2273
2274         /*
2275          * Note: use tableoid 0 so that this object won't be mistaken for
2276          * something that pg_depend entries apply to.
2277          */
2278         tdinfo->dobj.catId.tableoid = 0;
2279         tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
2280         AssignDumpId(&tdinfo->dobj);
2281         tdinfo->dobj.name = tbinfo->dobj.name;
2282         tdinfo->dobj.namespace = tbinfo->dobj.namespace;
2283         tdinfo->tdtable = tbinfo;
2284         tdinfo->oids = oids;
2285         tdinfo->filtercond = NULL;      /* might get set later */
2286         addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
2287
2288         tbinfo->dataObj = tdinfo;
2289 }
2290
2291 /*
2292  * The refresh for a materialized view must be dependent on the refresh for
2293  * any materialized view that this one is dependent on.
2294  *
2295  * This must be called after all the objects are created, but before they are
2296  * sorted.
2297  */
2298 static void
2299 buildMatViewRefreshDependencies(Archive *fout)
2300 {
2301         PQExpBuffer query;
2302         PGresult   *res;
2303         int                     ntups,
2304                                 i;
2305         int                     i_classid,
2306                                 i_objid,
2307                                 i_refobjid;
2308
2309         /* No Mat Views before 9.3. */
2310         if (fout->remoteVersion < 90300)
2311                 return;
2312
2313         query = createPQExpBuffer();
2314
2315         appendPQExpBufferStr(query, "WITH RECURSIVE w AS "
2316                                                  "( "
2317                                                  "SELECT d1.objid, d2.refobjid, c2.relkind AS refrelkind "
2318                                                  "FROM pg_depend d1 "
2319                                                  "JOIN pg_class c1 ON c1.oid = d1.objid "
2320                                                  "AND c1.relkind = " CppAsString2(RELKIND_MATVIEW)
2321                                                  " JOIN pg_rewrite r1 ON r1.ev_class = d1.objid "
2322                                                  "JOIN pg_depend d2 ON d2.classid = 'pg_rewrite'::regclass "
2323                                                  "AND d2.objid = r1.oid "
2324                                                  "AND d2.refobjid <> d1.objid "
2325                                                  "JOIN pg_class c2 ON c2.oid = d2.refobjid "
2326                                                  "AND c2.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2327                                                  CppAsString2(RELKIND_VIEW) ") "
2328                                                  "WHERE d1.classid = 'pg_class'::regclass "
2329                                                  "UNION "
2330                                                  "SELECT w.objid, d3.refobjid, c3.relkind "
2331                                                  "FROM w "
2332                                                  "JOIN pg_rewrite r3 ON r3.ev_class = w.refobjid "
2333                                                  "JOIN pg_depend d3 ON d3.classid = 'pg_rewrite'::regclass "
2334                                                  "AND d3.objid = r3.oid "
2335                                                  "AND d3.refobjid <> w.refobjid "
2336                                                  "JOIN pg_class c3 ON c3.oid = d3.refobjid "
2337                                                  "AND c3.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2338                                                  CppAsString2(RELKIND_VIEW) ") "
2339                                                  ") "
2340                                                  "SELECT 'pg_class'::regclass::oid AS classid, objid, refobjid "
2341                                                  "FROM w "
2342                                                  "WHERE refrelkind = " CppAsString2(RELKIND_MATVIEW));
2343
2344         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2345
2346         ntups = PQntuples(res);
2347
2348         i_classid = PQfnumber(res, "classid");
2349         i_objid = PQfnumber(res, "objid");
2350         i_refobjid = PQfnumber(res, "refobjid");
2351
2352         for (i = 0; i < ntups; i++)
2353         {
2354                 CatalogId       objId;
2355                 CatalogId       refobjId;
2356                 DumpableObject *dobj;
2357                 DumpableObject *refdobj;
2358                 TableInfo  *tbinfo;
2359                 TableInfo  *reftbinfo;
2360
2361                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
2362                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
2363                 refobjId.tableoid = objId.tableoid;
2364                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
2365
2366                 dobj = findObjectByCatalogId(objId);
2367                 if (dobj == NULL)
2368                         continue;
2369
2370                 Assert(dobj->objType == DO_TABLE);
2371                 tbinfo = (TableInfo *) dobj;
2372                 Assert(tbinfo->relkind == RELKIND_MATVIEW);
2373                 dobj = (DumpableObject *) tbinfo->dataObj;
2374                 if (dobj == NULL)
2375                         continue;
2376                 Assert(dobj->objType == DO_REFRESH_MATVIEW);
2377
2378                 refdobj = findObjectByCatalogId(refobjId);
2379                 if (refdobj == NULL)
2380                         continue;
2381
2382                 Assert(refdobj->objType == DO_TABLE);
2383                 reftbinfo = (TableInfo *) refdobj;
2384                 Assert(reftbinfo->relkind == RELKIND_MATVIEW);
2385                 refdobj = (DumpableObject *) reftbinfo->dataObj;
2386                 if (refdobj == NULL)
2387                         continue;
2388                 Assert(refdobj->objType == DO_REFRESH_MATVIEW);
2389
2390                 addObjectDependency(dobj, refdobj->dumpId);
2391
2392                 if (!reftbinfo->relispopulated)
2393                         tbinfo->relispopulated = false;
2394         }
2395
2396         PQclear(res);
2397
2398         destroyPQExpBuffer(query);
2399 }
2400
2401 /*
2402  * getTableDataFKConstraints -
2403  *        add dump-order dependencies reflecting foreign key constraints
2404  *
2405  * This code is executed only in a data-only dump --- in schema+data dumps
2406  * we handle foreign key issues by not creating the FK constraints until
2407  * after the data is loaded.  In a data-only dump, however, we want to
2408  * order the table data objects in such a way that a table's referenced
2409  * tables are restored first.  (In the presence of circular references or
2410  * self-references this may be impossible; we'll detect and complain about
2411  * that during the dependency sorting step.)
2412  */
2413 static void
2414 getTableDataFKConstraints(void)
2415 {
2416         DumpableObject **dobjs;
2417         int                     numObjs;
2418         int                     i;
2419
2420         /* Search through all the dumpable objects for FK constraints */
2421         getDumpableObjects(&dobjs, &numObjs);
2422         for (i = 0; i < numObjs; i++)
2423         {
2424                 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
2425                 {
2426                         ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
2427                         TableInfo  *ftable;
2428
2429                         /* Not interesting unless both tables are to be dumped */
2430                         if (cinfo->contable == NULL ||
2431                                 cinfo->contable->dataObj == NULL)
2432                                 continue;
2433                         ftable = findTableByOid(cinfo->confrelid);
2434                         if (ftable == NULL ||
2435                                 ftable->dataObj == NULL)
2436                                 continue;
2437
2438                         /*
2439                          * Okay, make referencing table's TABLE_DATA object depend on the
2440                          * referenced table's TABLE_DATA object.
2441                          */
2442                         addObjectDependency(&cinfo->contable->dataObj->dobj,
2443                                                                 ftable->dataObj->dobj.dumpId);
2444                 }
2445         }
2446         free(dobjs);
2447 }
2448
2449
2450 /*
2451  * guessConstraintInheritance:
2452  *      In pre-8.4 databases, we can't tell for certain which constraints
2453  *      are inherited.  We assume a CHECK constraint is inherited if its name
2454  *      matches the name of any constraint in the parent.  Originally this code
2455  *      tried to compare the expression texts, but that can fail for various
2456  *      reasons --- for example, if the parent and child tables are in different
2457  *      schemas, reverse-listing of function calls may produce different text
2458  *      (schema-qualified or not) depending on search path.
2459  *
2460  *      In 8.4 and up we can rely on the conislocal field to decide which
2461  *      constraints must be dumped; much safer.
2462  *
2463  *      This function assumes all conislocal flags were initialized to true.
2464  *      It clears the flag on anything that seems to be inherited.
2465  */
2466 static void
2467 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
2468 {
2469         int                     i,
2470                                 j,
2471                                 k;
2472
2473         for (i = 0; i < numTables; i++)
2474         {
2475                 TableInfo  *tbinfo = &(tblinfo[i]);
2476                 int                     numParents;
2477                 TableInfo **parents;
2478                 TableInfo  *parent;
2479
2480                 /* Sequences and views never have parents */
2481                 if (tbinfo->relkind == RELKIND_SEQUENCE ||
2482                         tbinfo->relkind == RELKIND_VIEW)
2483                         continue;
2484
2485                 /* Don't bother computing anything for non-target tables, either */
2486                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
2487                         continue;
2488
2489                 numParents = tbinfo->numParents;
2490                 parents = tbinfo->parents;
2491
2492                 if (numParents == 0)
2493                         continue;                       /* nothing to see here, move along */
2494
2495                 /* scan for inherited CHECK constraints */
2496                 for (j = 0; j < tbinfo->ncheck; j++)
2497                 {
2498                         ConstraintInfo *constr;
2499
2500                         constr = &(tbinfo->checkexprs[j]);
2501
2502                         for (k = 0; k < numParents; k++)
2503                         {
2504                                 int                     l;
2505
2506                                 parent = parents[k];
2507                                 for (l = 0; l < parent->ncheck; l++)
2508                                 {
2509                                         ConstraintInfo *pconstr = &(parent->checkexprs[l]);
2510
2511                                         if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
2512                                         {
2513                                                 constr->conislocal = false;
2514                                                 break;
2515                                         }
2516                                 }
2517                                 if (!constr->conislocal)
2518                                         break;
2519                         }
2520                 }
2521         }
2522 }
2523
2524
2525 /*
2526  * dumpDatabase:
2527  *      dump the database definition
2528  */
2529 static void
2530 dumpDatabase(Archive *fout)
2531 {
2532         DumpOptions *dopt = fout->dopt;
2533         PQExpBuffer dbQry = createPQExpBuffer();
2534         PQExpBuffer delQry = createPQExpBuffer();
2535         PQExpBuffer creaQry = createPQExpBuffer();
2536         PQExpBuffer labelq = createPQExpBuffer();
2537         PGconn     *conn = GetConnection(fout);
2538         PGresult   *res;
2539         int                     i_tableoid,
2540                                 i_oid,
2541                                 i_dba,
2542                                 i_encoding,
2543                                 i_collate,
2544                                 i_ctype,
2545                                 i_frozenxid,
2546                                 i_minmxid,
2547                                 i_datacl,
2548                                 i_rdatacl,
2549                                 i_datistemplate,
2550                                 i_datconnlimit,
2551                                 i_tablespace;
2552         CatalogId       dbCatId;
2553         DumpId          dbDumpId;
2554         const char *datname,
2555                            *dba,
2556                            *encoding,
2557                            *collate,
2558                            *ctype,
2559                            *datacl,
2560                            *rdatacl,
2561                            *datistemplate,
2562                            *datconnlimit,
2563                            *tablespace;
2564         uint32          frozenxid,
2565                                 minmxid;
2566         char       *qdatname;
2567
2568         datname = PQdb(conn);
2569         qdatname = pg_strdup(fmtId(datname));
2570
2571         if (g_verbose)
2572                 write_msg(NULL, "saving database definition\n");
2573
2574         /* Fetch the database-level properties for this database */
2575         if (fout->remoteVersion >= 90600)
2576         {
2577                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2578                                                   "(%s datdba) AS dba, "
2579                                                   "pg_encoding_to_char(encoding) AS encoding, "
2580                                                   "datcollate, datctype, datfrozenxid, datminmxid, "
2581                                                   "(SELECT array_agg(acl ORDER BY acl::text COLLATE \"C\") FROM ( "
2582                                                   "  SELECT unnest(coalesce(datacl,acldefault('d',datdba))) AS acl "
2583                                                   "  EXCEPT SELECT unnest(acldefault('d',datdba))) as datacls)"
2584                                                   " AS datacl, "
2585                                                   "(SELECT array_agg(acl ORDER BY acl::text COLLATE \"C\") FROM ( "
2586                                                   "  SELECT unnest(acldefault('d',datdba)) AS acl "
2587                                                   "  EXCEPT SELECT unnest(coalesce(datacl,acldefault('d',datdba)))) as rdatacls)"
2588                                                   " AS rdatacl, "
2589                                                   "datistemplate, datconnlimit, "
2590                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2591                                                   "shobj_description(oid, 'pg_database') AS description "
2592
2593                                                   "FROM pg_database "
2594                                                   "WHERE datname = ",
2595                                                   username_subquery);
2596                 appendStringLiteralAH(dbQry, datname, fout);
2597         }
2598         else if (fout->remoteVersion >= 90300)
2599         {
2600                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2601                                                   "(%s datdba) AS dba, "
2602                                                   "pg_encoding_to_char(encoding) AS encoding, "
2603                                                   "datcollate, datctype, datfrozenxid, datminmxid, "
2604                                                   "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2605                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2606                                                   "shobj_description(oid, 'pg_database') AS description "
2607
2608                                                   "FROM pg_database "
2609                                                   "WHERE datname = ",
2610                                                   username_subquery);
2611                 appendStringLiteralAH(dbQry, datname, fout);
2612         }
2613         else if (fout->remoteVersion >= 80400)
2614         {
2615                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2616                                                   "(%s datdba) AS dba, "
2617                                                   "pg_encoding_to_char(encoding) AS encoding, "
2618                                                   "datcollate, datctype, datfrozenxid, 0 AS datminmxid, "
2619                                                   "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2620                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2621                                                   "shobj_description(oid, 'pg_database') AS description "
2622
2623                                                   "FROM pg_database "
2624                                                   "WHERE datname = ",
2625                                                   username_subquery);
2626                 appendStringLiteralAH(dbQry, datname, fout);
2627         }
2628         else if (fout->remoteVersion >= 80200)
2629         {
2630                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2631                                                   "(%s datdba) AS dba, "
2632                                                   "pg_encoding_to_char(encoding) AS encoding, "
2633                                                   "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2634                                                   "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2635                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2636                                                   "shobj_description(oid, 'pg_database') AS description "
2637
2638                                                   "FROM pg_database "
2639                                                   "WHERE datname = ",
2640                                                   username_subquery);
2641                 appendStringLiteralAH(dbQry, datname, fout);
2642         }
2643         else
2644         {
2645                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
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 = ",
2654                                                   username_subquery);
2655                 appendStringLiteralAH(dbQry, datname, fout);
2656         }
2657
2658         res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
2659
2660         i_tableoid = PQfnumber(res, "tableoid");
2661         i_oid = PQfnumber(res, "oid");
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         dba = PQgetvalue(res, 0, i_dba);
2677         encoding = PQgetvalue(res, 0, i_encoding);
2678         collate = PQgetvalue(res, 0, i_collate);
2679         ctype = PQgetvalue(res, 0, i_ctype);
2680         frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
2681         minmxid = atooid(PQgetvalue(res, 0, i_minmxid));
2682         datacl = PQgetvalue(res, 0, i_datacl);
2683         rdatacl = PQgetvalue(res, 0, i_rdatacl);
2684         datistemplate = PQgetvalue(res, 0, i_datistemplate);
2685         datconnlimit = PQgetvalue(res, 0, i_datconnlimit);
2686         tablespace = PQgetvalue(res, 0, i_tablespace);
2687
2688         /*
2689          * Prepare the CREATE DATABASE command.  We must specify encoding, locale,
2690          * and tablespace since those can't be altered later.  Other DB properties
2691          * are left to the DATABASE PROPERTIES entry, so that they can be applied
2692          * after reconnecting to the target DB.
2693          */
2694         appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
2695                                           qdatname);
2696         if (strlen(encoding) > 0)
2697         {
2698                 appendPQExpBufferStr(creaQry, " ENCODING = ");
2699                 appendStringLiteralAH(creaQry, encoding, fout);
2700         }
2701         if (strlen(collate) > 0)
2702         {
2703                 appendPQExpBufferStr(creaQry, " LC_COLLATE = ");
2704                 appendStringLiteralAH(creaQry, collate, fout);
2705         }
2706         if (strlen(ctype) > 0)
2707         {
2708                 appendPQExpBufferStr(creaQry, " LC_CTYPE = ");
2709                 appendStringLiteralAH(creaQry, ctype, fout);
2710         }
2711
2712         /*
2713          * Note: looking at dopt->outputNoTablespaces here is completely the wrong
2714          * thing; the decision whether to specify a tablespace should be left till
2715          * pg_restore, so that pg_restore --no-tablespaces applies.  Ideally we'd
2716          * label the DATABASE entry with the tablespace and let the normal
2717          * tablespace selection logic work ... but CREATE DATABASE doesn't pay
2718          * attention to default_tablespace, so that won't work.
2719          */
2720         if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0 &&
2721                 !dopt->outputNoTablespaces)
2722                 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
2723                                                   fmtId(tablespace));
2724         appendPQExpBufferStr(creaQry, ";\n");
2725
2726         appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
2727                                           qdatname);
2728
2729         dbDumpId = createDumpId();
2730
2731         ArchiveEntry(fout,
2732                                  dbCatId,               /* catalog ID */
2733                                  dbDumpId,              /* dump ID */
2734                                  datname,               /* Name */
2735                                  NULL,                  /* Namespace */
2736                                  NULL,                  /* Tablespace */
2737                                  dba,                   /* Owner */
2738                                  false,                 /* with oids */
2739                                  "DATABASE",    /* Desc */
2740                                  SECTION_PRE_DATA,      /* Section */
2741                                  creaQry->data, /* Create */
2742                                  delQry->data,  /* Del */
2743                                  NULL,                  /* Copy */
2744                                  NULL,                  /* Deps */
2745                                  0,                             /* # Deps */
2746                                  NULL,                  /* Dumper */
2747                                  NULL);                 /* Dumper Arg */
2748
2749         /* Compute correct tag for archive entry */
2750         appendPQExpBuffer(labelq, "DATABASE %s", qdatname);
2751
2752         /* Dump DB comment if any */
2753         if (fout->remoteVersion >= 80200)
2754         {
2755                 /*
2756                  * 8.2 and up keep comments on shared objects in a shared table, so we
2757                  * cannot use the dumpComment() code used for other database objects.
2758                  * Be careful that the ArchiveEntry parameters match that function.
2759                  */
2760                 char       *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2761
2762                 if (comment && *comment && !dopt->no_comments)
2763                 {
2764                         resetPQExpBuffer(dbQry);
2765
2766                         /*
2767                          * Generates warning when loaded into a differently-named
2768                          * database.
2769                          */
2770                         appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", qdatname);
2771                         appendStringLiteralAH(dbQry, comment, fout);
2772                         appendPQExpBufferStr(dbQry, ";\n");
2773
2774                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2775                                                  labelq->data, NULL, NULL, dba,
2776                                                  false, "COMMENT", SECTION_NONE,
2777                                                  dbQry->data, "", NULL,
2778                                                  &(dbDumpId), 1,
2779                                                  NULL, NULL);
2780                 }
2781         }
2782         else
2783         {
2784                 dumpComment(fout, "DATABASE", qdatname, NULL, dba,
2785                                         dbCatId, 0, dbDumpId);
2786         }
2787
2788         /* Dump DB security label, if enabled */
2789         if (!dopt->no_security_labels && fout->remoteVersion >= 90200)
2790         {
2791                 PGresult   *shres;
2792                 PQExpBuffer seclabelQry;
2793
2794                 seclabelQry = createPQExpBuffer();
2795
2796                 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2797                 shres = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2798                 resetPQExpBuffer(seclabelQry);
2799                 emitShSecLabels(conn, shres, seclabelQry, "DATABASE", datname);
2800                 if (seclabelQry->len > 0)
2801                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2802                                                  labelq->data, NULL, NULL, dba,
2803                                                  false, "SECURITY LABEL", SECTION_NONE,
2804                                                  seclabelQry->data, "", NULL,
2805                                                  &(dbDumpId), 1,
2806                                                  NULL, NULL);
2807                 destroyPQExpBuffer(seclabelQry);
2808                 PQclear(shres);
2809         }
2810
2811         /*
2812          * Dump ACL if any.  Note that we do not support initial privileges
2813          * (pg_init_privs) on databases.
2814          */
2815         dumpACL(fout, dbCatId, dbDumpId, "DATABASE",
2816                         qdatname, NULL, NULL,
2817                         dba, datacl, rdatacl, "", "");
2818
2819         /*
2820          * Now construct a DATABASE PROPERTIES archive entry to restore any
2821          * non-default database-level properties.  (The reason this must be
2822          * separate is that we cannot put any additional commands into the TOC
2823          * entry that has CREATE DATABASE.  pg_restore would execute such a group
2824          * in an implicit transaction block, and the backend won't allow CREATE
2825          * DATABASE in that context.)
2826          */
2827         resetPQExpBuffer(creaQry);
2828         resetPQExpBuffer(delQry);
2829
2830         if (strlen(datconnlimit) > 0 && strcmp(datconnlimit, "-1") != 0)
2831                 appendPQExpBuffer(creaQry, "ALTER DATABASE %s CONNECTION LIMIT = %s;\n",
2832                                                   qdatname, datconnlimit);
2833
2834         if (strcmp(datistemplate, "t") == 0)
2835         {
2836                 appendPQExpBuffer(creaQry, "ALTER DATABASE %s IS_TEMPLATE = true;\n",
2837                                                   qdatname);
2838
2839                 /*
2840                  * The backend won't accept DROP DATABASE on a template database.  We
2841                  * can deal with that by removing the template marking before the DROP
2842                  * gets issued.  We'd prefer to use ALTER DATABASE IF EXISTS here, but
2843                  * since no such command is currently supported, fake it with a direct
2844                  * UPDATE on pg_database.
2845                  */
2846                 appendPQExpBufferStr(delQry, "UPDATE pg_catalog.pg_database "
2847                                                          "SET datistemplate = false WHERE datname = ");
2848                 appendStringLiteralAH(delQry, datname, fout);
2849                 appendPQExpBufferStr(delQry, ";\n");
2850         }
2851
2852         /* Add database-specific SET options */
2853         dumpDatabaseConfig(fout, creaQry, datname, dbCatId.oid);
2854
2855         /*
2856          * We stick this binary-upgrade query into the DATABASE PROPERTIES archive
2857          * entry, too, for lack of a better place.
2858          */
2859         if (dopt->binary_upgrade)
2860         {
2861                 appendPQExpBufferStr(creaQry, "\n-- For binary upgrade, set datfrozenxid and datminmxid.\n");
2862                 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
2863                                                   "SET datfrozenxid = '%u', datminmxid = '%u'\n"
2864                                                   "WHERE datname = ",
2865                                                   frozenxid, minmxid);
2866                 appendStringLiteralAH(creaQry, datname, fout);
2867                 appendPQExpBufferStr(creaQry, ";\n");
2868         }
2869
2870         if (creaQry->len > 0)
2871                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2872                                          datname, NULL, NULL, dba,
2873                                          false, "DATABASE PROPERTIES", SECTION_PRE_DATA,
2874                                          creaQry->data, delQry->data, NULL,
2875                                          &(dbDumpId), 1,
2876                                          NULL, NULL);
2877
2878         /*
2879          * pg_largeobject and pg_largeobject_metadata come from the old system
2880          * intact, so set their relfrozenxids and relminmxids.
2881          */
2882         if (dopt->binary_upgrade)
2883         {
2884                 PGresult   *lo_res;
2885                 PQExpBuffer loFrozenQry = createPQExpBuffer();
2886                 PQExpBuffer loOutQry = createPQExpBuffer();
2887                 int                     i_relfrozenxid,
2888                                         i_relminmxid;
2889
2890                 /*
2891                  * pg_largeobject
2892                  */
2893                 if (fout->remoteVersion >= 90300)
2894                         appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
2895                                                           "FROM pg_catalog.pg_class\n"
2896                                                           "WHERE oid = %u;\n",
2897                                                           LargeObjectRelationId);
2898                 else
2899                         appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
2900                                                           "FROM pg_catalog.pg_class\n"
2901                                                           "WHERE oid = %u;\n",
2902                                                           LargeObjectRelationId);
2903
2904                 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2905
2906                 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2907                 i_relminmxid = PQfnumber(lo_res, "relminmxid");
2908
2909                 appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject relfrozenxid and relminmxid\n");
2910                 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2911                                                   "SET relfrozenxid = '%u', relminmxid = '%u'\n"
2912                                                   "WHERE oid = %u;\n",
2913                                                   atooid(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2914                                                   atooid(PQgetvalue(lo_res, 0, i_relminmxid)),
2915                                                   LargeObjectRelationId);
2916                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2917                                          "pg_largeobject", NULL, NULL, "",
2918                                          false, "pg_largeobject", SECTION_PRE_DATA,
2919                                          loOutQry->data, "", NULL,
2920                                          NULL, 0,
2921                                          NULL, NULL);
2922
2923                 PQclear(lo_res);
2924
2925                 /*
2926                  * pg_largeobject_metadata
2927                  */
2928                 if (fout->remoteVersion >= 90000)
2929                 {
2930                         resetPQExpBuffer(loFrozenQry);
2931                         resetPQExpBuffer(loOutQry);
2932
2933                         if (fout->remoteVersion >= 90300)
2934                                 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
2935                                                                   "FROM pg_catalog.pg_class\n"
2936                                                                   "WHERE oid = %u;\n",
2937                                                                   LargeObjectMetadataRelationId);
2938                         else
2939                                 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
2940                                                                   "FROM pg_catalog.pg_class\n"
2941                                                                   "WHERE oid = %u;\n",
2942                                                                   LargeObjectMetadataRelationId);
2943
2944                         lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2945
2946                         i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2947                         i_relminmxid = PQfnumber(lo_res, "relminmxid");
2948
2949                         appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata relfrozenxid and relminmxid\n");
2950                         appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2951                                                           "SET relfrozenxid = '%u', relminmxid = '%u'\n"
2952                                                           "WHERE oid = %u;\n",
2953                                                           atooid(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2954                                                           atooid(PQgetvalue(lo_res, 0, i_relminmxid)),
2955                                                           LargeObjectMetadataRelationId);
2956                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2957                                                  "pg_largeobject_metadata", NULL, NULL, "",
2958                                                  false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2959                                                  loOutQry->data, "", NULL,
2960                                                  NULL, 0,
2961                                                  NULL, NULL);
2962
2963                         PQclear(lo_res);
2964                 }
2965
2966                 destroyPQExpBuffer(loFrozenQry);
2967                 destroyPQExpBuffer(loOutQry);
2968         }
2969
2970         PQclear(res);
2971
2972         free(qdatname);
2973         destroyPQExpBuffer(dbQry);
2974         destroyPQExpBuffer(delQry);
2975         destroyPQExpBuffer(creaQry);
2976         destroyPQExpBuffer(labelq);
2977 }
2978
2979 /*
2980  * Collect any database-specific or role-and-database-specific SET options
2981  * for this database, and append them to outbuf.
2982  */
2983 static void
2984 dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
2985                                    const char *dbname, Oid dboid)
2986 {
2987         PGconn     *conn = GetConnection(AH);
2988         PQExpBuffer buf = createPQExpBuffer();
2989         PGresult   *res;
2990         int                     count = 1;
2991
2992         /*
2993          * First collect database-specific options.  Pre-8.4 server versions lack
2994          * unnest(), so we do this the hard way by querying once per subscript.
2995          */
2996         for (;;)
2997         {
2998                 if (AH->remoteVersion >= 90000)
2999                         printfPQExpBuffer(buf, "SELECT setconfig[%d] FROM pg_db_role_setting "
3000                                                           "WHERE setrole = 0 AND setdatabase = '%u'::oid",
3001                                                           count, dboid);
3002                 else
3003                         printfPQExpBuffer(buf, "SELECT datconfig[%d] FROM pg_database WHERE oid = '%u'::oid", count, dboid);
3004
3005                 res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3006
3007                 if (PQntuples(res) == 1 &&
3008                         !PQgetisnull(res, 0, 0))
3009                 {
3010                         makeAlterConfigCommand(conn, PQgetvalue(res, 0, 0),
3011                                                                    "DATABASE", dbname, NULL, NULL,
3012                                                                    outbuf);
3013                         PQclear(res);
3014                         count++;
3015                 }
3016                 else
3017                 {
3018                         PQclear(res);
3019                         break;
3020                 }
3021         }
3022
3023         /* Now look for role-and-database-specific options */
3024         if (AH->remoteVersion >= 90000)
3025         {
3026                 /* Here we can assume we have unnest() */
3027                 printfPQExpBuffer(buf, "SELECT rolname, unnest(setconfig) "
3028                                                   "FROM pg_db_role_setting s, pg_roles r "
3029                                                   "WHERE setrole = r.oid AND setdatabase = '%u'::oid",
3030                                                   dboid);
3031
3032                 res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3033
3034                 if (PQntuples(res) > 0)
3035                 {
3036                         int                     i;
3037
3038                         for (i = 0; i < PQntuples(res); i++)
3039                                 makeAlterConfigCommand(conn, PQgetvalue(res, i, 1),
3040                                                                            "ROLE", PQgetvalue(res, i, 0),
3041                                                                            "DATABASE", dbname,
3042                                                                            outbuf);
3043                 }
3044
3045                 PQclear(res);
3046         }
3047
3048         destroyPQExpBuffer(buf);
3049 }
3050
3051 /*
3052  * dumpEncoding: put the correct encoding into the archive
3053  */
3054 static void
3055 dumpEncoding(Archive *AH)
3056 {
3057         const char *encname = pg_encoding_to_char(AH->encoding);
3058         PQExpBuffer qry = createPQExpBuffer();
3059
3060         if (g_verbose)
3061                 write_msg(NULL, "saving encoding = %s\n", encname);
3062
3063         appendPQExpBufferStr(qry, "SET client_encoding = ");
3064         appendStringLiteralAH(qry, encname, AH);
3065         appendPQExpBufferStr(qry, ";\n");
3066
3067         ArchiveEntry(AH, nilCatalogId, createDumpId(),
3068                                  "ENCODING", NULL, NULL, "",
3069                                  false, "ENCODING", SECTION_PRE_DATA,
3070                                  qry->data, "", NULL,
3071                                  NULL, 0,
3072                                  NULL, NULL);
3073
3074         destroyPQExpBuffer(qry);
3075 }
3076
3077
3078 /*
3079  * dumpStdStrings: put the correct escape string behavior into the archive
3080  */
3081 static void
3082 dumpStdStrings(Archive *AH)
3083 {
3084         const char *stdstrings = AH->std_strings ? "on" : "off";
3085         PQExpBuffer qry = createPQExpBuffer();
3086
3087         if (g_verbose)
3088                 write_msg(NULL, "saving standard_conforming_strings = %s\n",
3089                                   stdstrings);
3090
3091         appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
3092                                           stdstrings);
3093
3094         ArchiveEntry(AH, nilCatalogId, createDumpId(),
3095                                  "STDSTRINGS", NULL, NULL, "",
3096                                  false, "STDSTRINGS", SECTION_PRE_DATA,
3097                                  qry->data, "", NULL,
3098                                  NULL, 0,
3099                                  NULL, NULL);
3100
3101         destroyPQExpBuffer(qry);
3102 }
3103
3104 /*
3105  * dumpSearchPath: record the active search_path in the archive
3106  */
3107 static void
3108 dumpSearchPath(Archive *AH)
3109 {
3110         PQExpBuffer qry = createPQExpBuffer();
3111         PQExpBuffer path = createPQExpBuffer();
3112         PGresult   *res;
3113         char      **schemanames = NULL;
3114         int                     nschemanames = 0;
3115         int                     i;
3116
3117         /*
3118          * We use the result of current_schemas(), not the search_path GUC,
3119          * because that might contain wildcards such as "$user", which won't
3120          * necessarily have the same value during restore.  Also, this way avoids
3121          * listing schemas that may appear in search_path but not actually exist,
3122          * which seems like a prudent exclusion.
3123          */
3124         res = ExecuteSqlQueryForSingleRow(AH,
3125                                                                           "SELECT pg_catalog.current_schemas(false)");
3126
3127         if (!parsePGArray(PQgetvalue(res, 0, 0), &schemanames, &nschemanames))
3128                 exit_horribly(NULL, "could not parse result of current_schemas()\n");
3129
3130         /*
3131          * We use set_config(), not a simple "SET search_path" command, because
3132          * the latter has less-clean behavior if the search path is empty.  While
3133          * that's likely to get fixed at some point, it seems like a good idea to
3134          * be as backwards-compatible as possible in what we put into archives.
3135          */
3136         for (i = 0; i < nschemanames; i++)
3137         {
3138                 if (i > 0)
3139                         appendPQExpBufferStr(path, ", ");
3140                 appendPQExpBufferStr(path, fmtId(schemanames[i]));
3141         }
3142
3143         appendPQExpBufferStr(qry, "SELECT pg_catalog.set_config('search_path', ");
3144         appendStringLiteralAH(qry, path->data, AH);
3145         appendPQExpBufferStr(qry, ", false);\n");
3146
3147         if (g_verbose)
3148                 write_msg(NULL, "saving search_path = %s\n", path->data);
3149
3150         ArchiveEntry(AH, nilCatalogId, createDumpId(),
3151                                  "SEARCHPATH", NULL, NULL, "",
3152                                  false, "SEARCHPATH", SECTION_PRE_DATA,
3153                                  qry->data, "", NULL,
3154                                  NULL, 0,
3155                                  NULL, NULL);
3156
3157         /* Also save it in AH->searchpath, in case we're doing plain text dump */
3158         AH->searchpath = pg_strdup(qry->data);
3159
3160         if (schemanames)
3161                 free(schemanames);
3162         PQclear(res);
3163         destroyPQExpBuffer(qry);
3164         destroyPQExpBuffer(path);
3165 }
3166
3167
3168 /*
3169  * getBlobs:
3170  *      Collect schema-level data about large objects
3171  */
3172 static void
3173 getBlobs(Archive *fout)
3174 {
3175         DumpOptions *dopt = fout->dopt;
3176         PQExpBuffer blobQry = createPQExpBuffer();
3177         BlobInfo   *binfo;
3178         DumpableObject *bdata;
3179         PGresult   *res;
3180         int                     ntups;
3181         int                     i;
3182         int                     i_oid;
3183         int                     i_lomowner;
3184         int                     i_lomacl;
3185         int                     i_rlomacl;
3186         int                     i_initlomacl;
3187         int                     i_initrlomacl;
3188
3189         /* Verbose message */
3190         if (g_verbose)
3191                 write_msg(NULL, "reading large objects\n");
3192
3193         /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
3194         if (fout->remoteVersion >= 90600)
3195         {
3196                 PQExpBuffer acl_subquery = createPQExpBuffer();
3197                 PQExpBuffer racl_subquery = createPQExpBuffer();
3198                 PQExpBuffer init_acl_subquery = createPQExpBuffer();
3199                 PQExpBuffer init_racl_subquery = createPQExpBuffer();
3200
3201                 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
3202                                                 init_racl_subquery, "l.lomacl", "l.lomowner", "'L'",
3203                                                 dopt->binary_upgrade);
3204
3205                 appendPQExpBuffer(blobQry,
3206                                                   "SELECT l.oid, (%s l.lomowner) AS rolname, "
3207                                                   "%s AS lomacl, "
3208                                                   "%s AS rlomacl, "
3209                                                   "%s AS initlomacl, "
3210                                                   "%s AS initrlomacl "
3211                                                   "FROM pg_largeobject_metadata l "
3212                                                   "LEFT JOIN pg_init_privs pip ON "
3213                                                   "(l.oid = pip.objoid "
3214                                                   "AND pip.classoid = 'pg_largeobject'::regclass "
3215                                                   "AND pip.objsubid = 0) ",
3216                                                   username_subquery,
3217                                                   acl_subquery->data,
3218                                                   racl_subquery->data,
3219                                                   init_acl_subquery->data,
3220                                                   init_racl_subquery->data);
3221
3222                 destroyPQExpBuffer(acl_subquery);
3223                 destroyPQExpBuffer(racl_subquery);
3224                 destroyPQExpBuffer(init_acl_subquery);
3225                 destroyPQExpBuffer(init_racl_subquery);
3226         }
3227         else if (fout->remoteVersion >= 90000)
3228                 appendPQExpBuffer(blobQry,
3229                                                   "SELECT oid, (%s lomowner) AS rolname, lomacl, "
3230                                                   "NULL AS rlomacl, NULL AS initlomacl, "
3231                                                   "NULL AS initrlomacl "
3232                                                   " FROM pg_largeobject_metadata",
3233                                                   username_subquery);
3234         else
3235                 appendPQExpBufferStr(blobQry,
3236                                                          "SELECT DISTINCT loid AS oid, "
3237                                                          "NULL::name AS rolname, NULL::oid AS lomacl, "
3238                                                          "NULL::oid AS rlomacl, NULL::oid AS initlomacl, "
3239                                                          "NULL::oid AS initrlomacl "
3240                                                          " FROM pg_largeobject");
3241
3242         res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
3243
3244         i_oid = PQfnumber(res, "oid");
3245         i_lomowner = PQfnumber(res, "rolname");
3246         i_lomacl = PQfnumber(res, "lomacl");
3247         i_rlomacl = PQfnumber(res, "rlomacl");
3248         i_initlomacl = PQfnumber(res, "initlomacl");
3249         i_initrlomacl = PQfnumber(res, "initrlomacl");
3250
3251         ntups = PQntuples(res);
3252
3253         /*
3254          * Each large object has its own BLOB archive entry.
3255          */
3256         binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
3257
3258         for (i = 0; i < ntups; i++)
3259         {
3260                 binfo[i].dobj.objType = DO_BLOB;
3261                 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
3262                 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3263                 AssignDumpId(&binfo[i].dobj);
3264
3265                 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oid));
3266                 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_lomowner));
3267                 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, i_lomacl));
3268                 binfo[i].rblobacl = pg_strdup(PQgetvalue(res, i, i_rlomacl));
3269                 binfo[i].initblobacl = pg_strdup(PQgetvalue(res, i, i_initlomacl));
3270                 binfo[i].initrblobacl = pg_strdup(PQgetvalue(res, i, i_initrlomacl));
3271
3272                 if (PQgetisnull(res, i, i_lomacl) &&
3273                         PQgetisnull(res, i, i_rlomacl) &&
3274                         PQgetisnull(res, i, i_initlomacl) &&
3275                         PQgetisnull(res, i, i_initrlomacl))
3276                         binfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
3277
3278                 /*
3279                  * In binary-upgrade mode for blobs, we do *not* dump out the data or
3280                  * the ACLs, should any exist.  The data and ACL (if any) will be
3281                  * copied by pg_upgrade, which simply copies the pg_largeobject and
3282                  * pg_largeobject_metadata tables.
3283                  *
3284                  * We *do* dump out the definition of the blob because we need that to
3285                  * make the restoration of the comments, and anything else, work since
3286                  * pg_upgrade copies the files behind pg_largeobject and
3287                  * pg_largeobject_metadata after the dump is restored.
3288                  */
3289                 if (dopt->binary_upgrade)
3290                         binfo[i].dobj.dump &= ~(DUMP_COMPONENT_DATA | DUMP_COMPONENT_ACL);
3291         }
3292
3293         /*
3294          * If we have any large objects, a "BLOBS" archive entry is needed. This
3295          * is just a placeholder for sorting; it carries no data now.
3296          */
3297         if (ntups > 0)
3298         {
3299                 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
3300                 bdata->objType = DO_BLOB_DATA;
3301                 bdata->catId = nilCatalogId;
3302                 AssignDumpId(bdata);
3303                 bdata->name = pg_strdup("BLOBS");
3304         }
3305
3306         PQclear(res);
3307         destroyPQExpBuffer(blobQry);
3308 }
3309
3310 /*
3311  * dumpBlob
3312  *
3313  * dump the definition (metadata) of the given large object
3314  */
3315 static void
3316 dumpBlob(Archive *fout, BlobInfo *binfo)
3317 {
3318         PQExpBuffer cquery = createPQExpBuffer();
3319         PQExpBuffer dquery = createPQExpBuffer();
3320
3321         appendPQExpBuffer(cquery,
3322                                           "SELECT pg_catalog.lo_create('%s');\n",
3323                                           binfo->dobj.name);
3324
3325         appendPQExpBuffer(dquery,
3326                                           "SELECT pg_catalog.lo_unlink('%s');\n",
3327                                           binfo->dobj.name);
3328
3329         if (binfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
3330                 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
3331                                          binfo->dobj.name,
3332                                          NULL, NULL,
3333                                          binfo->rolname, false,
3334                                          "BLOB", SECTION_PRE_DATA,
3335                                          cquery->data, dquery->data, NULL,
3336                                          NULL, 0,
3337                                          NULL, NULL);
3338
3339         /* Dump comment if any */
3340         if (binfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3341                 dumpComment(fout, "LARGE OBJECT", binfo->dobj.name,
3342                                         NULL, binfo->rolname,
3343                                         binfo->dobj.catId, 0, binfo->dobj.dumpId);
3344
3345         /* Dump security label if any */
3346         if (binfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3347                 dumpSecLabel(fout, "LARGE OBJECT", binfo->dobj.name,
3348                                          NULL, binfo->rolname,
3349                                          binfo->dobj.catId, 0, binfo->dobj.dumpId);
3350
3351         /* Dump ACL if any */
3352         if (binfo->blobacl && (binfo->dobj.dump & DUMP_COMPONENT_ACL))
3353                 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
3354                                 binfo->dobj.name, NULL,
3355                                 NULL, binfo->rolname, binfo->blobacl, binfo->rblobacl,
3356                                 binfo->initblobacl, binfo->initrblobacl);
3357
3358         destroyPQExpBuffer(cquery);
3359         destroyPQExpBuffer(dquery);
3360 }
3361
3362 /*
3363  * dumpBlobs:
3364  *      dump the data contents of all large objects
3365  */
3366 static int
3367 dumpBlobs(Archive *fout, void *arg)
3368 {
3369         const char *blobQry;
3370         const char *blobFetchQry;
3371         PGconn     *conn = GetConnection(fout);
3372         PGresult   *res;
3373         char            buf[LOBBUFSIZE];
3374         int                     ntups;
3375         int                     i;
3376         int                     cnt;
3377
3378         if (g_verbose)
3379                 write_msg(NULL, "saving large objects\n");
3380
3381         /*
3382          * Currently, we re-fetch all BLOB OIDs using a cursor.  Consider scanning
3383          * the already-in-memory dumpable objects instead...
3384          */
3385         if (fout->remoteVersion >= 90000)
3386                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
3387         else
3388                 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
3389
3390         ExecuteSqlStatement(fout, blobQry);
3391
3392         /* Command to fetch from cursor */
3393         blobFetchQry = "FETCH 1000 IN bloboid";
3394
3395         do
3396         {
3397                 /* Do a fetch */
3398                 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
3399
3400                 /* Process the tuples, if any */
3401                 ntups = PQntuples(res);
3402                 for (i = 0; i < ntups; i++)
3403                 {
3404                         Oid                     blobOid;
3405                         int                     loFd;
3406
3407                         blobOid = atooid(PQgetvalue(res, i, 0));
3408                         /* Open the BLOB */
3409                         loFd = lo_open(conn, blobOid, INV_READ);
3410                         if (loFd == -1)
3411                                 exit_horribly(NULL, "could not open large object %u: %s",
3412                                                           blobOid, PQerrorMessage(conn));
3413
3414                         StartBlob(fout, blobOid);
3415
3416                         /* Now read it in chunks, sending data to archive */
3417                         do
3418                         {
3419                                 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
3420                                 if (cnt < 0)
3421                                         exit_horribly(NULL, "error reading large object %u: %s",
3422                                                                   blobOid, PQerrorMessage(conn));
3423
3424                                 WriteData(fout, buf, cnt);
3425                         } while (cnt > 0);
3426
3427                         lo_close(conn, loFd);
3428
3429                         EndBlob(fout, blobOid);
3430                 }
3431
3432                 PQclear(res);
3433         } while (ntups > 0);
3434
3435         return 1;
3436 }
3437
3438 /*
3439  * getPolicies
3440  *        get information about policies on a dumpable table.
3441  */
3442 void
3443 getPolicies(Archive *fout, TableInfo tblinfo[], int numTables)
3444 {
3445         PQExpBuffer query;
3446         PGresult   *res;
3447         PolicyInfo *polinfo;
3448         int                     i_oid;
3449         int                     i_tableoid;
3450         int                     i_polname;
3451         int                     i_polcmd;
3452         int                     i_polpermissive;
3453         int                     i_polroles;
3454         int                     i_polqual;
3455         int                     i_polwithcheck;
3456         int                     i,
3457                                 j,
3458                                 ntups;
3459
3460         if (fout->remoteVersion < 90500)
3461                 return;
3462
3463         query = createPQExpBuffer();
3464
3465         for (i = 0; i < numTables; i++)
3466         {
3467                 TableInfo  *tbinfo = &tblinfo[i];
3468
3469                 /* Ignore row security on tables not to be dumped */
3470                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_POLICY))
3471                         continue;
3472
3473                 if (g_verbose)
3474                         write_msg(NULL, "reading row security enabled for table \"%s.%s\"\n",
3475                                           tbinfo->dobj.namespace->dobj.name,
3476                                           tbinfo->dobj.name);
3477
3478                 /*
3479                  * Get row security enabled information for the table. We represent
3480                  * RLS enabled on a table by creating PolicyInfo object with an empty
3481                  * policy.
3482                  */
3483                 if (tbinfo->rowsec)
3484                 {
3485                         /*
3486                          * Note: use tableoid 0 so that this object won't be mistaken for
3487                          * something that pg_depend entries apply to.
3488                          */
3489                         polinfo = pg_malloc(sizeof(PolicyInfo));
3490                         polinfo->dobj.objType = DO_POLICY;
3491                         polinfo->dobj.catId.tableoid = 0;
3492                         polinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
3493                         AssignDumpId(&polinfo->dobj);
3494                         polinfo->dobj.namespace = tbinfo->dobj.namespace;
3495                         polinfo->dobj.name = pg_strdup(tbinfo->dobj.name);
3496                         polinfo->poltable = tbinfo;
3497                         polinfo->polname = NULL;
3498                         polinfo->polcmd = '\0';
3499                         polinfo->polpermissive = 0;
3500                         polinfo->polroles = NULL;
3501                         polinfo->polqual = NULL;
3502                         polinfo->polwithcheck = NULL;
3503                 }
3504
3505                 if (g_verbose)
3506                         write_msg(NULL, "reading policies for table \"%s.%s\"\n",
3507                                           tbinfo->dobj.namespace->dobj.name,
3508                                           tbinfo->dobj.name);
3509
3510                 resetPQExpBuffer(query);
3511
3512                 /* Get the policies for the table. */
3513                 if (fout->remoteVersion >= 100000)
3514                         appendPQExpBuffer(query,
3515                                                           "SELECT oid, tableoid, pol.polname, pol.polcmd, pol.polpermissive, "
3516                                                           "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3517                                                           "   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, "
3518                                                           "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3519                                                           "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3520                                                           "FROM pg_catalog.pg_policy pol "
3521                                                           "WHERE polrelid = '%u'",
3522                                                           tbinfo->dobj.catId.oid);
3523                 else
3524                         appendPQExpBuffer(query,
3525                                                           "SELECT oid, tableoid, pol.polname, pol.polcmd, 't' as polpermissive, "
3526                                                           "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3527                                                           "   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, "
3528                                                           "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3529                                                           "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3530                                                           "FROM pg_catalog.pg_policy pol "
3531                                                           "WHERE polrelid = '%u'",
3532                                                           tbinfo->dobj.catId.oid);
3533                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3534
3535                 ntups = PQntuples(res);
3536
3537                 if (ntups == 0)
3538                 {
3539                         /*
3540                          * No explicit policies to handle (only the default-deny policy,
3541                          * which is handled as part of the table definition).  Clean up
3542                          * and return.
3543                          */
3544                         PQclear(res);
3545                         continue;
3546                 }
3547
3548                 i_oid = PQfnumber(res, "oid");
3549                 i_tableoid = PQfnumber(res, "tableoid");
3550                 i_polname = PQfnumber(res, "polname");
3551                 i_polcmd = PQfnumber(res, "polcmd");
3552                 i_polpermissive = PQfnumber(res, "polpermissive");
3553                 i_polroles = PQfnumber(res, "polroles");
3554                 i_polqual = PQfnumber(res, "polqual");
3555                 i_polwithcheck = PQfnumber(res, "polwithcheck");
3556
3557                 polinfo = pg_malloc(ntups * sizeof(PolicyInfo));
3558
3559                 for (j = 0; j < ntups; j++)
3560                 {
3561                         polinfo[j].dobj.objType = DO_POLICY;
3562                         polinfo[j].dobj.catId.tableoid =
3563                                 atooid(PQgetvalue(res, j, i_tableoid));
3564                         polinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3565                         AssignDumpId(&polinfo[j].dobj);
3566                         polinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3567                         polinfo[j].poltable = tbinfo;
3568                         polinfo[j].polname = pg_strdup(PQgetvalue(res, j, i_polname));
3569                         polinfo[j].dobj.name = pg_strdup(polinfo[j].polname);
3570
3571                         polinfo[j].polcmd = *(PQgetvalue(res, j, i_polcmd));
3572                         polinfo[j].polpermissive = *(PQgetvalue(res, j, i_polpermissive)) == 't';
3573
3574                         if (PQgetisnull(res, j, i_polroles))
3575                                 polinfo[j].polroles = NULL;
3576                         else
3577                                 polinfo[j].polroles = pg_strdup(PQgetvalue(res, j, i_polroles));
3578
3579                         if (PQgetisnull(res, j, i_polqual))
3580                                 polinfo[j].polqual = NULL;
3581                         else
3582                                 polinfo[j].polqual = pg_strdup(PQgetvalue(res, j, i_polqual));
3583
3584                         if (PQgetisnull(res, j, i_polwithcheck))
3585                                 polinfo[j].polwithcheck = NULL;
3586                         else
3587                                 polinfo[j].polwithcheck
3588                                         = pg_strdup(PQgetvalue(res, j, i_polwithcheck));
3589                 }
3590                 PQclear(res);
3591         }
3592         destroyPQExpBuffer(query);
3593 }
3594
3595 /*
3596  * dumpPolicy
3597  *        dump the definition of the given policy
3598  */
3599 static void
3600 dumpPolicy(Archive *fout, PolicyInfo *polinfo)
3601 {
3602         DumpOptions *dopt = fout->dopt;
3603         TableInfo  *tbinfo = polinfo->poltable;
3604         PQExpBuffer query;
3605         PQExpBuffer delqry;
3606         const char *cmd;
3607         char       *tag;
3608
3609         if (dopt->dataOnly)
3610                 return;
3611
3612         /*
3613          * If polname is NULL, then this record is just indicating that ROW LEVEL
3614          * SECURITY is enabled for the table. Dump as ALTER TABLE <table> ENABLE
3615          * ROW LEVEL SECURITY.
3616          */
3617         if (polinfo->polname == NULL)
3618         {
3619                 query = createPQExpBuffer();
3620
3621                 appendPQExpBuffer(query, "ALTER TABLE %s ENABLE ROW LEVEL SECURITY;",
3622                                                   fmtQualifiedDumpable(polinfo));
3623
3624                 if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3625                         ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3626                                                  polinfo->dobj.name,
3627                                                  polinfo->dobj.namespace->dobj.name,
3628                                                  NULL,
3629                                                  tbinfo->rolname, false,
3630                                                  "ROW SECURITY", SECTION_POST_DATA,
3631                                                  query->data, "", NULL,
3632                                                  NULL, 0,
3633                                                  NULL, NULL);
3634
3635                 destroyPQExpBuffer(query);
3636                 return;
3637         }
3638
3639         if (polinfo->polcmd == '*')
3640                 cmd = "";
3641         else if (polinfo->polcmd == 'r')
3642                 cmd = " FOR SELECT";
3643         else if (polinfo->polcmd == 'a')
3644                 cmd = " FOR INSERT";
3645         else if (polinfo->polcmd == 'w')
3646                 cmd = " FOR UPDATE";
3647         else if (polinfo->polcmd == 'd')
3648                 cmd = " FOR DELETE";
3649         else
3650         {
3651                 write_msg(NULL, "unexpected policy command type: %c\n",
3652                                   polinfo->polcmd);
3653                 exit_nicely(1);
3654         }
3655
3656         query = createPQExpBuffer();
3657         delqry = createPQExpBuffer();
3658
3659         appendPQExpBuffer(query, "CREATE POLICY %s", fmtId(polinfo->polname));
3660
3661         appendPQExpBuffer(query, " ON %s%s%s", fmtQualifiedDumpable(tbinfo),
3662                                           !polinfo->polpermissive ? " AS RESTRICTIVE" : "", cmd);
3663
3664         if (polinfo->polroles != NULL)
3665                 appendPQExpBuffer(query, " TO %s", polinfo->polroles);
3666
3667         if (polinfo->polqual != NULL)
3668                 appendPQExpBuffer(query, " USING (%s)", polinfo->polqual);
3669
3670         if (polinfo->polwithcheck != NULL)
3671                 appendPQExpBuffer(query, " WITH CHECK (%s)", polinfo->polwithcheck);
3672
3673         appendPQExpBuffer(query, ";\n");
3674
3675         appendPQExpBuffer(delqry, "DROP POLICY %s", fmtId(polinfo->polname));
3676         appendPQExpBuffer(delqry, " ON %s;\n", fmtQualifiedDumpable(tbinfo));
3677
3678         tag = psprintf("%s %s", tbinfo->dobj.name, polinfo->dobj.name);
3679
3680         if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3681                 ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3682                                          tag,
3683                                          polinfo->dobj.namespace->dobj.name,
3684                                          NULL,
3685                                          tbinfo->rolname, false,
3686                                          "POLICY", SECTION_POST_DATA,
3687                                          query->data, delqry->data, NULL,
3688                                          NULL, 0,
3689                                          NULL, NULL);
3690
3691         free(tag);
3692         destroyPQExpBuffer(query);
3693         destroyPQExpBuffer(delqry);
3694 }
3695
3696 /*
3697  * getPublications
3698  *        get information about publications
3699  */
3700 void
3701 getPublications(Archive *fout)
3702 {
3703         DumpOptions *dopt = fout->dopt;
3704         PQExpBuffer query;
3705         PGresult   *res;
3706         PublicationInfo *pubinfo;
3707         int                     i_tableoid;
3708         int                     i_oid;
3709         int                     i_pubname;
3710         int                     i_rolname;
3711         int                     i_puballtables;
3712         int                     i_pubinsert;
3713         int                     i_pubupdate;
3714         int                     i_pubdelete;
3715         int                     i,
3716                                 ntups;
3717
3718         if (dopt->no_publications || fout->remoteVersion < 100000)
3719                 return;
3720
3721         query = createPQExpBuffer();
3722
3723         resetPQExpBuffer(query);
3724
3725         /* Get the publications. */
3726         appendPQExpBuffer(query,
3727                                           "SELECT p.tableoid, p.oid, p.pubname, "
3728                                           "(%s p.pubowner) AS rolname, "
3729                                           "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete "
3730                                           "FROM pg_publication p",
3731                                           username_subquery);
3732
3733         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3734
3735         ntups = PQntuples(res);
3736
3737         i_tableoid = PQfnumber(res, "tableoid");
3738         i_oid = PQfnumber(res, "oid");
3739         i_pubname = PQfnumber(res, "pubname");
3740         i_rolname = PQfnumber(res, "rolname");
3741         i_puballtables = PQfnumber(res, "puballtables");
3742         i_pubinsert = PQfnumber(res, "pubinsert");
3743         i_pubupdate = PQfnumber(res, "pubupdate");
3744         i_pubdelete = PQfnumber(res, "pubdelete");
3745
3746         pubinfo = pg_malloc(ntups * sizeof(PublicationInfo));
3747
3748         for (i = 0; i < ntups; i++)
3749         {
3750                 pubinfo[i].dobj.objType = DO_PUBLICATION;
3751                 pubinfo[i].dobj.catId.tableoid =
3752                         atooid(PQgetvalue(res, i, i_tableoid));
3753                 pubinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3754                 AssignDumpId(&pubinfo[i].dobj);
3755                 pubinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_pubname));
3756                 pubinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3757                 pubinfo[i].puballtables =
3758                         (strcmp(PQgetvalue(res, i, i_puballtables), "t") == 0);
3759                 pubinfo[i].pubinsert =
3760                         (strcmp(PQgetvalue(res, i, i_pubinsert), "t") == 0);
3761                 pubinfo[i].pubupdate =
3762                         (strcmp(PQgetvalue(res, i, i_pubupdate), "t") == 0);
3763                 pubinfo[i].pubdelete =
3764                         (strcmp(PQgetvalue(res, i, i_pubdelete), "t") == 0);
3765
3766                 if (strlen(pubinfo[i].rolname) == 0)
3767                         write_msg(NULL, "WARNING: owner of publication \"%s\" appears to be invalid\n",
3768                                           pubinfo[i].dobj.name);
3769
3770                 /* Decide whether we want to dump it */
3771                 selectDumpableObject(&(pubinfo[i].dobj), fout);
3772         }
3773         PQclear(res);
3774
3775         destroyPQExpBuffer(query);
3776 }
3777
3778 /*
3779  * dumpPublication
3780  *        dump the definition of the given publication
3781  */
3782 static void
3783 dumpPublication(Archive *fout, PublicationInfo *pubinfo)
3784 {
3785         PQExpBuffer delq;
3786         PQExpBuffer query;
3787         char       *qpubname;
3788         bool            first = true;
3789
3790         if (!(pubinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3791                 return;
3792
3793         delq = createPQExpBuffer();
3794         query = createPQExpBuffer();
3795
3796         qpubname = pg_strdup(fmtId(pubinfo->dobj.name));
3797
3798         appendPQExpBuffer(delq, "DROP PUBLICATION %s;\n",
3799                                           qpubname);
3800
3801         appendPQExpBuffer(query, "CREATE PUBLICATION %s",
3802                                           qpubname);
3803
3804         if (pubinfo->puballtables)
3805                 appendPQExpBufferStr(query, " FOR ALL TABLES");
3806
3807         appendPQExpBufferStr(query, " WITH (publish = '");
3808         if (pubinfo->pubinsert)
3809         {
3810                 appendPQExpBufferStr(query, "insert");
3811                 first = false;
3812         }
3813
3814         if (pubinfo->pubupdate)
3815         {
3816                 if (!first)
3817                         appendPQExpBufferStr(query, ", ");
3818
3819                 appendPQExpBufferStr(query, "update");
3820                 first = false;
3821         }
3822
3823         if (pubinfo->pubdelete)
3824         {
3825                 if (!first)
3826                         appendPQExpBufferStr(query, ", ");
3827
3828                 appendPQExpBufferStr(query, "delete");
3829                 first = false;
3830         }
3831
3832         appendPQExpBufferStr(query, "');\n");
3833
3834         ArchiveEntry(fout, pubinfo->dobj.catId, pubinfo->dobj.dumpId,
3835                                  pubinfo->dobj.name,
3836                                  NULL,
3837                                  NULL,
3838                                  pubinfo->rolname, false,
3839                                  "PUBLICATION", SECTION_POST_DATA,
3840                                  query->data, delq->data, NULL,
3841                                  NULL, 0,
3842                                  NULL, NULL);
3843
3844         if (pubinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3845                 dumpComment(fout, "PUBLICATION", qpubname,
3846                                         NULL, pubinfo->rolname,
3847                                         pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3848
3849         if (pubinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3850                 dumpSecLabel(fout, "PUBLICATION", qpubname,
3851                                          NULL, pubinfo->rolname,
3852                                          pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3853
3854         destroyPQExpBuffer(delq);
3855         destroyPQExpBuffer(query);
3856         free(qpubname);
3857 }
3858
3859 /*
3860  * getPublicationTables
3861  *        get information about publication membership for dumpable tables.
3862  */
3863 void
3864 getPublicationTables(Archive *fout, TableInfo tblinfo[], int numTables)
3865 {
3866         PQExpBuffer query;
3867         PGresult   *res;
3868         PublicationRelInfo *pubrinfo;
3869         int                     i_tableoid;
3870         int                     i_oid;
3871         int                     i_pubname;
3872         int                     i,
3873                                 j,
3874                                 ntups;
3875
3876         if (fout->remoteVersion < 100000)
3877                 return;
3878
3879         query = createPQExpBuffer();
3880
3881         for (i = 0; i < numTables; i++)
3882         {
3883                 TableInfo  *tbinfo = &tblinfo[i];
3884
3885                 /* Only plain tables can be aded to publications. */
3886                 if (tbinfo->relkind != RELKIND_RELATION)
3887                         continue;
3888
3889                 /*
3890                  * Ignore publication membership of tables whose definitions are not
3891                  * to be dumped.
3892                  */
3893                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3894                         continue;
3895
3896                 if (g_verbose)
3897                         write_msg(NULL, "reading publication membership for table \"%s.%s\"\n",
3898                                           tbinfo->dobj.namespace->dobj.name,
3899                                           tbinfo->dobj.name);
3900
3901                 resetPQExpBuffer(query);
3902
3903                 /* Get the publication membership for the table. */
3904                 appendPQExpBuffer(query,
3905                                                   "SELECT pr.tableoid, pr.oid, p.pubname "
3906                                                   "FROM pg_publication_rel pr, pg_publication p "
3907                                                   "WHERE pr.prrelid = '%u'"
3908                                                   "  AND p.oid = pr.prpubid",
3909                                                   tbinfo->dobj.catId.oid);
3910                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3911
3912                 ntups = PQntuples(res);
3913
3914                 if (ntups == 0)
3915                 {
3916                         /*
3917                          * Table is not member of any publications. Clean up and return.
3918                          */
3919                         PQclear(res);
3920                         continue;
3921                 }
3922
3923                 i_tableoid = PQfnumber(res, "tableoid");
3924                 i_oid = PQfnumber(res, "oid");
3925                 i_pubname = PQfnumber(res, "pubname");
3926
3927                 pubrinfo = pg_malloc(ntups * sizeof(PublicationRelInfo));
3928
3929                 for (j = 0; j < ntups; j++)
3930                 {
3931                         pubrinfo[j].dobj.objType = DO_PUBLICATION_REL;
3932                         pubrinfo[j].dobj.catId.tableoid =
3933                                 atooid(PQgetvalue(res, j, i_tableoid));
3934                         pubrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3935                         AssignDumpId(&pubrinfo[j].dobj);
3936                         pubrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3937                         pubrinfo[j].dobj.name = tbinfo->dobj.name;
3938                         pubrinfo[j].pubname = pg_strdup(PQgetvalue(res, j, i_pubname));
3939                         pubrinfo[j].pubtable = tbinfo;
3940
3941                         /* Decide whether we want to dump it */
3942                         selectDumpablePublicationTable(&(pubrinfo[j].dobj), fout);
3943                 }
3944                 PQclear(res);
3945         }
3946         destroyPQExpBuffer(query);
3947 }
3948
3949 /*
3950  * dumpPublicationTable
3951  *        dump the definition of the given publication table mapping
3952  */
3953 static void
3954 dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo)
3955 {
3956         TableInfo  *tbinfo = pubrinfo->pubtable;
3957         PQExpBuffer query;
3958         char       *tag;
3959
3960         if (!(pubrinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3961                 return;
3962
3963         tag = psprintf("%s %s", pubrinfo->pubname, tbinfo->dobj.name);
3964
3965         query = createPQExpBuffer();
3966
3967         appendPQExpBuffer(query, "ALTER PUBLICATION %s ADD TABLE ONLY",
3968                                           fmtId(pubrinfo->pubname));
3969         appendPQExpBuffer(query, " %s;\n",
3970                                           fmtQualifiedDumpable(tbinfo));
3971
3972         /*
3973          * There is no point in creating drop query as drop query as the drop is
3974          * done by table drop.
3975          */
3976         ArchiveEntry(fout, pubrinfo->dobj.catId, pubrinfo->dobj.dumpId,
3977                                  tag,
3978                                  tbinfo->dobj.namespace->dobj.name,
3979                                  NULL,
3980                                  "", false,
3981                                  "PUBLICATION TABLE", SECTION_POST_DATA,
3982                                  query->data, "", NULL,
3983                                  NULL, 0,
3984                                  NULL, NULL);
3985
3986         free(tag);
3987         destroyPQExpBuffer(query);
3988 }
3989
3990 /*
3991  * Is the currently connected user a superuser?
3992  */
3993 static bool
3994 is_superuser(Archive *fout)
3995 {
3996         ArchiveHandle *AH = (ArchiveHandle *) fout;
3997         const char *val;
3998
3999         val = PQparameterStatus(AH->connection, "is_superuser");
4000
4001         if (val && strcmp(val, "on") == 0)
4002                 return true;
4003
4004         return false;
4005 }
4006
4007 /*
4008  * getSubscriptions
4009  *        get information about subscriptions
4010  */
4011 void
4012 getSubscriptions(Archive *fout)
4013 {
4014         DumpOptions *dopt = fout->dopt;
4015         PQExpBuffer query;
4016         PGresult   *res;
4017         SubscriptionInfo *subinfo;
4018         int                     i_tableoid;
4019         int                     i_oid;
4020         int                     i_subname;
4021         int                     i_rolname;
4022         int                     i_subconninfo;
4023         int                     i_subslotname;
4024         int                     i_subsynccommit;
4025         int                     i_subpublications;
4026         int                     i,
4027                                 ntups;
4028
4029         if (dopt->no_subscriptions || fout->remoteVersion < 100000)
4030                 return;
4031
4032         if (!is_superuser(fout))
4033         {
4034                 int                     n;
4035
4036                 res = ExecuteSqlQuery(fout,
4037                                                           "SELECT count(*) FROM pg_subscription "
4038                                                           "WHERE subdbid = (SELECT oid FROM pg_database"
4039                                                           "                 WHERE datname = current_database())",
4040                                                           PGRES_TUPLES_OK);
4041                 n = atoi(PQgetvalue(res, 0, 0));
4042                 if (n > 0)
4043                         write_msg(NULL, "WARNING: subscriptions not dumped because current user is not a superuser\n");
4044                 PQclear(res);
4045                 return;
4046         }
4047
4048         query = createPQExpBuffer();
4049
4050         resetPQExpBuffer(query);
4051
4052         /* Get the subscriptions in current database. */
4053         appendPQExpBuffer(query,
4054                                           "SELECT s.tableoid, s.oid, s.subname,"
4055                                           "(%s s.subowner) AS rolname, "
4056                                           " s.subconninfo, s.subslotname, s.subsynccommit, "
4057                                           " s.subpublications "
4058                                           "FROM pg_subscription s "
4059                                           "WHERE s.subdbid = (SELECT oid FROM pg_database"
4060                                           "                   WHERE datname = current_database())",
4061                                           username_subquery);
4062         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4063
4064         ntups = PQntuples(res);
4065
4066         i_tableoid = PQfnumber(res, "tableoid");
4067         i_oid = PQfnumber(res, "oid");
4068         i_subname = PQfnumber(res, "subname");
4069         i_rolname = PQfnumber(res, "rolname");
4070         i_subconninfo = PQfnumber(res, "subconninfo");
4071         i_subslotname = PQfnumber(res, "subslotname");
4072         i_subsynccommit = PQfnumber(res, "subsynccommit");
4073         i_subpublications = PQfnumber(res, "subpublications");
4074
4075         subinfo = pg_malloc(ntups * sizeof(SubscriptionInfo));
4076
4077         for (i = 0; i < ntups; i++)
4078         {
4079                 subinfo[i].dobj.objType = DO_SUBSCRIPTION;
4080                 subinfo[i].dobj.catId.tableoid =
4081                         atooid(PQgetvalue(res, i, i_tableoid));
4082                 subinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4083                 AssignDumpId(&subinfo[i].dobj);
4084                 subinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_subname));
4085                 subinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4086                 subinfo[i].subconninfo = pg_strdup(PQgetvalue(res, i, i_subconninfo));
4087                 if (PQgetisnull(res, i, i_subslotname))
4088                         subinfo[i].subslotname = NULL;
4089                 else
4090                         subinfo[i].subslotname = pg_strdup(PQgetvalue(res, i, i_subslotname));
4091                 subinfo[i].subsynccommit =
4092                         pg_strdup(PQgetvalue(res, i, i_subsynccommit));
4093                 subinfo[i].subpublications =
4094                         pg_strdup(PQgetvalue(res, i, i_subpublications));
4095
4096                 if (strlen(subinfo[i].rolname) == 0)
4097                         write_msg(NULL, "WARNING: owner of subscription \"%s\" appears to be invalid\n",
4098                                           subinfo[i].dobj.name);
4099
4100                 /* Decide whether we want to dump it */
4101                 selectDumpableObject(&(subinfo[i].dobj), fout);
4102         }
4103         PQclear(res);
4104
4105         destroyPQExpBuffer(query);
4106 }
4107
4108 /*
4109  * dumpSubscription
4110  *        dump the definition of the given subscription
4111  */
4112 static void
4113 dumpSubscription(Archive *fout, SubscriptionInfo *subinfo)
4114 {
4115         PQExpBuffer delq;
4116         PQExpBuffer query;
4117         PQExpBuffer publications;
4118         char       *qsubname;
4119         char      **pubnames = NULL;
4120         int                     npubnames = 0;
4121         int                     i;
4122
4123         if (!(subinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
4124                 return;
4125
4126         delq = createPQExpBuffer();
4127         query = createPQExpBuffer();
4128
4129         qsubname = pg_strdup(fmtId(subinfo->dobj.name));
4130
4131         appendPQExpBuffer(delq, "DROP SUBSCRIPTION %s;\n",
4132                                           qsubname);
4133
4134         appendPQExpBuffer(query, "CREATE SUBSCRIPTION %s CONNECTION ",
4135                                           qsubname);
4136         appendStringLiteralAH(query, subinfo->subconninfo, fout);
4137
4138         /* Build list of quoted publications and append them to query. */
4139         if (!parsePGArray(subinfo->subpublications, &pubnames, &npubnames))
4140         {
4141                 write_msg(NULL,
4142                                   "WARNING: could not parse subpublications array\n");
4143                 if (pubnames)
4144                         free(pubnames);
4145                 pubnames = NULL;
4146                 npubnames = 0;
4147         }
4148
4149         publications = createPQExpBuffer();
4150         for (i = 0; i < npubnames; i++)
4151         {
4152                 if (i > 0)
4153                         appendPQExpBufferStr(publications, ", ");
4154
4155                 appendPQExpBufferStr(publications, fmtId(pubnames[i]));
4156         }
4157
4158         appendPQExpBuffer(query, " PUBLICATION %s WITH (connect = false, slot_name = ", publications->data);
4159         if (subinfo->subslotname)
4160                 appendStringLiteralAH(query, subinfo->subslotname, fout);
4161         else
4162                 appendPQExpBufferStr(query, "NONE");
4163
4164         if (strcmp(subinfo->subsynccommit, "off") != 0)
4165                 appendPQExpBuffer(query, ", synchronous_commit = %s", fmtId(subinfo->subsynccommit));
4166
4167         appendPQExpBufferStr(query, ");\n");
4168
4169         ArchiveEntry(fout, subinfo->dobj.catId, subinfo->dobj.dumpId,
4170                                  subinfo->dobj.name,
4171                                  NULL,
4172                                  NULL,
4173                                  subinfo->rolname, false,
4174                                  "SUBSCRIPTION", SECTION_POST_DATA,
4175                                  query->data, delq->data, NULL,
4176                                  NULL, 0,
4177                                  NULL, NULL);
4178
4179         if (subinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
4180                 dumpComment(fout, "SUBSCRIPTION", qsubname,
4181                                         NULL, subinfo->rolname,
4182                                         subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
4183
4184         if (subinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
4185                 dumpSecLabel(fout, "SUBSCRIPTION", qsubname,
4186                                          NULL, subinfo->rolname,
4187                                          subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
4188
4189         destroyPQExpBuffer(publications);
4190         if (pubnames)
4191                 free(pubnames);
4192
4193         destroyPQExpBuffer(delq);
4194         destroyPQExpBuffer(query);
4195         free(qsubname);
4196 }
4197
4198 static void
4199 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
4200                                                                                  PQExpBuffer upgrade_buffer,
4201                                                                                  Oid pg_type_oid,
4202                                                                                  bool force_array_type)
4203 {
4204         PQExpBuffer upgrade_query = createPQExpBuffer();
4205         PGresult   *res;
4206         Oid                     pg_type_array_oid;
4207
4208         appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
4209         appendPQExpBuffer(upgrade_buffer,
4210                                           "SELECT pg_catalog.binary_upgrade_set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4211                                           pg_type_oid);
4212
4213         /* we only support old >= 8.3 for binary upgrades */
4214         appendPQExpBuffer(upgrade_query,
4215                                           "SELECT typarray "
4216                                           "FROM pg_catalog.pg_type "
4217                                           "WHERE oid = '%u'::pg_catalog.oid;",
4218                                           pg_type_oid);
4219
4220         res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4221
4222         pg_type_array_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typarray")));
4223
4224         PQclear(res);
4225
4226         if (!OidIsValid(pg_type_array_oid) && force_array_type)
4227         {
4228                 /*
4229                  * If the old version didn't assign an array type, but the new version
4230                  * does, we must select an unused type OID to assign.  This currently
4231                  * only happens for domains, when upgrading pre-v11 to v11 and up.
4232                  *
4233                  * Note: local state here is kind of ugly, but we must have some,
4234                  * since we mustn't choose the same unused OID more than once.
4235                  */
4236                 static Oid      next_possible_free_oid = FirstNormalObjectId;
4237                 bool            is_dup;
4238
4239                 do
4240                 {
4241                         ++next_possible_free_oid;
4242                         printfPQExpBuffer(upgrade_query,
4243                                                           "SELECT EXISTS(SELECT 1 "
4244                                                           "FROM pg_catalog.pg_type "
4245                                                           "WHERE oid = '%u'::pg_catalog.oid);",
4246                                                           next_possible_free_oid);
4247                         res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4248                         is_dup = (PQgetvalue(res, 0, 0)[0] == 't');
4249                         PQclear(res);
4250                 } while (is_dup);
4251
4252                 pg_type_array_oid = next_possible_free_oid;
4253         }
4254
4255         if (OidIsValid(pg_type_array_oid))
4256         {
4257                 appendPQExpBufferStr(upgrade_buffer,
4258                                                          "\n-- For binary upgrade, must preserve pg_type array oid\n");
4259                 appendPQExpBuffer(upgrade_buffer,
4260                                                   "SELECT pg_catalog.binary_upgrade_set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4261                                                   pg_type_array_oid);
4262         }
4263
4264         destroyPQExpBuffer(upgrade_query);
4265 }
4266
4267 static bool
4268 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
4269                                                                                 PQExpBuffer upgrade_buffer,
4270                                                                                 Oid pg_rel_oid)
4271 {
4272         PQExpBuffer upgrade_query = createPQExpBuffer();
4273         PGresult   *upgrade_res;
4274         Oid                     pg_type_oid;
4275         bool            toast_set = false;
4276
4277         /* we only support old >= 8.3 for binary upgrades */
4278         appendPQExpBuffer(upgrade_query,
4279                                           "SELECT c.reltype AS crel, t.reltype AS trel "
4280                                           "FROM pg_catalog.pg_class c "
4281                                           "LEFT JOIN pg_catalog.pg_class t ON "
4282                                           "  (c.reltoastrelid = t.oid) "
4283                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
4284                                           pg_rel_oid);
4285
4286         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4287
4288         pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
4289
4290         binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
4291                                                                                          pg_type_oid, false);
4292
4293         if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
4294         {
4295                 /* Toast tables do not have pg_type array rows */
4296                 Oid                     pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
4297                                                                                                                   PQfnumber(upgrade_res, "trel")));
4298
4299                 appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
4300                 appendPQExpBuffer(upgrade_buffer,
4301                                                   "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4302                                                   pg_type_toast_oid);
4303
4304                 toast_set = true;
4305         }
4306
4307         PQclear(upgrade_res);
4308         destroyPQExpBuffer(upgrade_query);
4309
4310         return toast_set;
4311 }
4312
4313 static void
4314 binary_upgrade_set_pg_class_oids(Archive *fout,
4315                                                                  PQExpBuffer upgrade_buffer, Oid pg_class_oid,
4316                                                                  bool is_index)
4317 {
4318         PQExpBuffer upgrade_query = createPQExpBuffer();
4319         PGresult   *upgrade_res;
4320         Oid                     pg_class_reltoastrelid;
4321         Oid                     pg_index_indexrelid;
4322
4323         appendPQExpBuffer(upgrade_query,
4324                                           "SELECT c.reltoastrelid, i.indexrelid "
4325                                           "FROM pg_catalog.pg_class c LEFT JOIN "
4326                                           "pg_catalog.pg_index i ON (c.reltoastrelid = i.indrelid AND i.indisvalid) "
4327                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
4328                                           pg_class_oid);
4329
4330         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4331
4332         pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
4333         pg_index_indexrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "indexrelid")));
4334
4335         appendPQExpBufferStr(upgrade_buffer,
4336                                                  "\n-- For binary upgrade, must preserve pg_class oids\n");
4337
4338         if (!is_index)
4339         {
4340                 appendPQExpBuffer(upgrade_buffer,
4341                                                   "SELECT pg_catalog.binary_upgrade_set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
4342                                                   pg_class_oid);
4343                 /* only tables have toast tables, not indexes */
4344                 if (OidIsValid(pg_class_reltoastrelid))
4345                 {
4346                         /*
4347                          * One complexity is that the table definition might not require
4348                          * the creation of a TOAST table, and the TOAST table might have
4349                          * been created long after table creation, when the table was
4350                          * loaded with wide data.  By setting the TOAST oid we force
4351                          * creation of the TOAST heap and TOAST index by the backend so we
4352                          * can cleanly copy the files during binary upgrade.
4353                          */
4354
4355                         appendPQExpBuffer(upgrade_buffer,
4356                                                           "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
4357                                                           pg_class_reltoastrelid);
4358
4359                         /* every toast table has an index */
4360                         appendPQExpBuffer(upgrade_buffer,
4361                                                           "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4362                                                           pg_index_indexrelid);
4363                 }
4364         }
4365         else
4366                 appendPQExpBuffer(upgrade_buffer,
4367                                                   "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4368                                                   pg_class_oid);
4369
4370         appendPQExpBufferChar(upgrade_buffer, '\n');
4371
4372         PQclear(upgrade_res);
4373         destroyPQExpBuffer(upgrade_query);
4374 }
4375
4376 /*
4377  * If the DumpableObject is a member of an extension, add a suitable
4378  * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
4379  *
4380  * For somewhat historical reasons, objname should already be quoted,
4381  * but not objnamespace (if any).
4382  */
4383 static void
4384 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
4385                                                                 DumpableObject *dobj,
4386                                                                 const char *objtype,
4387                                                                 const char *objname,
4388                                                                 const char *objnamespace)
4389 {
4390         DumpableObject *extobj = NULL;
4391         int                     i;
4392
4393         if (!dobj->ext_member)
4394                 return;
4395
4396         /*
4397          * Find the parent extension.  We could avoid this search if we wanted to
4398          * add a link field to DumpableObject, but the space costs of that would
4399          * be considerable.  We assume that member objects could only have a
4400          * direct dependency on their own extension, not any others.
4401          */
4402         for (i = 0; i < dobj->nDeps; i++)
4403         {
4404                 extobj = findObjectByDumpId(dobj->dependencies[i]);
4405                 if (extobj && extobj->objType == DO_EXTENSION)
4406                         break;
4407                 extobj = NULL;
4408         }
4409         if (extobj == NULL)
4410                 exit_horribly(NULL, "could not find parent extension for %s %s\n",
4411                                           objtype, objname);
4412
4413         appendPQExpBufferStr(upgrade_buffer,
4414                                                  "\n-- For binary upgrade, handle extension membership the hard way\n");
4415         appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s ",
4416                                           fmtId(extobj->name),
4417                                           objtype);
4418         if (objnamespace && *objnamespace)
4419                 appendPQExpBuffer(upgrade_buffer, "%s.", fmtId(objnamespace));
4420         appendPQExpBuffer(upgrade_buffer, "%s;\n", objname);
4421 }
4422
4423 /*
4424  * getNamespaces:
4425  *        read all namespaces in the system catalogs and return them in the
4426  * NamespaceInfo* structure
4427  *
4428  *      numNamespaces is set to the number of namespaces read in
4429  */
4430 NamespaceInfo *
4431 getNamespaces(Archive *fout, int *numNamespaces)
4432 {
4433         DumpOptions *dopt = fout->dopt;
4434         PGresult   *res;
4435         int                     ntups;
4436         int                     i;
4437         PQExpBuffer query;
4438         NamespaceInfo *nsinfo;
4439         int                     i_tableoid;
4440         int                     i_oid;
4441         int                     i_nspname;
4442         int                     i_rolname;
4443         int                     i_nspacl;
4444         int                     i_rnspacl;
4445         int                     i_initnspacl;
4446         int                     i_initrnspacl;
4447
4448         query = createPQExpBuffer();
4449
4450         /*
4451          * we fetch all namespaces including system ones, so that every object we
4452          * read in can be linked to a containing namespace.
4453          */
4454         if (fout->remoteVersion >= 90600)
4455         {
4456                 PQExpBuffer acl_subquery = createPQExpBuffer();
4457                 PQExpBuffer racl_subquery = createPQExpBuffer();
4458                 PQExpBuffer init_acl_subquery = createPQExpBuffer();
4459                 PQExpBuffer init_racl_subquery = createPQExpBuffer();
4460
4461                 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
4462                                                 init_racl_subquery, "n.nspacl", "n.nspowner", "'n'",
4463                                                 dopt->binary_upgrade);
4464
4465                 appendPQExpBuffer(query, "SELECT n.tableoid, n.oid, n.nspname, "
4466                                                   "(%s nspowner) AS rolname, "
4467                                                   "%s as nspacl, "
4468                                                   "%s as rnspacl, "
4469                                                   "%s as initnspacl, "
4470                                                   "%s as initrnspacl "
4471                                                   "FROM pg_namespace n "
4472                                                   "LEFT JOIN pg_init_privs pip "
4473                                                   "ON (n.oid = pip.objoid "
4474                                                   "AND pip.classoid = 'pg_namespace'::regclass "
4475                                                   "AND pip.objsubid = 0",
4476                                                   username_subquery,
4477                                                   acl_subquery->data,
4478                                                   racl_subquery->data,
4479                                                   init_acl_subquery->data,
4480                                                   init_racl_subquery->data);
4481
4482                 appendPQExpBuffer(query, ") ");
4483
4484                 destroyPQExpBuffer(acl_subquery);
4485                 destroyPQExpBuffer(racl_subquery);
4486                 destroyPQExpBuffer(init_acl_subquery);
4487                 destroyPQExpBuffer(init_racl_subquery);
4488         }
4489         else
4490                 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
4491                                                   "(%s nspowner) AS rolname, "
4492                                                   "nspacl, NULL as rnspacl, "
4493                                                   "NULL AS initnspacl, NULL as initrnspacl "
4494                                                   "FROM pg_namespace",
4495                                                   username_subquery);
4496
4497         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4498
4499         ntups = PQntuples(res);
4500
4501         nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
4502
4503         i_tableoid = PQfnumber(res, "tableoid");
4504         i_oid = PQfnumber(res, "oid");
4505         i_nspname = PQfnumber(res, "nspname");
4506         i_rolname = PQfnumber(res, "rolname");
4507         i_nspacl = PQfnumber(res, "nspacl");
4508         i_rnspacl = PQfnumber(res, "rnspacl");
4509         i_initnspacl = PQfnumber(res, "initnspacl");
4510         i_initrnspacl = PQfnumber(res, "initrnspacl");
4511
4512         for (i = 0; i < ntups; i++)
4513         {
4514                 nsinfo[i].dobj.objType = DO_NAMESPACE;
4515                 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4516                 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4517                 AssignDumpId(&nsinfo[i].dobj);
4518                 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
4519                 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4520                 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
4521                 nsinfo[i].rnspacl = pg_strdup(PQgetvalue(res, i, i_rnspacl));
4522                 nsinfo[i].initnspacl = pg_strdup(PQgetvalue(res, i, i_initnspacl));
4523                 nsinfo[i].initrnspacl = pg_strdup(PQgetvalue(res, i, i_initrnspacl));
4524
4525                 /* Decide whether to dump this namespace */
4526                 selectDumpableNamespace(&nsinfo[i], fout);
4527
4528                 /*
4529                  * Do not try to dump ACL if the ACL is empty or the default.
4530                  *
4531                  * This is useful because, for some schemas/objects, the only
4532                  * component we are going to try and dump is the ACL and if we can
4533                  * remove that then 'dump' goes to zero/false and we don't consider
4534                  * this object for dumping at all later on.
4535                  */
4536                 if (PQgetisnull(res, i, i_nspacl) && PQgetisnull(res, i, i_rnspacl) &&
4537                         PQgetisnull(res, i, i_initnspacl) &&
4538                         PQgetisnull(res, i, i_initrnspacl))
4539                         nsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4540
4541                 if (strlen(nsinfo[i].rolname) == 0)
4542                         write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
4543                                           nsinfo[i].dobj.name);
4544         }
4545
4546         PQclear(res);
4547         destroyPQExpBuffer(query);
4548
4549         *numNamespaces = ntups;
4550
4551         return nsinfo;
4552 }
4553
4554 /*
4555  * findNamespace:
4556  *              given a namespace OID, look up the info read by getNamespaces
4557  */
4558 static NamespaceInfo *
4559 findNamespace(Archive *fout, Oid nsoid)
4560 {
4561         NamespaceInfo *nsinfo;
4562
4563         nsinfo = findNamespaceByOid(nsoid);
4564         if (nsinfo == NULL)
4565                 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
4566         return nsinfo;
4567 }
4568
4569 /*
4570  * getExtensions:
4571  *        read all extensions in the system catalogs and return them in the
4572  * ExtensionInfo* structure
4573  *
4574  *      numExtensions is set to the number of extensions read in
4575  */
4576 ExtensionInfo *
4577 getExtensions(Archive *fout, int *numExtensions)
4578 {
4579         DumpOptions *dopt = fout->dopt;
4580         PGresult   *res;
4581         int                     ntups;
4582         int                     i;
4583         PQExpBuffer query;
4584         ExtensionInfo *extinfo;
4585         int                     i_tableoid;
4586         int                     i_oid;
4587         int                     i_extname;
4588         int                     i_nspname;
4589         int                     i_extrelocatable;
4590         int                     i_extversion;
4591         int                     i_extconfig;
4592         int                     i_extcondition;
4593
4594         /*
4595          * Before 9.1, there are no extensions.
4596          */
4597         if (fout->remoteVersion < 90100)
4598         {
4599                 *numExtensions = 0;
4600                 return NULL;
4601         }
4602
4603         query = createPQExpBuffer();
4604
4605         appendPQExpBufferStr(query, "SELECT x.tableoid, x.oid, "
4606                                                  "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
4607                                                  "FROM pg_extension x "
4608                                                  "JOIN pg_namespace n ON n.oid = x.extnamespace");
4609
4610         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4611
4612         ntups = PQntuples(res);
4613
4614         extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
4615
4616         i_tableoid = PQfnumber(res, "tableoid");
4617         i_oid = PQfnumber(res, "oid");
4618         i_extname = PQfnumber(res, "extname");
4619         i_nspname = PQfnumber(res, "nspname");
4620         i_extrelocatable = PQfnumber(res, "extrelocatable");
4621         i_extversion = PQfnumber(res, "extversion");
4622         i_extconfig = PQfnumber(res, "extconfig");
4623         i_extcondition = PQfnumber(res, "extcondition");
4624
4625         for (i = 0; i < ntups; i++)
4626         {
4627                 extinfo[i].dobj.objType = DO_EXTENSION;
4628                 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4629                 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4630                 AssignDumpId(&extinfo[i].dobj);
4631                 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
4632                 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
4633                 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
4634                 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
4635                 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
4636                 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
4637
4638                 /* Decide whether we want to dump it */
4639                 selectDumpableExtension(&(extinfo[i]), dopt);
4640         }
4641
4642         PQclear(res);
4643         destroyPQExpBuffer(query);
4644
4645         *numExtensions = ntups;
4646
4647         return extinfo;
4648 }
4649
4650 /*
4651  * getTypes:
4652  *        read all types in the system catalogs and return them in the
4653  * TypeInfo* structure
4654  *
4655  *      numTypes is set to the number of types read in
4656  *
4657  * NB: this must run after getFuncs() because we assume we can do
4658  * findFuncByOid().
4659  */
4660 TypeInfo *
4661 getTypes(Archive *fout, int *numTypes)
4662 {
4663         DumpOptions *dopt = fout->dopt;
4664         PGresult   *res;
4665         int                     ntups;
4666         int                     i;
4667         PQExpBuffer query = createPQExpBuffer();
4668         TypeInfo   *tyinfo;
4669         ShellTypeInfo *stinfo;
4670         int                     i_tableoid;
4671         int                     i_oid;
4672         int                     i_typname;
4673         int                     i_typnamespace;
4674         int                     i_typacl;
4675         int                     i_rtypacl;
4676         int                     i_inittypacl;
4677         int                     i_initrtypacl;
4678         int                     i_rolname;
4679         int                     i_typelem;
4680         int                     i_typrelid;
4681         int                     i_typrelkind;
4682         int                     i_typtype;
4683         int                     i_typisdefined;
4684         int                     i_isarray;
4685
4686         /*
4687          * we include even the built-in types because those may be used as array
4688          * elements by user-defined types
4689          *
4690          * we filter out the built-in types when we dump out the types
4691          *
4692          * same approach for undefined (shell) types and array types
4693          *
4694          * Note: as of 8.3 we can reliably detect whether a type is an
4695          * auto-generated array type by checking the element type's typarray.
4696          * (Before that the test is capable of generating false positives.) We
4697          * still check for name beginning with '_', though, so as to avoid the
4698          * cost of the subselect probe for all standard types.  This would have to
4699          * be revisited if the backend ever allows renaming of array types.
4700          */
4701
4702         if (fout->remoteVersion >= 90600)
4703         {
4704                 PQExpBuffer acl_subquery = createPQExpBuffer();
4705                 PQExpBuffer racl_subquery = createPQExpBuffer();
4706                 PQExpBuffer initacl_subquery = createPQExpBuffer();
4707                 PQExpBuffer initracl_subquery = createPQExpBuffer();
4708
4709                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
4710                                                 initracl_subquery, "t.typacl", "t.typowner", "'T'",
4711                                                 dopt->binary_upgrade);
4712
4713                 appendPQExpBuffer(query, "SELECT t.tableoid, t.oid, t.typname, "
4714                                                   "t.typnamespace, "
4715                                                   "%s AS typacl, "
4716                                                   "%s AS rtypacl, "
4717                                                   "%s AS inittypacl, "
4718                                                   "%s AS initrtypacl, "
4719                                                   "(%s t.typowner) AS rolname, "
4720                                                   "t.typelem, t.typrelid, "
4721                                                   "CASE WHEN t.typrelid = 0 THEN ' '::\"char\" "
4722                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = t.typrelid) END AS typrelkind, "
4723                                                   "t.typtype, t.typisdefined, "
4724                                                   "t.typname[0] = '_' AND t.typelem != 0 AND "
4725                                                   "(SELECT typarray FROM pg_type te WHERE oid = t.typelem) = t.oid AS isarray "
4726                                                   "FROM pg_type t "
4727                                                   "LEFT JOIN pg_init_privs pip ON "
4728                                                   "(t.oid = pip.objoid "
4729                                                   "AND pip.classoid = 'pg_type'::regclass "
4730                                                   "AND pip.objsubid = 0) ",
4731                                                   acl_subquery->data,
4732                                                   racl_subquery->data,
4733                                                   initacl_subquery->data,
4734                                                   initracl_subquery->data,
4735                                                   username_subquery);
4736
4737                 destroyPQExpBuffer(acl_subquery);
4738                 destroyPQExpBuffer(racl_subquery);
4739                 destroyPQExpBuffer(initacl_subquery);
4740                 destroyPQExpBuffer(initracl_subquery);
4741         }
4742         else if (fout->remoteVersion >= 90200)
4743         {
4744                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4745                                                   "typnamespace, typacl, NULL as rtypacl, "
4746                                                   "NULL AS inittypacl, NULL AS initrtypacl, "
4747                                                   "(%s typowner) AS rolname, "
4748                                                   "typelem, typrelid, "
4749                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4750                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4751                                                   "typtype, typisdefined, "
4752                                                   "typname[0] = '_' AND typelem != 0 AND "
4753                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4754                                                   "FROM pg_type",
4755                                                   username_subquery);
4756         }
4757         else if (fout->remoteVersion >= 80300)
4758         {
4759                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4760                                                   "typnamespace, NULL AS typacl, NULL as rtypacl, "
4761                                                   "NULL AS inittypacl, NULL AS initrtypacl, "
4762                                                   "(%s typowner) AS rolname, "
4763                                                   "typelem, typrelid, "
4764                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4765                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4766                                                   "typtype, typisdefined, "
4767                                                   "typname[0] = '_' AND typelem != 0 AND "
4768                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4769                                                   "FROM pg_type",
4770                                                   username_subquery);
4771         }
4772         else
4773         {
4774                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4775                                                   "typnamespace, NULL AS typacl, NULL as rtypacl, "
4776                                                   "NULL AS inittypacl, NULL AS initrtypacl, "
4777                                                   "(%s typowner) AS rolname, "
4778                                                   "typelem, typrelid, "
4779                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4780                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4781                                                   "typtype, typisdefined, "
4782                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
4783                                                   "FROM pg_type",
4784                                                   username_subquery);
4785         }
4786
4787         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4788
4789         ntups = PQntuples(res);
4790
4791         tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
4792
4793         i_tableoid = PQfnumber(res, "tableoid");
4794         i_oid = PQfnumber(res, "oid");
4795         i_typname = PQfnumber(res, "typname");
4796         i_typnamespace = PQfnumber(res, "typnamespace");
4797         i_typacl = PQfnumber(res, "typacl");
4798         i_rtypacl = PQfnumber(res, "rtypacl");
4799         i_inittypacl = PQfnumber(res, "inittypacl");
4800         i_initrtypacl = PQfnumber(res, "initrtypacl");
4801         i_rolname = PQfnumber(res, "rolname");
4802         i_typelem = PQfnumber(res, "typelem");
4803         i_typrelid = PQfnumber(res, "typrelid");
4804         i_typrelkind = PQfnumber(res, "typrelkind");
4805         i_typtype = PQfnumber(res, "typtype");
4806         i_typisdefined = PQfnumber(res, "typisdefined");
4807         i_isarray = PQfnumber(res, "isarray");
4808
4809         for (i = 0; i < ntups; i++)
4810         {
4811                 tyinfo[i].dobj.objType = DO_TYPE;
4812                 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4813                 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4814                 AssignDumpId(&tyinfo[i].dobj);
4815                 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
4816                 tyinfo[i].dobj.namespace =
4817                         findNamespace(fout,
4818                                                   atooid(PQgetvalue(res, i, i_typnamespace)));
4819                 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4820                 tyinfo[i].typacl = pg_strdup(PQgetvalue(res, i, i_typacl));
4821                 tyinfo[i].rtypacl = pg_strdup(PQgetvalue(res, i, i_rtypacl));
4822                 tyinfo[i].inittypacl = pg_strdup(PQgetvalue(res, i, i_inittypacl));
4823                 tyinfo[i].initrtypacl = pg_strdup(PQgetvalue(res, i, i_initrtypacl));
4824                 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
4825                 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
4826                 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
4827                 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
4828                 tyinfo[i].shellType = NULL;
4829
4830                 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
4831                         tyinfo[i].isDefined = true;
4832                 else
4833                         tyinfo[i].isDefined = false;
4834
4835                 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
4836                         tyinfo[i].isArray = true;
4837                 else
4838                         tyinfo[i].isArray = false;
4839
4840                 /* Decide whether we want to dump it */
4841                 selectDumpableType(&tyinfo[i], fout);
4842
4843                 /* Do not try to dump ACL if no ACL exists. */
4844                 if (PQgetisnull(res, i, i_typacl) && PQgetisnull(res, i, i_rtypacl) &&
4845                         PQgetisnull(res, i, i_inittypacl) &&
4846                         PQgetisnull(res, i, i_initrtypacl))
4847                         tyinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4848
4849                 /*
4850                  * If it's a domain, fetch info about its constraints, if any
4851                  */
4852                 tyinfo[i].nDomChecks = 0;
4853                 tyinfo[i].domChecks = NULL;
4854                 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4855                         tyinfo[i].typtype == TYPTYPE_DOMAIN)
4856                         getDomainConstraints(fout, &(tyinfo[i]));
4857
4858                 /*
4859                  * If it's a base type, make a DumpableObject representing a shell
4860                  * definition of the type.  We will need to dump that ahead of the I/O
4861                  * functions for the type.  Similarly, range types need a shell
4862                  * definition in case they have a canonicalize function.
4863                  *
4864                  * Note: the shell type doesn't have a catId.  You might think it
4865                  * should copy the base type's catId, but then it might capture the
4866                  * pg_depend entries for the type, which we don't want.
4867                  */
4868                 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4869                         (tyinfo[i].typtype == TYPTYPE_BASE ||
4870                          tyinfo[i].typtype == TYPTYPE_RANGE))
4871                 {
4872                         stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
4873                         stinfo->dobj.objType = DO_SHELL_TYPE;
4874                         stinfo->dobj.catId = nilCatalogId;
4875                         AssignDumpId(&stinfo->dobj);
4876                         stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
4877                         stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
4878                         stinfo->baseType = &(tyinfo[i]);
4879                         tyinfo[i].shellType = stinfo;
4880
4881                         /*
4882                          * Initially mark the shell type as not to be dumped.  We'll only
4883                          * dump it if the I/O or canonicalize functions need to be dumped;
4884                          * this is taken care of while sorting dependencies.
4885                          */
4886                         stinfo->dobj.dump = DUMP_COMPONENT_NONE;
4887                 }
4888
4889                 if (strlen(tyinfo[i].rolname) == 0)
4890                         write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
4891                                           tyinfo[i].dobj.name);
4892         }
4893
4894         *numTypes = ntups;
4895
4896         PQclear(res);
4897
4898         destroyPQExpBuffer(query);
4899
4900         return tyinfo;
4901 }
4902
4903 /*
4904  * getOperators:
4905  *        read all operators in the system catalogs and return them in the
4906  * OprInfo* structure
4907  *
4908  *      numOprs is set to the number of operators read in
4909  */
4910 OprInfo *
4911 getOperators(Archive *fout, int *numOprs)
4912 {
4913         PGresult   *res;
4914         int                     ntups;
4915         int                     i;
4916         PQExpBuffer query = createPQExpBuffer();
4917         OprInfo    *oprinfo;
4918         int                     i_tableoid;
4919         int                     i_oid;
4920         int                     i_oprname;
4921         int                     i_oprnamespace;
4922         int                     i_rolname;
4923         int                     i_oprkind;
4924         int                     i_oprcode;
4925
4926         /*
4927          * find all operators, including builtin operators; we filter out
4928          * system-defined operators at dump-out time.
4929          */
4930
4931         appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
4932                                           "oprnamespace, "
4933                                           "(%s oprowner) AS rolname, "
4934                                           "oprkind, "
4935                                           "oprcode::oid AS oprcode "
4936                                           "FROM pg_operator",
4937                                           username_subquery);
4938
4939         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4940
4941         ntups = PQntuples(res);
4942         *numOprs = ntups;
4943
4944         oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
4945
4946         i_tableoid = PQfnumber(res, "tableoid");
4947         i_oid = PQfnumber(res, "oid");
4948         i_oprname = PQfnumber(res, "oprname");
4949         i_oprnamespace = PQfnumber(res, "oprnamespace");
4950         i_rolname = PQfnumber(res, "rolname");
4951         i_oprkind = PQfnumber(res, "oprkind");
4952         i_oprcode = PQfnumber(res, "oprcode");
4953
4954         for (i = 0; i < ntups; i++)
4955         {
4956                 oprinfo[i].dobj.objType = DO_OPERATOR;
4957                 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4958                 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4959                 AssignDumpId(&oprinfo[i].dobj);
4960                 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
4961                 oprinfo[i].dobj.namespace =
4962                         findNamespace(fout,
4963                                                   atooid(PQgetvalue(res, i, i_oprnamespace)));
4964                 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4965                 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
4966                 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
4967
4968                 /* Decide whether we want to dump it */
4969                 selectDumpableObject(&(oprinfo[i].dobj), fout);
4970
4971                 /* Operators do not currently have ACLs. */
4972                 oprinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4973
4974                 if (strlen(oprinfo[i].rolname) == 0)
4975                         write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
4976                                           oprinfo[i].dobj.name);
4977         }
4978
4979         PQclear(res);
4980
4981         destroyPQExpBuffer(query);
4982
4983         return oprinfo;
4984 }
4985
4986 /*
4987  * getCollations:
4988  *        read all collations in the system catalogs and return them in the
4989  * CollInfo* structure
4990  *
4991  *      numCollations is set to the number of collations read in
4992  */
4993 CollInfo *
4994 getCollations(Archive *fout, int *numCollations)
4995 {
4996         PGresult   *res;
4997         int                     ntups;
4998         int                     i;
4999         PQExpBuffer query;
5000         CollInfo   *collinfo;
5001         int                     i_tableoid;
5002         int                     i_oid;
5003         int                     i_collname;
5004         int                     i_collnamespace;
5005         int                     i_rolname;
5006
5007         /* Collations didn't exist pre-9.1 */
5008         if (fout->remoteVersion < 90100)
5009         {
5010                 *numCollations = 0;
5011                 return NULL;
5012         }
5013
5014         query = createPQExpBuffer();
5015
5016         /*
5017          * find all collations, including builtin collations; we filter out
5018          * system-defined collations at dump-out time.
5019          */
5020
5021         appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
5022                                           "collnamespace, "
5023                                           "(%s collowner) AS rolname "
5024                                           "FROM pg_collation",
5025                                           username_subquery);
5026
5027         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5028
5029         ntups = PQntuples(res);
5030         *numCollations = ntups;
5031
5032         collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
5033
5034         i_tableoid = PQfnumber(res, "tableoid");
5035         i_oid = PQfnumber(res, "oid");
5036         i_collname = PQfnumber(res, "collname");
5037         i_collnamespace = PQfnumber(res, "collnamespace");
5038         i_rolname = PQfnumber(res, "rolname");
5039
5040         for (i = 0; i < ntups; i++)
5041         {
5042                 collinfo[i].dobj.objType = DO_COLLATION;
5043                 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5044                 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5045                 AssignDumpId(&collinfo[i].dobj);
5046                 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
5047                 collinfo[i].dobj.namespace =
5048                         findNamespace(fout,
5049                                                   atooid(PQgetvalue(res, i, i_collnamespace)));
5050                 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5051
5052                 /* Decide whether we want to dump it */
5053                 selectDumpableObject(&(collinfo[i].dobj), fout);
5054
5055                 /* Collations do not currently have ACLs. */
5056                 collinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5057         }
5058
5059         PQclear(res);
5060
5061         destroyPQExpBuffer(query);
5062
5063         return collinfo;
5064 }
5065
5066 /*
5067  * getConversions:
5068  *        read all conversions in the system catalogs and return them in the
5069  * ConvInfo* structure
5070  *
5071  *      numConversions is set to the number of conversions read in
5072  */
5073 ConvInfo *
5074 getConversions(Archive *fout, int *numConversions)
5075 {
5076         PGresult   *res;
5077         int                     ntups;
5078         int                     i;
5079         PQExpBuffer query;
5080         ConvInfo   *convinfo;
5081         int                     i_tableoid;
5082         int                     i_oid;
5083         int                     i_conname;
5084         int                     i_connamespace;
5085         int                     i_rolname;
5086
5087         query = createPQExpBuffer();
5088
5089         /*
5090          * find all conversions, including builtin conversions; we filter out
5091          * system-defined conversions at dump-out time.
5092          */
5093
5094         appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5095                                           "connamespace, "
5096                                           "(%s conowner) AS rolname "
5097                                           "FROM pg_conversion",
5098                                           username_subquery);
5099
5100         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5101
5102         ntups = PQntuples(res);
5103         *numConversions = ntups;
5104
5105         convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
5106
5107         i_tableoid = PQfnumber(res, "tableoid");
5108         i_oid = PQfnumber(res, "oid");
5109         i_conname = PQfnumber(res, "conname");
5110         i_connamespace = PQfnumber(res, "connamespace");
5111         i_rolname = PQfnumber(res, "rolname");
5112
5113         for (i = 0; i < ntups; i++)
5114         {
5115                 convinfo[i].dobj.objType = DO_CONVERSION;
5116                 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5117                 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5118                 AssignDumpId(&convinfo[i].dobj);
5119                 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5120                 convinfo[i].dobj.namespace =
5121                         findNamespace(fout,
5122                                                   atooid(PQgetvalue(res, i, i_connamespace)));
5123                 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5124
5125                 /* Decide whether we want to dump it */
5126                 selectDumpableObject(&(convinfo[i].dobj), fout);
5127
5128                 /* Conversions do not currently have ACLs. */
5129                 convinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5130         }
5131
5132         PQclear(res);
5133
5134         destroyPQExpBuffer(query);
5135
5136         return convinfo;
5137 }
5138
5139 /*
5140  * getAccessMethods:
5141  *        read all user-defined access methods in the system catalogs and return
5142  *        them in the AccessMethodInfo* structure
5143  *
5144  *      numAccessMethods is set to the number of access methods read in
5145  */
5146 AccessMethodInfo *
5147 getAccessMethods(Archive *fout, int *numAccessMethods)
5148 {
5149         PGresult   *res;
5150         int                     ntups;
5151         int                     i;
5152         PQExpBuffer query;
5153         AccessMethodInfo *aminfo;
5154         int                     i_tableoid;
5155         int                     i_oid;
5156         int                     i_amname;
5157         int                     i_amhandler;
5158         int                     i_amtype;
5159
5160         /* Before 9.6, there are no user-defined access methods */
5161         if (fout->remoteVersion < 90600)
5162         {
5163                 *numAccessMethods = 0;
5164                 return NULL;
5165         }
5166
5167         query = createPQExpBuffer();
5168
5169         /* Select all access methods from pg_am table */
5170         appendPQExpBuffer(query, "SELECT tableoid, oid, amname, amtype, "
5171                                           "amhandler::pg_catalog.regproc AS amhandler "
5172                                           "FROM pg_am");
5173
5174         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5175
5176         ntups = PQntuples(res);
5177         *numAccessMethods = ntups;
5178
5179         aminfo = (AccessMethodInfo *) pg_malloc(ntups * sizeof(AccessMethodInfo));
5180
5181         i_tableoid = PQfnumber(res, "tableoid");
5182         i_oid = PQfnumber(res, "oid");
5183         i_amname = PQfnumber(res, "amname");
5184         i_amhandler = PQfnumber(res, "amhandler");
5185         i_amtype = PQfnumber(res, "amtype");
5186
5187         for (i = 0; i < ntups; i++)
5188         {
5189                 aminfo[i].dobj.objType = DO_ACCESS_METHOD;
5190                 aminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5191                 aminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5192                 AssignDumpId(&aminfo[i].dobj);
5193                 aminfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_amname));
5194                 aminfo[i].dobj.namespace = NULL;
5195                 aminfo[i].amhandler = pg_strdup(PQgetvalue(res, i, i_amhandler));
5196                 aminfo[i].amtype = *(PQgetvalue(res, i, i_amtype));
5197
5198                 /* Decide whether we want to dump it */
5199                 selectDumpableAccessMethod(&(aminfo[i]), fout);
5200
5201                 /* Access methods do not currently have ACLs. */
5202                 aminfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5203         }
5204
5205         PQclear(res);
5206
5207         destroyPQExpBuffer(query);
5208
5209         return aminfo;
5210 }
5211
5212
5213 /*
5214  * getOpclasses:
5215  *        read all opclasses in the system catalogs and return them in the
5216  * OpclassInfo* structure
5217  *
5218  *      numOpclasses is set to the number of opclasses read in
5219  */
5220 OpclassInfo *
5221 getOpclasses(Archive *fout, int *numOpclasses)
5222 {
5223         PGresult   *res;
5224         int                     ntups;
5225         int                     i;
5226         PQExpBuffer query = createPQExpBuffer();
5227         OpclassInfo *opcinfo;
5228         int                     i_tableoid;
5229         int                     i_oid;
5230         int                     i_opcname;
5231         int                     i_opcnamespace;
5232         int                     i_rolname;
5233
5234         /*
5235          * find all opclasses, including builtin opclasses; we filter out
5236          * system-defined opclasses at dump-out time.
5237          */
5238
5239         appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
5240                                           "opcnamespace, "
5241                                           "(%s opcowner) AS rolname "
5242                                           "FROM pg_opclass",
5243                                           username_subquery);
5244
5245         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5246
5247         ntups = PQntuples(res);
5248         *numOpclasses = ntups;
5249
5250         opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
5251
5252         i_tableoid = PQfnumber(res, "tableoid");
5253         i_oid = PQfnumber(res, "oid");
5254         i_opcname = PQfnumber(res, "opcname");
5255         i_opcnamespace = PQfnumber(res, "opcnamespace");
5256         i_rolname = PQfnumber(res, "rolname");
5257
5258         for (i = 0; i < ntups; i++)
5259         {
5260                 opcinfo[i].dobj.objType = DO_OPCLASS;
5261                 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5262                 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5263                 AssignDumpId(&opcinfo[i].dobj);
5264                 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
5265                 opcinfo[i].dobj.namespace =
5266                         findNamespace(fout,
5267                                                   atooid(PQgetvalue(res, i, i_opcnamespace)));
5268                 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5269
5270                 /* Decide whether we want to dump it */
5271                 selectDumpableObject(&(opcinfo[i].dobj), fout);
5272
5273                 /* Op Classes do not currently have ACLs. */
5274                 opcinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5275
5276                 if (strlen(opcinfo[i].rolname) == 0)
5277                         write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
5278                                           opcinfo[i].dobj.name);
5279         }
5280
5281         PQclear(res);
5282
5283         destroyPQExpBuffer(query);
5284
5285         return opcinfo;
5286 }
5287
5288 /*
5289  * getOpfamilies:
5290  *        read all opfamilies in the system catalogs and return them in the
5291  * OpfamilyInfo* structure
5292  *
5293  *      numOpfamilies is set to the number of opfamilies read in
5294  */
5295 OpfamilyInfo *
5296 getOpfamilies(Archive *fout, int *numOpfamilies)
5297 {
5298         PGresult   *res;
5299         int                     ntups;
5300         int                     i;
5301         PQExpBuffer query;
5302         OpfamilyInfo *opfinfo;
5303         int                     i_tableoid;
5304         int                     i_oid;
5305         int                     i_opfname;
5306         int                     i_opfnamespace;
5307         int                     i_rolname;
5308
5309         /* Before 8.3, there is no separate concept of opfamilies */
5310         if (fout->remoteVersion < 80300)
5311         {
5312                 *numOpfamilies = 0;
5313                 return NULL;
5314         }
5315
5316         query = createPQExpBuffer();
5317
5318         /*
5319          * find all opfamilies, including builtin opfamilies; we filter out
5320          * system-defined opfamilies at dump-out time.
5321          */
5322
5323         appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
5324                                           "opfnamespace, "
5325                                           "(%s opfowner) AS rolname "
5326                                           "FROM pg_opfamily",
5327                                           username_subquery);
5328
5329         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5330
5331         ntups = PQntuples(res);
5332         *numOpfamilies = ntups;
5333
5334         opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
5335
5336         i_tableoid = PQfnumber(res, "tableoid");
5337         i_oid = PQfnumber(res, "oid");
5338         i_opfname = PQfnumber(res, "opfname");
5339         i_opfnamespace = PQfnumber(res, "opfnamespace");
5340         i_rolname = PQfnumber(res, "rolname");
5341
5342         for (i = 0; i < ntups; i++)
5343         {
5344                 opfinfo[i].dobj.objType = DO_OPFAMILY;
5345                 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5346                 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5347                 AssignDumpId(&opfinfo[i].dobj);
5348                 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
5349                 opfinfo[i].dobj.namespace =
5350                         findNamespace(fout,
5351                                                   atooid(PQgetvalue(res, i, i_opfnamespace)));
5352                 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5353
5354                 /* Decide whether we want to dump it */
5355                 selectDumpableObject(&(opfinfo[i].dobj), fout);
5356
5357                 /* Extensions do not currently have ACLs. */
5358                 opfinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5359
5360                 if (strlen(opfinfo[i].rolname) == 0)
5361                         write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
5362                                           opfinfo[i].dobj.name);
5363         }
5364
5365         PQclear(res);
5366
5367         destroyPQExpBuffer(query);
5368
5369         return opfinfo;
5370 }
5371
5372 /*
5373  * getAggregates:
5374  *        read all the user-defined aggregates in the system catalogs and
5375  * return them in the AggInfo* structure
5376  *
5377  * numAggs is set to the number of aggregates read in
5378  */
5379 AggInfo *
5380 getAggregates(Archive *fout, int *numAggs)
5381 {
5382         DumpOptions *dopt = fout->dopt;
5383         PGresult   *res;
5384         int                     ntups;
5385         int                     i;
5386         PQExpBuffer query = createPQExpBuffer();
5387         AggInfo    *agginfo;
5388         int                     i_tableoid;
5389         int                     i_oid;
5390         int                     i_aggname;
5391         int                     i_aggnamespace;
5392         int                     i_pronargs;
5393         int                     i_proargtypes;
5394         int                     i_rolname;
5395         int                     i_aggacl;
5396         int                     i_raggacl;
5397         int                     i_initaggacl;
5398         int                     i_initraggacl;
5399
5400         /*
5401          * Find all interesting aggregates.  See comment in getFuncs() for the
5402          * rationale behind the filtering logic.
5403          */
5404         if (fout->remoteVersion >= 90600)
5405         {
5406                 PQExpBuffer acl_subquery = createPQExpBuffer();
5407                 PQExpBuffer racl_subquery = createPQExpBuffer();
5408                 PQExpBuffer initacl_subquery = createPQExpBuffer();
5409                 PQExpBuffer initracl_subquery = createPQExpBuffer();
5410                 const char *agg_check;
5411
5412                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5413                                                 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5414                                                 dopt->binary_upgrade);
5415
5416                 agg_check = (fout->remoteVersion >= 110000 ? "p.prokind = 'a'"
5417                                          : "p.proisagg");
5418
5419                 appendPQExpBuffer(query, "SELECT p.tableoid, p.oid, "
5420                                                   "p.proname AS aggname, "
5421                                                   "p.pronamespace AS aggnamespace, "
5422                                                   "p.pronargs, p.proargtypes, "
5423                                                   "(%s p.proowner) AS rolname, "
5424                                                   "%s AS aggacl, "
5425                                                   "%s AS raggacl, "
5426                                                   "%s AS initaggacl, "
5427                                                   "%s AS initraggacl "
5428                                                   "FROM pg_proc p "
5429                                                   "LEFT JOIN pg_init_privs pip ON "
5430                                                   "(p.oid = pip.objoid "
5431                                                   "AND pip.classoid = 'pg_proc'::regclass "
5432                                                   "AND pip.objsubid = 0) "
5433                                                   "WHERE %s AND ("
5434                                                   "p.pronamespace != "
5435                                                   "(SELECT oid FROM pg_namespace "
5436                                                   "WHERE nspname = 'pg_catalog') OR "
5437                                                   "p.proacl IS DISTINCT FROM pip.initprivs",
5438                                                   username_subquery,
5439                                                   acl_subquery->data,
5440                                                   racl_subquery->data,
5441                                                   initacl_subquery->data,
5442                                                   initracl_subquery->data,
5443                                                   agg_check);
5444                 if (dopt->binary_upgrade)
5445                         appendPQExpBufferStr(query,
5446                                                                  " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5447                                                                  "classid = 'pg_proc'::regclass AND "
5448                                                                  "objid = p.oid AND "
5449                                                                  "refclassid = 'pg_extension'::regclass AND "
5450                                                                  "deptype = 'e')");
5451                 appendPQExpBufferChar(query, ')');
5452
5453                 destroyPQExpBuffer(acl_subquery);
5454                 destroyPQExpBuffer(racl_subquery);
5455                 destroyPQExpBuffer(initacl_subquery);
5456                 destroyPQExpBuffer(initracl_subquery);
5457         }
5458         else if (fout->remoteVersion >= 80200)
5459         {
5460                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5461                                                   "pronamespace AS aggnamespace, "
5462                                                   "pronargs, proargtypes, "
5463                                                   "(%s proowner) AS rolname, "
5464                                                   "proacl AS aggacl, "
5465                                                   "NULL AS raggacl, "
5466                                                   "NULL AS initaggacl, NULL AS initraggacl "
5467                                                   "FROM pg_proc p "
5468                                                   "WHERE proisagg AND ("
5469                                                   "pronamespace != "
5470                                                   "(SELECT oid FROM pg_namespace "
5471                                                   "WHERE nspname = 'pg_catalog')",
5472                                                   username_subquery);
5473                 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5474                         appendPQExpBufferStr(query,
5475                                                                  " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5476                                                                  "classid = 'pg_proc'::regclass AND "
5477                                                                  "objid = p.oid AND "
5478                                                                  "refclassid = 'pg_extension'::regclass AND "
5479                                                                  "deptype = 'e')");
5480                 appendPQExpBufferChar(query, ')');
5481         }
5482         else
5483         {
5484                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5485                                                   "pronamespace AS aggnamespace, "
5486                                                   "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
5487                                                   "proargtypes, "
5488                                                   "(%s proowner) AS rolname, "
5489                                                   "proacl AS aggacl, "
5490                                                   "NULL AS raggacl, "
5491                                                   "NULL AS initaggacl, NULL AS initraggacl "
5492                                                   "FROM pg_proc "
5493                                                   "WHERE proisagg "
5494                                                   "AND pronamespace != "
5495                                                   "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
5496                                                   username_subquery);
5497         }
5498
5499         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5500
5501         ntups = PQntuples(res);
5502         *numAggs = ntups;
5503
5504         agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
5505
5506         i_tableoid = PQfnumber(res, "tableoid");
5507         i_oid = PQfnumber(res, "oid");
5508         i_aggname = PQfnumber(res, "aggname");
5509         i_aggnamespace = PQfnumber(res, "aggnamespace");
5510         i_pronargs = PQfnumber(res, "pronargs");
5511         i_proargtypes = PQfnumber(res, "proargtypes");
5512         i_rolname = PQfnumber(res, "rolname");
5513         i_aggacl = PQfnumber(res, "aggacl");
5514         i_raggacl = PQfnumber(res, "raggacl");
5515         i_initaggacl = PQfnumber(res, "initaggacl");
5516         i_initraggacl = PQfnumber(res, "initraggacl");
5517
5518         for (i = 0; i < ntups; i++)
5519         {
5520                 agginfo[i].aggfn.dobj.objType = DO_AGG;
5521                 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5522                 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5523                 AssignDumpId(&agginfo[i].aggfn.dobj);
5524                 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
5525                 agginfo[i].aggfn.dobj.namespace =
5526                         findNamespace(fout,
5527                                                   atooid(PQgetvalue(res, i, i_aggnamespace)));
5528                 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5529                 if (strlen(agginfo[i].aggfn.rolname) == 0)
5530                         write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
5531                                           agginfo[i].aggfn.dobj.name);
5532                 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
5533                 agginfo[i].aggfn.prorettype = InvalidOid;       /* not saved */
5534                 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
5535                 agginfo[i].aggfn.rproacl = pg_strdup(PQgetvalue(res, i, i_raggacl));
5536                 agginfo[i].aggfn.initproacl = pg_strdup(PQgetvalue(res, i, i_initaggacl));
5537                 agginfo[i].aggfn.initrproacl = pg_strdup(PQgetvalue(res, i, i_initraggacl));
5538                 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
5539                 if (agginfo[i].aggfn.nargs == 0)
5540                         agginfo[i].aggfn.argtypes = NULL;
5541                 else
5542                 {
5543                         agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
5544                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
5545                                                   agginfo[i].aggfn.argtypes,
5546                                                   agginfo[i].aggfn.nargs);
5547                 }
5548
5549                 /* Decide whether we want to dump it */
5550                 selectDumpableObject(&(agginfo[i].aggfn.dobj), fout);
5551
5552                 /* Do not try to dump ACL if no ACL exists. */
5553                 if (PQgetisnull(res, i, i_aggacl) && PQgetisnull(res, i, i_raggacl) &&
5554                         PQgetisnull(res, i, i_initaggacl) &&
5555                         PQgetisnull(res, i, i_initraggacl))
5556                         agginfo[i].aggfn.dobj.dump &= ~DUMP_COMPONENT_ACL;
5557         }
5558
5559         PQclear(res);
5560
5561         destroyPQExpBuffer(query);
5562
5563         return agginfo;
5564 }
5565
5566 /*
5567  * getFuncs:
5568  *        read all the user-defined functions in the system catalogs and
5569  * return them in the FuncInfo* structure
5570  *
5571  * numFuncs is set to the number of functions read in
5572  */
5573 FuncInfo *
5574 getFuncs(Archive *fout, int *numFuncs)
5575 {
5576         DumpOptions *dopt = fout->dopt;
5577         PGresult   *res;
5578         int                     ntups;
5579         int                     i;
5580         PQExpBuffer query = createPQExpBuffer();
5581         FuncInfo   *finfo;
5582         int                     i_tableoid;
5583         int                     i_oid;
5584         int                     i_proname;
5585         int                     i_pronamespace;
5586         int                     i_rolname;
5587         int                     i_prolang;
5588         int                     i_pronargs;
5589         int                     i_proargtypes;
5590         int                     i_prorettype;
5591         int                     i_proacl;
5592         int                     i_rproacl;
5593         int                     i_initproacl;
5594         int                     i_initrproacl;
5595
5596         /*
5597          * Find all interesting functions.  This is a bit complicated:
5598          *
5599          * 1. Always exclude aggregates; those are handled elsewhere.
5600          *
5601          * 2. Always exclude functions that are internally dependent on something
5602          * else, since presumably those will be created as a result of creating
5603          * the something else.  This currently acts only to suppress constructor
5604          * functions for range types (so we only need it in 9.2 and up).  Note
5605          * this is OK only because the constructors don't have any dependencies
5606          * the range type doesn't have; otherwise we might not get creation
5607          * ordering correct.
5608          *
5609          * 3. Otherwise, we normally exclude functions in pg_catalog.  However, if
5610          * they're members of extensions and we are in binary-upgrade mode then
5611          * include them, since we want to dump extension members individually in
5612          * that mode.  Also, if they are used by casts or transforms then we need
5613          * to gather the information about them, though they won't be dumped if
5614          * they are built-in.  Also, in 9.6 and up, include functions in
5615          * pg_catalog if they have an ACL different from what's shown in
5616          * pg_init_privs.
5617          */
5618         if (fout->remoteVersion >= 90600)
5619         {
5620                 PQExpBuffer acl_subquery = createPQExpBuffer();
5621                 PQExpBuffer racl_subquery = createPQExpBuffer();
5622                 PQExpBuffer initacl_subquery = createPQExpBuffer();
5623                 PQExpBuffer initracl_subquery = createPQExpBuffer();
5624                 const char *not_agg_check;
5625
5626                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5627                                                 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5628                                                 dopt->binary_upgrade);
5629
5630                 not_agg_check = (fout->remoteVersion >= 110000 ? "p.prokind <> 'a'"
5631                                                  : "NOT p.proisagg");
5632
5633                 appendPQExpBuffer(query,
5634                                                   "SELECT p.tableoid, p.oid, p.proname, p.prolang, "
5635                                                   "p.pronargs, p.proargtypes, p.prorettype, "
5636                                                   "%s AS proacl, "
5637                                                   "%s AS rproacl, "
5638                                                   "%s AS initproacl, "
5639                                                   "%s AS initrproacl, "
5640                                                   "p.pronamespace, "
5641                                                   "(%s p.proowner) AS rolname "
5642                                                   "FROM pg_proc p "
5643                                                   "LEFT JOIN pg_init_privs pip ON "
5644                                                   "(p.oid = pip.objoid "
5645                                                   "AND pip.classoid = 'pg_proc'::regclass "
5646                                                   "AND pip.objsubid = 0) "
5647                                                   "WHERE %s"
5648                                                   "\n  AND NOT EXISTS (SELECT 1 FROM pg_depend "
5649                                                   "WHERE classid = 'pg_proc'::regclass AND "
5650                                                   "objid = p.oid AND deptype = 'i')"
5651                                                   "\n  AND ("
5652                                                   "\n  pronamespace != "
5653                                                   "(SELECT oid FROM pg_namespace "
5654                                                   "WHERE nspname = 'pg_catalog')"
5655                                                   "\n  OR EXISTS (SELECT 1 FROM pg_cast"
5656                                                   "\n  WHERE pg_cast.oid > %u "
5657                                                   "\n  AND p.oid = pg_cast.castfunc)"
5658                                                   "\n  OR EXISTS (SELECT 1 FROM pg_transform"
5659                                                   "\n  WHERE pg_transform.oid > %u AND "
5660                                                   "\n  (p.oid = pg_transform.trffromsql"
5661                                                   "\n  OR p.oid = pg_transform.trftosql))",
5662                                                   acl_subquery->data,
5663                                                   racl_subquery->data,
5664                                                   initacl_subquery->data,
5665                                                   initracl_subquery->data,
5666                                                   username_subquery,
5667                                                   not_agg_check,
5668                                                   g_last_builtin_oid,
5669                                                   g_last_builtin_oid);
5670                 if (dopt->binary_upgrade)
5671                         appendPQExpBufferStr(query,
5672                                                                  "\n  OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5673                                                                  "classid = 'pg_proc'::regclass AND "
5674                                                                  "objid = p.oid AND "
5675                                                                  "refclassid = 'pg_extension'::regclass AND "
5676                                                                  "deptype = 'e')");
5677                 appendPQExpBufferStr(query,
5678                                                          "\n  OR p.proacl IS DISTINCT FROM pip.initprivs");
5679                 appendPQExpBufferChar(query, ')');
5680
5681                 destroyPQExpBuffer(acl_subquery);
5682                 destroyPQExpBuffer(racl_subquery);
5683                 destroyPQExpBuffer(initacl_subquery);
5684                 destroyPQExpBuffer(initracl_subquery);
5685         }
5686         else
5687         {
5688                 appendPQExpBuffer(query,
5689                                                   "SELECT tableoid, oid, proname, prolang, "
5690                                                   "pronargs, proargtypes, prorettype, proacl, "
5691                                                   "NULL as rproacl, "
5692                                                   "NULL as initproacl, NULL AS initrproacl, "
5693                                                   "pronamespace, "
5694                                                   "(%s proowner) AS rolname "
5695                                                   "FROM pg_proc p "
5696                                                   "WHERE NOT proisagg",
5697                                                   username_subquery);
5698                 if (fout->remoteVersion >= 90200)
5699                         appendPQExpBufferStr(query,
5700                                                                  "\n  AND NOT EXISTS (SELECT 1 FROM pg_depend "
5701                                                                  "WHERE classid = 'pg_proc'::regclass AND "
5702                                                                  "objid = p.oid AND deptype = 'i')");
5703                 appendPQExpBuffer(query,
5704                                                   "\n  AND ("
5705                                                   "\n  pronamespace != "
5706                                                   "(SELECT oid FROM pg_namespace "
5707                                                   "WHERE nspname = 'pg_catalog')"
5708                                                   "\n  OR EXISTS (SELECT 1 FROM pg_cast"
5709                                                   "\n  WHERE pg_cast.oid > '%u'::oid"
5710                                                   "\n  AND p.oid = pg_cast.castfunc)",
5711                                                   g_last_builtin_oid);
5712
5713                 if (fout->remoteVersion >= 90500)
5714                         appendPQExpBuffer(query,
5715                                                           "\n  OR EXISTS (SELECT 1 FROM pg_transform"
5716                                                           "\n  WHERE pg_transform.oid > '%u'::oid"
5717                                                           "\n  AND (p.oid = pg_transform.trffromsql"
5718                                                           "\n  OR p.oid = pg_transform.trftosql))",
5719                                                           g_last_builtin_oid);
5720
5721                 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5722                         appendPQExpBufferStr(query,
5723                                                                  "\n  OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5724                                                                  "classid = 'pg_proc'::regclass AND "
5725                                                                  "objid = p.oid AND "
5726                                                                  "refclassid = 'pg_extension'::regclass AND "
5727                                                                  "deptype = 'e')");
5728                 appendPQExpBufferChar(query, ')');
5729         }
5730
5731         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5732
5733         ntups = PQntuples(res);
5734
5735         *numFuncs = ntups;
5736
5737         finfo = (FuncInfo *) pg_malloc0(ntups * sizeof(FuncInfo));
5738
5739         i_tableoid = PQfnumber(res, "tableoid");
5740         i_oid = PQfnumber(res, "oid");
5741         i_proname = PQfnumber(res, "proname");
5742         i_pronamespace = PQfnumber(res, "pronamespace");
5743         i_rolname = PQfnumber(res, "rolname");
5744         i_prolang = PQfnumber(res, "prolang");
5745         i_pronargs = PQfnumber(res, "pronargs");
5746         i_proargtypes = PQfnumber(res, "proargtypes");
5747         i_prorettype = PQfnumber(res, "prorettype");
5748         i_proacl = PQfnumber(res, "proacl");
5749         i_rproacl = PQfnumber(res, "rproacl");
5750         i_initproacl = PQfnumber(res, "initproacl");
5751         i_initrproacl = PQfnumber(res, "initrproacl");
5752
5753         for (i = 0; i < ntups; i++)
5754         {
5755                 finfo[i].dobj.objType = DO_FUNC;
5756                 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5757                 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5758                 AssignDumpId(&finfo[i].dobj);
5759                 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
5760                 finfo[i].dobj.namespace =
5761                         findNamespace(fout,
5762                                                   atooid(PQgetvalue(res, i, i_pronamespace)));
5763                 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5764                 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
5765                 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
5766                 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
5767                 finfo[i].rproacl = pg_strdup(PQgetvalue(res, i, i_rproacl));
5768                 finfo[i].initproacl = pg_strdup(PQgetvalue(res, i, i_initproacl));
5769                 finfo[i].initrproacl = pg_strdup(PQgetvalue(res, i, i_initrproacl));
5770                 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
5771                 if (finfo[i].nargs == 0)
5772                         finfo[i].argtypes = NULL;
5773                 else
5774                 {
5775                         finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
5776                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
5777                                                   finfo[i].argtypes, finfo[i].nargs);
5778                 }
5779
5780                 /* Decide whether we want to dump it */
5781                 selectDumpableObject(&(finfo[i].dobj), fout);
5782
5783                 /* Do not try to dump ACL if no ACL exists. */
5784                 if (PQgetisnull(res, i, i_proacl) && PQgetisnull(res, i, i_rproacl) &&
5785                         PQgetisnull(res, i, i_initproacl) &&
5786                         PQgetisnull(res, i, i_initrproacl))
5787                         finfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5788
5789                 if (strlen(finfo[i].rolname) == 0)
5790                         write_msg(NULL,
5791                                           "WARNING: owner of function \"%s\" appears to be invalid\n",
5792                                           finfo[i].dobj.name);
5793         }
5794
5795         PQclear(res);
5796
5797         destroyPQExpBuffer(query);
5798
5799         return finfo;
5800 }
5801
5802 /*
5803  * getTables
5804  *        read all the tables (no indexes)
5805  * in the system catalogs return them in the TableInfo* structure
5806  *
5807  * numTables is set to the number of tables read in
5808  */
5809 TableInfo *
5810 getTables(Archive *fout, int *numTables)
5811 {
5812         DumpOptions *dopt = fout->dopt;
5813         PGresult   *res;
5814         int                     ntups;
5815         int                     i;
5816         PQExpBuffer query = createPQExpBuffer();
5817         TableInfo  *tblinfo;
5818         int                     i_reltableoid;
5819         int                     i_reloid;
5820         int                     i_relname;
5821         int                     i_relnamespace;
5822         int                     i_relkind;
5823         int                     i_relacl;
5824         int                     i_rrelacl;
5825         int                     i_initrelacl;
5826         int                     i_initrrelacl;
5827         int                     i_rolname;
5828         int                     i_relchecks;
5829         int                     i_relhastriggers;
5830         int                     i_relhasindex;
5831         int                     i_relhasrules;
5832         int                     i_relrowsec;
5833         int                     i_relforcerowsec;
5834         int                     i_relhasoids;
5835         int                     i_relfrozenxid;
5836         int                     i_relminmxid;
5837         int                     i_toastoid;
5838         int                     i_toastfrozenxid;
5839         int                     i_toastminmxid;
5840         int                     i_relpersistence;
5841         int                     i_relispopulated;
5842         int                     i_relreplident;
5843         int                     i_owning_tab;
5844         int                     i_owning_col;
5845         int                     i_reltablespace;
5846         int                     i_reloptions;
5847         int                     i_checkoption;
5848         int                     i_toastreloptions;
5849         int                     i_reloftype;
5850         int                     i_relpages;
5851         int                     i_is_identity_sequence;
5852         int                     i_changed_acl;
5853         int                     i_partkeydef;
5854         int                     i_ispartition;
5855         int                     i_partbound;
5856
5857         /*
5858          * Find all the tables and table-like objects.
5859          *
5860          * We include system catalogs, so that we can work if a user table is
5861          * defined to inherit from a system catalog (pretty weird, but...)
5862          *
5863          * We ignore relations that are not ordinary tables, sequences, views,
5864          * materialized views, composite types, or foreign tables.
5865          *
5866          * Composite-type table entries won't be dumped as such, but we have to
5867          * make a DumpableObject for them so that we can track dependencies of the
5868          * composite type (pg_depend entries for columns of the composite type
5869          * link to the pg_class entry not the pg_type entry).
5870          *
5871          * Note: in this phase we should collect only a minimal amount of
5872          * information about each table, basically just enough to decide if it is
5873          * interesting. We must fetch all tables in this phase because otherwise
5874          * we cannot correctly identify inherited columns, owned sequences, etc.
5875          */
5876
5877         if (fout->remoteVersion >= 90600)
5878         {
5879                 char       *partkeydef = "NULL";
5880                 char       *ispartition = "false";
5881                 char       *partbound = "NULL";
5882
5883                 PQExpBuffer acl_subquery = createPQExpBuffer();
5884                 PQExpBuffer racl_subquery = createPQExpBuffer();
5885                 PQExpBuffer initacl_subquery = createPQExpBuffer();
5886                 PQExpBuffer initracl_subquery = createPQExpBuffer();
5887
5888                 PQExpBuffer attacl_subquery = createPQExpBuffer();
5889                 PQExpBuffer attracl_subquery = createPQExpBuffer();
5890                 PQExpBuffer attinitacl_subquery = createPQExpBuffer();
5891                 PQExpBuffer attinitracl_subquery = createPQExpBuffer();
5892
5893                 /*
5894                  * Collect the information about any partitioned tables, which were
5895                  * added in PG10.
5896                  */
5897
5898                 if (fout->remoteVersion >= 100000)
5899                 {
5900                         partkeydef = "pg_get_partkeydef(c.oid)";
5901                         ispartition = "c.relispartition";
5902                         partbound = "pg_get_expr(c.relpartbound, c.oid)";
5903                 }
5904
5905                 /*
5906                  * Left join to pick up dependency info linking sequences to their
5907                  * owning column, if any (note this dependency is AUTO as of 8.2)
5908                  *
5909                  * Left join to detect if any privileges are still as-set-at-init, in
5910                  * which case we won't dump out ACL commands for those.
5911                  */
5912
5913                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5914                                                 initracl_subquery, "c.relacl", "c.relowner",
5915                                                 "CASE WHEN c.relkind = " CppAsString2(RELKIND_SEQUENCE)
5916                                                 " THEN 's' ELSE 'r' END::\"char\"",
5917                                                 dopt->binary_upgrade);
5918
5919                 buildACLQueries(attacl_subquery, attracl_subquery, attinitacl_subquery,
5920                                                 attinitracl_subquery, "at.attacl", "c.relowner", "'c'",
5921                                                 dopt->binary_upgrade);
5922
5923                 appendPQExpBuffer(query,
5924                                                   "SELECT c.tableoid, c.oid, c.relname, "
5925                                                   "%s AS relacl, %s as rrelacl, "
5926                                                   "%s AS initrelacl, %s as initrrelacl, "
5927                                                   "c.relkind, c.relnamespace, "
5928                                                   "(%s c.relowner) AS rolname, "
5929                                                   "c.relchecks, c.relhastriggers, "
5930                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
5931                                                   "c.relrowsecurity, c.relforcerowsecurity, "
5932                                                   "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
5933                                                   "tc.relfrozenxid AS tfrozenxid, "
5934                                                   "tc.relminmxid AS tminmxid, "
5935                                                   "c.relpersistence, c.relispopulated, "
5936                                                   "c.relreplident, c.relpages, "
5937                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
5938                                                   "d.refobjid AS owning_tab, "
5939                                                   "d.refobjsubid AS owning_col, "
5940                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5941                                                   "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
5942                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
5943                                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
5944                                                   "tc.reloptions AS toast_reloptions, "
5945                                                   "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, "
5946                                                   "EXISTS (SELECT 1 FROM pg_attribute at LEFT JOIN pg_init_privs pip ON "
5947                                                   "(c.oid = pip.objoid "
5948                                                   "AND pip.classoid = 'pg_class'::regclass "
5949                                                   "AND pip.objsubid = at.attnum)"
5950                                                   "WHERE at.attrelid = c.oid AND ("
5951                                                   "%s IS NOT NULL "
5952                                                   "OR %s IS NOT NULL "
5953                                                   "OR %s IS NOT NULL "
5954                                                   "OR %s IS NOT NULL"
5955                                                   "))"
5956                                                   "AS changed_acl, "
5957                                                   "%s AS partkeydef, "
5958                                                   "%s AS ispartition, "
5959                                                   "%s AS partbound "
5960                                                   "FROM pg_class c "
5961                                                   "LEFT JOIN pg_depend d ON "
5962                                                   "(c.relkind = '%c' AND "
5963                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
5964                                                   "d.objsubid = 0 AND "
5965                                                   "d.refclassid = c.tableoid AND d.deptype IN ('a', 'i')) "
5966                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5967                                                   "LEFT JOIN pg_init_privs pip ON "
5968                                                   "(c.oid = pip.objoid "
5969                                                   "AND pip.classoid = 'pg_class'::regclass "
5970                                                   "AND pip.objsubid = 0) "
5971                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c', '%c') "
5972                                                   "ORDER BY c.oid",
5973                                                   acl_subquery->data,
5974                                                   racl_subquery->data,
5975                                                   initacl_subquery->data,
5976                                                   initracl_subquery->data,
5977                                                   username_subquery,
5978                                                   RELKIND_SEQUENCE,
5979                                                   attacl_subquery->data,
5980                                                   attracl_subquery->data,
5981                                                   attinitacl_subquery->data,
5982                                                   attinitracl_subquery->data,
5983                                                   partkeydef,
5984                                                   ispartition,
5985                                                   partbound,
5986                                                   RELKIND_SEQUENCE,
5987                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
5988                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
5989                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
5990                                                   RELKIND_PARTITIONED_TABLE);
5991
5992                 destroyPQExpBuffer(acl_subquery);
5993                 destroyPQExpBuffer(racl_subquery);
5994                 destroyPQExpBuffer(initacl_subquery);
5995                 destroyPQExpBuffer(initracl_subquery);
5996
5997                 destroyPQExpBuffer(attacl_subquery);
5998                 destroyPQExpBuffer(attracl_subquery);
5999                 destroyPQExpBuffer(attinitacl_subquery);
6000                 destroyPQExpBuffer(attinitracl_subquery);
6001         }
6002         else if (fout->remoteVersion >= 90500)
6003         {
6004                 /*
6005                  * Left join to pick up dependency info linking sequences to their
6006                  * owning column, if any (note this dependency is AUTO as of 8.2)
6007                  */
6008                 appendPQExpBuffer(query,
6009                                                   "SELECT c.tableoid, c.oid, c.relname, "
6010                                                   "c.relacl, NULL as rrelacl, "
6011                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6012                                                   "c.relkind, "
6013                                                   "c.relnamespace, "
6014                                                   "(%s c.relowner) AS rolname, "
6015                                                   "c.relchecks, c.relhastriggers, "
6016                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6017                                                   "c.relrowsecurity, c.relforcerowsecurity, "
6018                                                   "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6019                                                   "tc.relfrozenxid AS tfrozenxid, "
6020                                                   "tc.relminmxid AS tminmxid, "
6021                                                   "c.relpersistence, c.relispopulated, "
6022                                                   "c.relreplident, c.relpages, "
6023                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6024                                                   "d.refobjid AS owning_tab, "
6025                                                   "d.refobjsubid AS owning_col, "
6026                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6027                                                   "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6028                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6029                                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6030                                                   "tc.reloptions AS toast_reloptions, "
6031                                                   "NULL AS changed_acl, "
6032                                                   "NULL AS partkeydef, "
6033                                                   "false AS ispartition, "
6034                                                   "NULL AS partbound "
6035                                                   "FROM pg_class c "
6036                                                   "LEFT JOIN pg_depend d ON "
6037                                                   "(c.relkind = '%c' AND "
6038                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6039                                                   "d.objsubid = 0 AND "
6040                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6041                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6042                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6043                                                   "ORDER BY c.oid",
6044                                                   username_subquery,
6045                                                   RELKIND_SEQUENCE,
6046                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6047                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6048                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6049         }
6050         else if (fout->remoteVersion >= 90400)
6051         {
6052                 /*
6053                  * Left join to pick up dependency info linking sequences to their
6054                  * owning column, if any (note this dependency is AUTO as of 8.2)
6055                  */
6056                 appendPQExpBuffer(query,
6057                                                   "SELECT c.tableoid, c.oid, c.relname, "
6058                                                   "c.relacl, NULL as rrelacl, "
6059                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6060                                                   "c.relkind, "
6061                                                   "c.relnamespace, "
6062                                                   "(%s c.relowner) AS rolname, "
6063                                                   "c.relchecks, c.relhastriggers, "
6064                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6065                                                   "'f'::bool AS relrowsecurity, "
6066                                                   "'f'::bool AS relforcerowsecurity, "
6067                                                   "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6068                                                   "tc.relfrozenxid AS tfrozenxid, "
6069                                                   "tc.relminmxid AS tminmxid, "
6070                                                   "c.relpersistence, c.relispopulated, "
6071                                                   "c.relreplident, c.relpages, "
6072                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6073                                                   "d.refobjid AS owning_tab, "
6074                                                   "d.refobjsubid AS owning_col, "
6075                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6076                                                   "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6077                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6078                                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6079                                                   "tc.reloptions AS toast_reloptions, "
6080                                                   "NULL AS changed_acl, "
6081                                                   "NULL AS partkeydef, "
6082                                                   "false AS ispartition, "
6083                                                   "NULL AS partbound "
6084                                                   "FROM pg_class c "
6085                                                   "LEFT JOIN pg_depend d ON "
6086                                                   "(c.relkind = '%c' AND "
6087                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6088                                                   "d.objsubid = 0 AND "
6089                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6090                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6091                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6092                                                   "ORDER BY c.oid",
6093                                                   username_subquery,
6094                                                   RELKIND_SEQUENCE,
6095                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6096                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6097                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6098         }
6099         else if (fout->remoteVersion >= 90300)
6100         {
6101                 /*
6102                  * Left join to pick up dependency info linking sequences to their
6103                  * owning column, if any (note this dependency is AUTO as of 8.2)
6104                  */
6105                 appendPQExpBuffer(query,
6106                                                   "SELECT c.tableoid, c.oid, c.relname, "
6107                                                   "c.relacl, NULL as rrelacl, "
6108                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6109                                                   "c.relkind, "
6110                                                   "c.relnamespace, "
6111                                                   "(%s c.relowner) AS rolname, "
6112                                                   "c.relchecks, c.relhastriggers, "
6113                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6114                                                   "'f'::bool AS relrowsecurity, "
6115                                                   "'f'::bool AS relforcerowsecurity, "
6116                                                   "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6117                                                   "tc.relfrozenxid AS tfrozenxid, "
6118                                                   "tc.relminmxid AS tminmxid, "
6119                                                   "c.relpersistence, c.relispopulated, "
6120                                                   "'d' AS relreplident, c.relpages, "
6121                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6122                                                   "d.refobjid AS owning_tab, "
6123                                                   "d.refobjsubid AS owning_col, "
6124                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6125                                                   "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6126                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6127                                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6128                                                   "tc.reloptions AS toast_reloptions, "
6129                                                   "NULL AS changed_acl, "
6130                                                   "NULL AS partkeydef, "
6131                                                   "false AS ispartition, "
6132                                                   "NULL AS partbound "
6133                                                   "FROM pg_class c "
6134                                                   "LEFT JOIN pg_depend d ON "
6135                                                   "(c.relkind = '%c' AND "
6136                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6137                                                   "d.objsubid = 0 AND "
6138                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6139                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6140                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6141                                                   "ORDER BY c.oid",
6142                                                   username_subquery,
6143                                                   RELKIND_SEQUENCE,
6144                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6145                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6146                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6147         }
6148         else if (fout->remoteVersion >= 90100)
6149         {
6150                 /*
6151                  * Left join to pick up dependency info linking sequences to their
6152                  * owning column, if any (note this dependency is AUTO as of 8.2)
6153                  */
6154                 appendPQExpBuffer(query,
6155                                                   "SELECT c.tableoid, c.oid, c.relname, "
6156                                                   "c.relacl, NULL as rrelacl, "
6157                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6158                                                   "c.relkind, "
6159                                                   "c.relnamespace, "
6160                                                   "(%s c.relowner) AS rolname, "
6161                                                   "c.relchecks, c.relhastriggers, "
6162                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6163                                                   "'f'::bool AS relrowsecurity, "
6164                                                   "'f'::bool AS relforcerowsecurity, "
6165                                                   "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6166                                                   "tc.relfrozenxid AS tfrozenxid, "
6167                                                   "0 AS tminmxid, "
6168                                                   "c.relpersistence, 't' as relispopulated, "
6169                                                   "'d' AS relreplident, c.relpages, "
6170                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6171                                                   "d.refobjid AS owning_tab, "
6172                                                   "d.refobjsubid AS owning_col, "
6173                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6174                                                   "c.reloptions AS reloptions, "
6175                                                   "tc.reloptions AS toast_reloptions, "
6176                                                   "NULL AS changed_acl, "
6177                                                   "NULL AS partkeydef, "
6178                                                   "false AS ispartition, "
6179                                                   "NULL AS partbound "
6180                                                   "FROM pg_class c "
6181                                                   "LEFT JOIN pg_depend d ON "
6182                                                   "(c.relkind = '%c' AND "
6183                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6184                                                   "d.objsubid = 0 AND "
6185                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6186                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6187                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6188                                                   "ORDER BY c.oid",
6189                                                   username_subquery,
6190                                                   RELKIND_SEQUENCE,
6191                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6192                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6193                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6194         }
6195         else if (fout->remoteVersion >= 90000)
6196         {
6197                 /*
6198                  * Left join to pick up dependency info linking sequences to their
6199                  * owning column, if any (note this dependency is AUTO as of 8.2)
6200                  */
6201                 appendPQExpBuffer(query,
6202                                                   "SELECT c.tableoid, c.oid, c.relname, "
6203                                                   "c.relacl, NULL as rrelacl, "
6204                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6205                                                   "c.relkind, "
6206                                                   "c.relnamespace, "
6207                                                   "(%s c.relowner) AS rolname, "
6208                                                   "c.relchecks, c.relhastriggers, "
6209                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6210                                                   "'f'::bool AS relrowsecurity, "
6211                                                   "'f'::bool AS relforcerowsecurity, "
6212                                                   "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6213                                                   "tc.relfrozenxid AS tfrozenxid, "
6214                                                   "0 AS tminmxid, "
6215                                                   "'p' AS relpersistence, 't' as relispopulated, "
6216                                                   "'d' AS relreplident, c.relpages, "
6217                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6218                                                   "d.refobjid AS owning_tab, "
6219                                                   "d.refobjsubid AS owning_col, "
6220                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6221                                                   "c.reloptions AS reloptions, "
6222                                                   "tc.reloptions AS toast_reloptions, "
6223                                                   "NULL AS changed_acl, "
6224                                                   "NULL AS partkeydef, "
6225                                                   "false AS ispartition, "
6226                                                   "NULL AS partbound "
6227                                                   "FROM pg_class c "
6228                                                   "LEFT JOIN pg_depend d ON "
6229                                                   "(c.relkind = '%c' AND "
6230                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6231                                                   "d.objsubid = 0 AND "
6232                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6233                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6234                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6235                                                   "ORDER BY c.oid",
6236                                                   username_subquery,
6237                                                   RELKIND_SEQUENCE,
6238                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6239                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6240         }
6241         else if (fout->remoteVersion >= 80400)
6242         {
6243                 /*
6244                  * Left join to pick up dependency info linking sequences to their
6245                  * owning column, if any (note this dependency is AUTO as of 8.2)
6246                  */
6247                 appendPQExpBuffer(query,
6248                                                   "SELECT c.tableoid, c.oid, c.relname, "
6249                                                   "c.relacl, NULL as rrelacl, "
6250                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6251                                                   "c.relkind, "
6252                                                   "c.relnamespace, "
6253                                                   "(%s c.relowner) AS rolname, "
6254                                                   "c.relchecks, c.relhastriggers, "
6255                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6256                                                   "'f'::bool AS relrowsecurity, "
6257                                                   "'f'::bool AS relforcerowsecurity, "
6258                                                   "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6259                                                   "tc.relfrozenxid AS tfrozenxid, "
6260                                                   "0 AS tminmxid, "
6261                                                   "'p' AS relpersistence, 't' as relispopulated, "
6262                                                   "'d' AS relreplident, c.relpages, "
6263                                                   "NULL AS reloftype, "
6264                                                   "d.refobjid AS owning_tab, "
6265                                                   "d.refobjsubid AS owning_col, "
6266                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6267                                                   "c.reloptions AS reloptions, "
6268                                                   "tc.reloptions AS toast_reloptions, "
6269                                                   "NULL AS changed_acl, "
6270                                                   "NULL AS partkeydef, "
6271                                                   "false AS ispartition, "
6272                                                   "NULL AS partbound "
6273                                                   "FROM pg_class c "
6274                                                   "LEFT JOIN pg_depend d ON "
6275                                                   "(c.relkind = '%c' AND "
6276                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6277                                                   "d.objsubid = 0 AND "
6278                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6279                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6280                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6281                                                   "ORDER BY c.oid",
6282                                                   username_subquery,
6283                                                   RELKIND_SEQUENCE,
6284                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6285                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6286         }
6287         else if (fout->remoteVersion >= 80200)
6288         {
6289                 /*
6290                  * Left join to pick up dependency info linking sequences to their
6291                  * owning column, if any (note this dependency is AUTO as of 8.2)
6292                  */
6293                 appendPQExpBuffer(query,
6294                                                   "SELECT c.tableoid, c.oid, c.relname, "
6295                                                   "c.relacl, NULL as rrelacl, "
6296                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6297                                                   "c.relkind, "
6298                                                   "c.relnamespace, "
6299                                                   "(%s c.relowner) AS rolname, "
6300                                                   "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
6301                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6302                                                   "'f'::bool AS relrowsecurity, "
6303                                                   "'f'::bool AS relforcerowsecurity, "
6304                                                   "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6305                                                   "tc.relfrozenxid AS tfrozenxid, "
6306                                                   "0 AS tminmxid, "
6307                                                   "'p' AS relpersistence, 't' as relispopulated, "
6308                                                   "'d' AS relreplident, c.relpages, "
6309                                                   "NULL AS reloftype, "
6310                                                   "d.refobjid AS owning_tab, "
6311                                                   "d.refobjsubid AS owning_col, "
6312                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6313                                                   "c.reloptions AS reloptions, "
6314                                                   "NULL AS toast_reloptions, "
6315                                                   "NULL AS changed_acl, "
6316                                                   "NULL AS partkeydef, "
6317                                                   "false AS ispartition, "
6318                                                   "NULL AS partbound "
6319                                                   "FROM pg_class c "
6320                                                   "LEFT JOIN pg_depend d ON "
6321                                                   "(c.relkind = '%c' AND "
6322                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6323                                                   "d.objsubid = 0 AND "
6324                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6325                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6326                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6327                                                   "ORDER BY c.oid",
6328                                                   username_subquery,
6329                                                   RELKIND_SEQUENCE,
6330                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6331                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6332         }
6333         else
6334         {
6335                 /*
6336                  * Left join to pick up dependency info linking sequences to their
6337                  * owning column, if any
6338                  */
6339                 appendPQExpBuffer(query,
6340                                                   "SELECT c.tableoid, c.oid, relname, "
6341                                                   "relacl, NULL as rrelacl, "
6342                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6343                                                   "relkind, relnamespace, "
6344                                                   "(%s relowner) AS rolname, "
6345                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
6346                                                   "relhasindex, relhasrules, relhasoids, "
6347                                                   "'f'::bool AS relrowsecurity, "
6348                                                   "'f'::bool AS relforcerowsecurity, "
6349                                                   "0 AS relfrozenxid, 0 AS relminmxid,"
6350                                                   "0 AS toid, "
6351                                                   "0 AS tfrozenxid, 0 AS tminmxid,"
6352                                                   "'p' AS relpersistence, 't' as relispopulated, "
6353                                                   "'d' AS relreplident, relpages, "
6354                                                   "NULL AS reloftype, "
6355                                                   "d.refobjid AS owning_tab, "
6356                                                   "d.refobjsubid AS owning_col, "
6357                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6358                                                   "NULL AS reloptions, "
6359                                                   "NULL AS toast_reloptions, "
6360                                                   "NULL AS changed_acl, "
6361                                                   "NULL AS partkeydef, "
6362                                                   "false AS ispartition, "
6363                                                   "NULL AS partbound "
6364                                                   "FROM pg_class c "
6365                                                   "LEFT JOIN pg_depend d ON "
6366                                                   "(c.relkind = '%c' AND "
6367                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6368                                                   "d.objsubid = 0 AND "
6369                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
6370                                                   "WHERE relkind in ('%c', '%c', '%c', '%c') "
6371                                                   "ORDER BY c.oid",
6372                                                   username_subquery,
6373                                                   RELKIND_SEQUENCE,
6374                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6375                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6376         }
6377
6378         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6379
6380         ntups = PQntuples(res);
6381
6382         *numTables = ntups;
6383
6384         /*
6385          * Extract data from result and lock dumpable tables.  We do the locking
6386          * before anything else, to minimize the window wherein a table could
6387          * disappear under us.
6388          *
6389          * Note that we have to save info about all tables here, even when dumping
6390          * only one, because we don't yet know which tables might be inheritance
6391          * ancestors of the target table.
6392          */
6393         tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
6394
6395         i_reltableoid = PQfnumber(res, "tableoid");
6396         i_reloid = PQfnumber(res, "oid");
6397         i_relname = PQfnumber(res, "relname");
6398         i_relnamespace = PQfnumber(res, "relnamespace");
6399         i_relacl = PQfnumber(res, "relacl");
6400         i_rrelacl = PQfnumber(res, "rrelacl");
6401         i_initrelacl = PQfnumber(res, "initrelacl");
6402         i_initrrelacl = PQfnumber(res, "initrrelacl");
6403         i_relkind = PQfnumber(res, "relkind");
6404         i_rolname = PQfnumber(res, "rolname");
6405         i_relchecks = PQfnumber(res, "relchecks");
6406         i_relhastriggers = PQfnumber(res, "relhastriggers");
6407         i_relhasindex = PQfnumber(res, "relhasindex");
6408         i_relhasrules = PQfnumber(res, "relhasrules");
6409         i_relrowsec = PQfnumber(res, "relrowsecurity");
6410         i_relforcerowsec = PQfnumber(res, "relforcerowsecurity");
6411         i_relhasoids = PQfnumber(res, "relhasoids");
6412         i_relfrozenxid = PQfnumber(res, "relfrozenxid");
6413         i_relminmxid = PQfnumber(res, "relminmxid");
6414         i_toastoid = PQfnumber(res, "toid");
6415         i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
6416         i_toastminmxid = PQfnumber(res, "tminmxid");
6417         i_relpersistence = PQfnumber(res, "relpersistence");
6418         i_relispopulated = PQfnumber(res, "relispopulated");
6419         i_relreplident = PQfnumber(res, "relreplident");
6420         i_relpages = PQfnumber(res, "relpages");
6421         i_owning_tab = PQfnumber(res, "owning_tab");
6422         i_owning_col = PQfnumber(res, "owning_col");
6423         i_reltablespace = PQfnumber(res, "reltablespace");
6424         i_reloptions = PQfnumber(res, "reloptions");
6425         i_checkoption = PQfnumber(res, "checkoption");
6426         i_toastreloptions = PQfnumber(res, "toast_reloptions");
6427         i_reloftype = PQfnumber(res, "reloftype");
6428         i_is_identity_sequence = PQfnumber(res, "is_identity_sequence");
6429         i_changed_acl = PQfnumber(res, "changed_acl");
6430         i_partkeydef = PQfnumber(res, "partkeydef");
6431         i_ispartition = PQfnumber(res, "ispartition");
6432         i_partbound = PQfnumber(res, "partbound");
6433
6434         if (dopt->lockWaitTimeout)
6435         {
6436                 /*
6437                  * Arrange to fail instead of waiting forever for a table lock.
6438                  *
6439                  * NB: this coding assumes that the only queries issued within the
6440                  * following loop are LOCK TABLEs; else the timeout may be undesirably
6441                  * applied to other things too.
6442                  */
6443                 resetPQExpBuffer(query);
6444                 appendPQExpBufferStr(query, "SET statement_timeout = ");
6445                 appendStringLiteralConn(query, dopt->lockWaitTimeout, GetConnection(fout));
6446                 ExecuteSqlStatement(fout, query->data);
6447         }
6448
6449         for (i = 0; i < ntups; i++)
6450         {
6451                 tblinfo[i].dobj.objType = DO_TABLE;
6452                 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
6453                 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
6454                 AssignDumpId(&tblinfo[i].dobj);
6455                 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
6456                 tblinfo[i].dobj.namespace =
6457                         findNamespace(fout,
6458                                                   atooid(PQgetvalue(res, i, i_relnamespace)));
6459                 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6460                 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
6461                 tblinfo[i].rrelacl = pg_strdup(PQgetvalue(res, i, i_rrelacl));
6462                 tblinfo[i].initrelacl = pg_strdup(PQgetvalue(res, i, i_initrelacl));
6463                 tblinfo[i].initrrelacl = pg_strdup(PQgetvalue(res, i, i_initrrelacl));
6464                 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
6465                 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
6466                 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
6467                 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
6468                 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
6469                 tblinfo[i].rowsec = (strcmp(PQgetvalue(res, i, i_relrowsec), "t") == 0);
6470                 tblinfo[i].forcerowsec = (strcmp(PQgetvalue(res, i, i_relforcerowsec), "t") == 0);
6471                 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
6472                 tblinfo[i].relispopulated = (strcmp(PQgetvalue(res, i, i_relispopulated), "t") == 0);
6473                 tblinfo[i].relreplident = *(PQgetvalue(res, i, i_relreplident));
6474                 tblinfo[i].relpages = atoi(PQgetvalue(res, i, i_relpages));
6475                 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
6476                 tblinfo[i].minmxid = atooid(PQgetvalue(res, i, i_relminmxid));
6477                 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
6478                 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
6479                 tblinfo[i].toast_minmxid = atooid(PQgetvalue(res, i, i_toastminmxid));
6480                 if (PQgetisnull(res, i, i_reloftype))
6481                         tblinfo[i].reloftype = NULL;
6482                 else
6483                         tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
6484                 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
6485                 if (PQgetisnull(res, i, i_owning_tab))
6486                 {
6487                         tblinfo[i].owning_tab = InvalidOid;
6488                         tblinfo[i].owning_col = 0;
6489                 }
6490                 else
6491                 {
6492                         tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
6493                         tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
6494                 }
6495                 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
6496                 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
6497                 if (i_checkoption == -1 || PQgetisnull(res, i, i_checkoption))
6498                         tblinfo[i].checkoption = NULL;
6499                 else
6500                         tblinfo[i].checkoption = pg_strdup(PQgetvalue(res, i, i_checkoption));
6501                 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
6502
6503                 /* other fields were zeroed above */
6504
6505                 /*
6506                  * Decide whether we want to dump this table.
6507                  */
6508                 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
6509                         tblinfo[i].dobj.dump = DUMP_COMPONENT_NONE;
6510                 else
6511                         selectDumpableTable(&tblinfo[i], fout);
6512
6513                 /*
6514                  * If the table-level and all column-level ACLs for this table are
6515                  * unchanged, then we don't need to worry about including the ACLs for
6516                  * this table.  If any column-level ACLs have been changed, the
6517                  * 'changed_acl' column from the query will indicate that.
6518                  *
6519                  * This can result in a significant performance improvement in cases
6520                  * where we are only looking to dump out the ACL (eg: pg_catalog).
6521                  */
6522                 if (PQgetisnull(res, i, i_relacl) && PQgetisnull(res, i, i_rrelacl) &&
6523                         PQgetisnull(res, i, i_initrelacl) &&
6524                         PQgetisnull(res, i, i_initrrelacl) &&
6525                         strcmp(PQgetvalue(res, i, i_changed_acl), "f") == 0)
6526                         tblinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
6527
6528                 tblinfo[i].interesting = tblinfo[i].dobj.dump ? true : false;
6529                 tblinfo[i].dummy_view = false;  /* might get set during sort */
6530                 tblinfo[i].postponed_def = false;       /* might get set during sort */
6531
6532                 tblinfo[i].is_identity_sequence = (i_is_identity_sequence >= 0 &&
6533                                                                                    strcmp(PQgetvalue(res, i, i_is_identity_sequence), "t") == 0);
6534
6535                 /* Partition key string or NULL */
6536                 tblinfo[i].partkeydef = pg_strdup(PQgetvalue(res, i, i_partkeydef));
6537                 tblinfo[i].ispartition = (strcmp(PQgetvalue(res, i, i_ispartition), "t") == 0);
6538                 tblinfo[i].partbound = pg_strdup(PQgetvalue(res, i, i_partbound));
6539
6540                 /*
6541                  * Read-lock target tables to make sure they aren't DROPPED or altered
6542                  * in schema before we get around to dumping them.
6543                  *
6544                  * Note that we don't explicitly lock parents of the target tables; we
6545                  * assume our lock on the child is enough to prevent schema
6546                  * alterations to parent tables.
6547                  *
6548                  * NOTE: it'd be kinda nice to lock other relations too, not only
6549                  * plain or partitioned tables, but the backend doesn't presently
6550                  * allow that.
6551                  *
6552                  * We only need to lock the table for certain components; see
6553                  * pg_dump.h
6554                  */
6555                 if (tblinfo[i].dobj.dump &&
6556                         (tblinfo[i].relkind == RELKIND_RELATION ||
6557                          tblinfo->relkind == RELKIND_PARTITIONED_TABLE) &&
6558                         (tblinfo[i].dobj.dump & DUMP_COMPONENTS_REQUIRING_LOCK))
6559                 {
6560                         resetPQExpBuffer(query);
6561                         appendPQExpBuffer(query,
6562                                                           "LOCK TABLE %s IN ACCESS SHARE MODE",
6563                                                           fmtQualifiedDumpable(&tblinfo[i]));
6564                         ExecuteSqlStatement(fout, query->data);
6565                 }
6566
6567                 /* Emit notice if join for owner failed */
6568                 if (strlen(tblinfo[i].rolname) == 0)
6569                         write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
6570                                           tblinfo[i].dobj.name);
6571         }
6572
6573         if (dopt->lockWaitTimeout)
6574         {
6575                 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
6576         }
6577
6578         PQclear(res);
6579
6580         destroyPQExpBuffer(query);
6581
6582         return tblinfo;
6583 }
6584
6585 /*
6586  * getOwnedSeqs
6587  *        identify owned sequences and mark them as dumpable if owning table is
6588  *
6589  * We used to do this in getTables(), but it's better to do it after the
6590  * index used by findTableByOid() has been set up.
6591  */
6592 void
6593 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
6594 {
6595         int                     i;
6596
6597         /*
6598          * Force sequences that are "owned" by table columns to be dumped whenever
6599          * their owning table is being dumped.
6600          */
6601         for (i = 0; i < numTables; i++)
6602         {
6603                 TableInfo  *seqinfo = &tblinfo[i];
6604                 TableInfo  *owning_tab;
6605
6606                 if (!OidIsValid(seqinfo->owning_tab))
6607                         continue;                       /* not an owned sequence */
6608
6609                 owning_tab = findTableByOid(seqinfo->owning_tab);
6610                 if (owning_tab == NULL)
6611                         exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
6612                                                   seqinfo->owning_tab, seqinfo->dobj.catId.oid);
6613
6614                 /*
6615                  * We need to dump the components that are being dumped for the table
6616                  * and any components which the sequence is explicitly marked with.
6617                  *
6618                  * We can't simply use the set of components which are being dumped
6619                  * for the table as the table might be in an extension (and only the
6620                  * non-extension components, eg: ACLs if changed, security labels, and
6621                  * policies, are being dumped) while the sequence is not (and
6622                  * therefore the definition and other components should also be
6623                  * dumped).
6624                  *
6625                  * If the sequence is part of the extension then it should be properly
6626                  * marked by checkExtensionMembership() and this will be a no-op as
6627                  * the table will be equivalently marked.
6628                  */
6629                 seqinfo->dobj.dump = seqinfo->dobj.dump | owning_tab->dobj.dump;
6630
6631                 if (seqinfo->dobj.dump != DUMP_COMPONENT_NONE)
6632                         seqinfo->interesting = true;
6633         }
6634 }
6635
6636 /*
6637  * getInherits
6638  *        read all the inheritance information
6639  * from the system catalogs return them in the InhInfo* structure
6640  *
6641  * numInherits is set to the number of pairs read in
6642  */
6643 InhInfo *
6644 getInherits(Archive *fout, int *numInherits)
6645 {
6646         PGresult   *res;
6647         int                     ntups;
6648         int                     i;
6649         PQExpBuffer query = createPQExpBuffer();
6650         InhInfo    *inhinfo;
6651
6652         int                     i_inhrelid;
6653         int                     i_inhparent;
6654
6655         /*
6656          * Find all the inheritance information, excluding implicit inheritance
6657          * via partitioning.  We handle that case using getPartitions(), because
6658          * we want more information about partitions than just the parent-child
6659          * relationship.
6660          */
6661         appendPQExpBufferStr(query, "SELECT inhrelid, inhparent FROM pg_inherits");
6662
6663         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6664
6665         ntups = PQntuples(res);
6666
6667         *numInherits = ntups;
6668
6669         inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
6670
6671         i_inhrelid = PQfnumber(res, "inhrelid");
6672         i_inhparent = PQfnumber(res, "inhparent");
6673
6674         for (i = 0; i < ntups; i++)
6675         {
6676                 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
6677                 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
6678         }
6679
6680         PQclear(res);
6681
6682         destroyPQExpBuffer(query);
6683
6684         return inhinfo;
6685 }
6686
6687 /*
6688  * getIndexes
6689  *        get information about every index on a dumpable table
6690  *
6691  * Note: index data is not returned directly to the caller, but it
6692  * does get entered into the DumpableObject tables.
6693  */
6694 void
6695 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
6696 {
6697         int                     i,
6698                                 j;
6699         PQExpBuffer query = createPQExpBuffer();
6700         PGresult   *res;
6701         IndxInfo   *indxinfo;
6702         ConstraintInfo *constrinfo;
6703         int                     i_tableoid,
6704                                 i_oid,
6705                                 i_indexname,
6706                                 i_parentidx,
6707                                 i_indexdef,
6708                                 i_indnkeys,
6709                                 i_indkey,
6710                                 i_indisclustered,
6711                                 i_indisreplident,
6712                                 i_contype,
6713                                 i_conname,
6714                                 i_condeferrable,
6715                                 i_condeferred,
6716                                 i_contableoid,
6717                                 i_conoid,
6718                                 i_condef,
6719                                 i_tablespace,
6720                                 i_indreloptions,
6721                                 i_relpages;
6722         int                     ntups;
6723
6724         for (i = 0; i < numTables; i++)
6725         {
6726                 TableInfo  *tbinfo = &tblinfo[i];
6727
6728                 if (!tbinfo->hasindex)
6729                         continue;
6730
6731                 /*
6732                  * Ignore indexes of tables whose definitions are not to be dumped.
6733                  *
6734                  * We also need indexes on partitioned tables which have partitions to
6735                  * be dumped, in order to dump the indexes on the partitions.
6736                  */
6737                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION) &&
6738                         !tbinfo->interesting)
6739                         continue;
6740
6741                 if (g_verbose)
6742                         write_msg(NULL, "reading indexes for table \"%s.%s\"\n",
6743                                           tbinfo->dobj.namespace->dobj.name,
6744                                           tbinfo->dobj.name);
6745
6746                 /*
6747                  * The point of the messy-looking outer join is to find a constraint
6748                  * that is related by an internal dependency link to the index. If we
6749                  * find one, create a CONSTRAINT entry linked to the INDEX entry.  We
6750                  * assume an index won't have more than one internal dependency.
6751                  *
6752                  * As of 9.0 we don't need to look at pg_depend but can check for a
6753                  * match to pg_constraint.conindid.  The check on conrelid is
6754                  * redundant but useful because that column is indexed while conindid
6755                  * is not.
6756                  */
6757                 resetPQExpBuffer(query);
6758                 if (fout->remoteVersion >= 110000)
6759                 {
6760                         appendPQExpBuffer(query,
6761                                                           "SELECT t.tableoid, t.oid, "
6762                                                           "t.relname AS indexname, "
6763                                                           "inh.inhparent AS parentidx, "
6764                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6765                                                           "t.relnatts AS indnkeys, "
6766                                                           "i.indkey, i.indisclustered, "
6767                                                           "i.indisreplident, t.relpages, "
6768                                                           "c.contype, c.conname, "
6769                                                           "c.condeferrable, c.condeferred, "
6770                                                           "c.tableoid AS contableoid, "
6771                                                           "c.oid AS conoid, "
6772                                                           "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6773                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6774                                                           "t.reloptions AS indreloptions "
6775                                                           "FROM pg_catalog.pg_index i "
6776                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6777                                                           "JOIN pg_catalog.pg_class t2 ON (t2.oid = i.indrelid) "
6778                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6779                                                           "ON (i.indrelid = c.conrelid AND "
6780                                                           "i.indexrelid = c.conindid AND "
6781                                                           "c.contype IN ('p','u','x')) "
6782                                                           "LEFT JOIN pg_catalog.pg_inherits inh "
6783                                                           "ON (inh.inhrelid = indexrelid) "
6784                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6785                                                           "AND (i.indisvalid OR t2.relkind = 'p') "
6786                                                           "AND i.indisready "
6787                                                           "ORDER BY indexname",
6788                                                           tbinfo->dobj.catId.oid);
6789                 }
6790                 else if (fout->remoteVersion >= 90400)
6791                 {
6792                         /*
6793                          * the test on indisready is necessary in 9.2, and harmless in
6794                          * earlier/later versions
6795                          */
6796                         appendPQExpBuffer(query,
6797                                                           "SELECT t.tableoid, t.oid, "
6798                                                           "t.relname AS indexname, "
6799                                                           "0 AS parentidx, "
6800                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6801                                                           "t.relnatts AS indnkeys, "
6802                                                           "i.indkey, i.indisclustered, "
6803                                                           "i.indisreplident, t.relpages, "
6804                                                           "c.contype, c.conname, "
6805                                                           "c.condeferrable, c.condeferred, "
6806                                                           "c.tableoid AS contableoid, "
6807                                                           "c.oid AS conoid, "
6808                                                           "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6809                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6810                                                           "t.reloptions AS indreloptions "
6811                                                           "FROM pg_catalog.pg_index i "
6812                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6813                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6814                                                           "ON (i.indrelid = c.conrelid AND "
6815                                                           "i.indexrelid = c.conindid AND "
6816                                                           "c.contype IN ('p','u','x')) "
6817                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6818                                                           "AND i.indisvalid AND i.indisready "
6819                                                           "ORDER BY indexname",
6820                                                           tbinfo->dobj.catId.oid);
6821                 }
6822                 else if (fout->remoteVersion >= 90000)
6823                 {
6824                         /*
6825                          * the test on indisready is necessary in 9.2, and harmless in
6826                          * earlier/later versions
6827                          */
6828                         appendPQExpBuffer(query,
6829                                                           "SELECT t.tableoid, t.oid, "
6830                                                           "t.relname AS indexname, "
6831                                                           "0 AS parentidx, "
6832                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6833                                                           "t.relnatts AS indnkeys, "
6834                                                           "i.indkey, i.indisclustered, "
6835                                                           "false AS indisreplident, t.relpages, "
6836                                                           "c.contype, c.conname, "
6837                                                           "c.condeferrable, c.condeferred, "
6838                                                           "c.tableoid AS contableoid, "
6839                                                           "c.oid AS conoid, "
6840                                                           "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6841                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6842                                                           "t.reloptions AS indreloptions "
6843                                                           "FROM pg_catalog.pg_index i "
6844                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6845                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6846                                                           "ON (i.indrelid = c.conrelid AND "
6847                                                           "i.indexrelid = c.conindid AND "
6848                                                           "c.contype IN ('p','u','x')) "
6849                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6850                                                           "AND i.indisvalid AND i.indisready "
6851                                                           "ORDER BY indexname",
6852                                                           tbinfo->dobj.catId.oid);
6853                 }
6854                 else if (fout->remoteVersion >= 80200)
6855                 {
6856                         appendPQExpBuffer(query,
6857                                                           "SELECT t.tableoid, t.oid, "
6858                                                           "t.relname AS indexname, "
6859                                                           "0 AS parentidx, "
6860                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6861                                                           "t.relnatts AS indnkeys, "
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                                                           "null 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_depend d "
6874                                                           "ON (d.classid = t.tableoid "
6875                                                           "AND d.objid = t.oid "
6876                                                           "AND d.deptype = 'i') "
6877                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6878                                                           "ON (d.refclassid = c.tableoid "
6879                                                           "AND d.refobjid = c.oid) "
6880                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6881                                                           "AND i.indisvalid "
6882                                                           "ORDER BY indexname",
6883                                                           tbinfo->dobj.catId.oid);
6884                 }
6885                 else
6886                 {
6887                         appendPQExpBuffer(query,
6888                                                           "SELECT t.tableoid, t.oid, "
6889                                                           "t.relname AS indexname, "
6890                                                           "0 AS parentidx, "
6891                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6892                                                           "t.relnatts AS indnkeys, "
6893                                                           "i.indkey, i.indisclustered, "
6894                                                           "false AS indisreplident, t.relpages, "
6895                                                           "c.contype, c.conname, "
6896                                                           "c.condeferrable, c.condeferred, "
6897                                                           "c.tableoid AS contableoid, "
6898                                                           "c.oid AS conoid, "
6899                                                           "null AS condef, "
6900                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6901                                                           "null AS indreloptions "
6902                                                           "FROM pg_catalog.pg_index i "
6903                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6904                                                           "LEFT JOIN pg_catalog.pg_depend d "
6905                                                           "ON (d.classid = t.tableoid "
6906                                                           "AND d.objid = t.oid "
6907                                                           "AND d.deptype = 'i') "
6908                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6909                                                           "ON (d.refclassid = c.tableoid "
6910                                                           "AND d.refobjid = c.oid) "
6911                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6912                                                           "ORDER BY indexname",
6913                                                           tbinfo->dobj.catId.oid);
6914                 }
6915
6916                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6917
6918                 ntups = PQntuples(res);
6919
6920                 i_tableoid = PQfnumber(res, "tableoid");
6921                 i_oid = PQfnumber(res, "oid");
6922                 i_indexname = PQfnumber(res, "indexname");
6923                 i_parentidx = PQfnumber(res, "parentidx");
6924                 i_indexdef = PQfnumber(res, "indexdef");
6925                 i_indnkeys = PQfnumber(res, "indnkeys");
6926                 i_indkey = PQfnumber(res, "indkey");
6927                 i_indisclustered = PQfnumber(res, "indisclustered");
6928                 i_indisreplident = PQfnumber(res, "indisreplident");
6929                 i_relpages = PQfnumber(res, "relpages");
6930                 i_contype = PQfnumber(res, "contype");
6931                 i_conname = PQfnumber(res, "conname");
6932                 i_condeferrable = PQfnumber(res, "condeferrable");
6933                 i_condeferred = PQfnumber(res, "condeferred");
6934                 i_contableoid = PQfnumber(res, "contableoid");
6935                 i_conoid = PQfnumber(res, "conoid");
6936                 i_condef = PQfnumber(res, "condef");
6937                 i_tablespace = PQfnumber(res, "tablespace");
6938                 i_indreloptions = PQfnumber(res, "indreloptions");
6939
6940                 tbinfo->indexes = indxinfo =
6941                         (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
6942                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
6943                 tbinfo->numIndexes = ntups;
6944
6945                 for (j = 0; j < ntups; j++)
6946                 {
6947                         char            contype;
6948
6949                         indxinfo[j].dobj.objType = DO_INDEX;
6950                         indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
6951                         indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
6952                         AssignDumpId(&indxinfo[j].dobj);
6953                         indxinfo[j].dobj.dump = tbinfo->dobj.dump;
6954                         indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
6955                         indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6956                         indxinfo[j].indextable = tbinfo;
6957                         indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
6958                         indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
6959                         indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
6960                         indxinfo[j].indreloptions = pg_strdup(PQgetvalue(res, j, i_indreloptions));
6961                         indxinfo[j].indkeys = (Oid *) pg_malloc(indxinfo[j].indnkeys * sizeof(Oid));
6962                         parseOidArray(PQgetvalue(res, j, i_indkey),
6963                                                   indxinfo[j].indkeys, indxinfo[j].indnkeys);
6964                         indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
6965                         indxinfo[j].indisreplident = (PQgetvalue(res, j, i_indisreplident)[0] == 't');
6966                         indxinfo[j].parentidx = atooid(PQgetvalue(res, j, i_parentidx));
6967                         indxinfo[j].relpages = atoi(PQgetvalue(res, j, i_relpages));
6968                         contype = *(PQgetvalue(res, j, i_contype));
6969
6970                         if (contype == 'p' || contype == 'u' || contype == 'x')
6971                         {
6972                                 /*
6973                                  * If we found a constraint matching the index, create an
6974                                  * entry for it.
6975                                  */
6976                                 constrinfo[j].dobj.objType = DO_CONSTRAINT;
6977                                 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
6978                                 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
6979                                 AssignDumpId(&constrinfo[j].dobj);
6980                                 constrinfo[j].dobj.dump = tbinfo->dobj.dump;
6981                                 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
6982                                 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6983                                 constrinfo[j].contable = tbinfo;
6984                                 constrinfo[j].condomain = NULL;
6985                                 constrinfo[j].contype = contype;
6986                                 if (contype == 'x')
6987                                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
6988                                 else
6989                                         constrinfo[j].condef = NULL;
6990                                 constrinfo[j].confrelid = InvalidOid;
6991                                 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
6992                                 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
6993                                 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
6994                                 constrinfo[j].conislocal = true;
6995                                 constrinfo[j].separate = true;
6996
6997                                 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
6998                         }
6999                         else
7000                         {
7001                                 /* Plain secondary index */
7002                                 indxinfo[j].indexconstraint = 0;
7003                         }
7004                 }
7005
7006                 PQclear(res);
7007         }
7008
7009         destroyPQExpBuffer(query);
7010 }
7011
7012 /*
7013  * getExtendedStatistics
7014  *        get information about extended-statistics objects.
7015  *
7016  * Note: extended statistics data is not returned directly to the caller, but
7017  * it does get entered into the DumpableObject tables.
7018  */
7019 void
7020 getExtendedStatistics(Archive *fout)
7021 {
7022         PQExpBuffer query;
7023         PGresult   *res;
7024         StatsExtInfo *statsextinfo;
7025         int                     ntups;
7026         int                     i_tableoid;
7027         int                     i_oid;
7028         int                     i_stxname;
7029         int                     i_stxnamespace;
7030         int                     i_rolname;
7031         int                     i;
7032
7033         /* Extended statistics were new in v10 */
7034         if (fout->remoteVersion < 100000)
7035                 return;
7036
7037         query = createPQExpBuffer();
7038
7039         appendPQExpBuffer(query, "SELECT tableoid, oid, stxname, "
7040                                           "stxnamespace, (%s stxowner) AS rolname "
7041                                           "FROM pg_catalog.pg_statistic_ext",
7042                                           username_subquery);
7043
7044         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7045
7046         ntups = PQntuples(res);
7047
7048         i_tableoid = PQfnumber(res, "tableoid");
7049         i_oid = PQfnumber(res, "oid");
7050         i_stxname = PQfnumber(res, "stxname");
7051         i_stxnamespace = PQfnumber(res, "stxnamespace");
7052         i_rolname = PQfnumber(res, "rolname");
7053
7054         statsextinfo = (StatsExtInfo *) pg_malloc(ntups * sizeof(StatsExtInfo));
7055
7056         for (i = 0; i < ntups; i++)
7057         {
7058                 statsextinfo[i].dobj.objType = DO_STATSEXT;
7059                 statsextinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7060                 statsextinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7061                 AssignDumpId(&statsextinfo[i].dobj);
7062                 statsextinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_stxname));
7063                 statsextinfo[i].dobj.namespace =
7064                         findNamespace(fout,
7065                                                   atooid(PQgetvalue(res, i, i_stxnamespace)));
7066                 statsextinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7067
7068                 /* Decide whether we want to dump it */
7069                 selectDumpableObject(&(statsextinfo[i].dobj), fout);
7070
7071                 /* Stats objects do not currently have ACLs. */
7072                 statsextinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7073         }
7074
7075         PQclear(res);
7076         destroyPQExpBuffer(query);
7077 }
7078
7079 /*
7080  * getConstraints
7081  *
7082  * Get info about constraints on dumpable tables.
7083  *
7084  * Currently handles foreign keys only.
7085  * Unique and primary key constraints are handled with indexes,
7086  * while check constraints are processed in getTableAttrs().
7087  */
7088 void
7089 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
7090 {
7091         int                     i,
7092                                 j;
7093         ConstraintInfo *constrinfo;
7094         PQExpBuffer query;
7095         PGresult   *res;
7096         int                     i_contableoid,
7097                                 i_conoid,
7098                                 i_conname,
7099                                 i_confrelid,
7100                                 i_condef;
7101         int                     ntups;
7102
7103         query = createPQExpBuffer();
7104
7105         for (i = 0; i < numTables; i++)
7106         {
7107                 TableInfo  *tbinfo = &tblinfo[i];
7108
7109                 if (!tbinfo->hastriggers ||
7110                         !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7111                         continue;
7112
7113                 if (g_verbose)
7114                         write_msg(NULL, "reading foreign key constraints for table \"%s.%s\"\n",
7115                                           tbinfo->dobj.namespace->dobj.name,
7116                                           tbinfo->dobj.name);
7117
7118                 resetPQExpBuffer(query);
7119                 appendPQExpBuffer(query,
7120                                                   "SELECT tableoid, oid, conname, confrelid, "
7121                                                   "pg_catalog.pg_get_constraintdef(oid) AS condef "
7122                                                   "FROM pg_catalog.pg_constraint "
7123                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
7124                                                   "AND contype = 'f'",
7125                                                   tbinfo->dobj.catId.oid);
7126                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7127
7128                 ntups = PQntuples(res);
7129
7130                 i_contableoid = PQfnumber(res, "tableoid");
7131                 i_conoid = PQfnumber(res, "oid");
7132                 i_conname = PQfnumber(res, "conname");
7133                 i_confrelid = PQfnumber(res, "confrelid");
7134                 i_condef = PQfnumber(res, "condef");
7135
7136                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7137
7138                 for (j = 0; j < ntups; j++)
7139                 {
7140                         constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
7141                         constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
7142                         constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7143                         AssignDumpId(&constrinfo[j].dobj);
7144                         constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7145                         constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7146                         constrinfo[j].contable = tbinfo;
7147                         constrinfo[j].condomain = NULL;
7148                         constrinfo[j].contype = 'f';
7149                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
7150                         constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
7151                         constrinfo[j].conindex = 0;
7152                         constrinfo[j].condeferrable = false;
7153                         constrinfo[j].condeferred = false;
7154                         constrinfo[j].conislocal = true;
7155                         constrinfo[j].separate = true;
7156                 }
7157
7158                 PQclear(res);
7159         }
7160
7161         destroyPQExpBuffer(query);
7162 }
7163
7164 /*
7165  * getDomainConstraints
7166  *
7167  * Get info about constraints on a domain.
7168  */
7169 static void
7170 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
7171 {
7172         int                     i;
7173         ConstraintInfo *constrinfo;
7174         PQExpBuffer query;
7175         PGresult   *res;
7176         int                     i_tableoid,
7177                                 i_oid,
7178                                 i_conname,
7179                                 i_consrc;
7180         int                     ntups;
7181
7182         query = createPQExpBuffer();
7183
7184         if (fout->remoteVersion >= 90100)
7185                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7186                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7187                                                   "convalidated "
7188                                                   "FROM pg_catalog.pg_constraint "
7189                                                   "WHERE contypid = '%u'::pg_catalog.oid "
7190                                                   "ORDER BY conname",
7191                                                   tyinfo->dobj.catId.oid);
7192
7193         else
7194                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7195                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7196                                                   "true as convalidated "
7197                                                   "FROM pg_catalog.pg_constraint "
7198                                                   "WHERE contypid = '%u'::pg_catalog.oid "
7199                                                   "ORDER BY conname",
7200                                                   tyinfo->dobj.catId.oid);
7201
7202         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7203
7204         ntups = PQntuples(res);
7205
7206         i_tableoid = PQfnumber(res, "tableoid");
7207         i_oid = PQfnumber(res, "oid");
7208         i_conname = PQfnumber(res, "conname");
7209         i_consrc = PQfnumber(res, "consrc");
7210
7211         constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7212
7213         tyinfo->nDomChecks = ntups;
7214         tyinfo->domChecks = constrinfo;
7215
7216         for (i = 0; i < ntups; i++)
7217         {
7218                 bool            validated = PQgetvalue(res, i, 4)[0] == 't';
7219
7220                 constrinfo[i].dobj.objType = DO_CONSTRAINT;
7221                 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7222                 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7223                 AssignDumpId(&constrinfo[i].dobj);
7224                 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
7225                 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
7226                 constrinfo[i].contable = NULL;
7227                 constrinfo[i].condomain = tyinfo;
7228                 constrinfo[i].contype = 'c';
7229                 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
7230                 constrinfo[i].confrelid = InvalidOid;
7231                 constrinfo[i].conindex = 0;
7232                 constrinfo[i].condeferrable = false;
7233                 constrinfo[i].condeferred = false;
7234                 constrinfo[i].conislocal = true;
7235
7236                 constrinfo[i].separate = !validated;
7237
7238                 /*
7239                  * Make the domain depend on the constraint, ensuring it won't be
7240                  * output till any constraint dependencies are OK.  If the constraint
7241                  * has not been validated, it's going to be dumped after the domain
7242                  * anyway, so this doesn't matter.
7243                  */
7244                 if (validated)
7245                         addObjectDependency(&tyinfo->dobj,
7246                                                                 constrinfo[i].dobj.dumpId);
7247         }
7248
7249         PQclear(res);
7250
7251         destroyPQExpBuffer(query);
7252 }
7253
7254 /*
7255  * getRules
7256  *        get basic information about every rule in the system
7257  *
7258  * numRules is set to the number of rules read in
7259  */
7260 RuleInfo *
7261 getRules(Archive *fout, int *numRules)
7262 {
7263         PGresult   *res;
7264         int                     ntups;
7265         int                     i;
7266         PQExpBuffer query = createPQExpBuffer();
7267         RuleInfo   *ruleinfo;
7268         int                     i_tableoid;
7269         int                     i_oid;
7270         int                     i_rulename;
7271         int                     i_ruletable;
7272         int                     i_ev_type;
7273         int                     i_is_instead;
7274         int                     i_ev_enabled;
7275
7276         if (fout->remoteVersion >= 80300)
7277         {
7278                 appendPQExpBufferStr(query, "SELECT "
7279                                                          "tableoid, oid, rulename, "
7280                                                          "ev_class AS ruletable, ev_type, is_instead, "
7281                                                          "ev_enabled "
7282                                                          "FROM pg_rewrite "
7283                                                          "ORDER BY oid");
7284         }
7285         else
7286         {
7287                 appendPQExpBufferStr(query, "SELECT "
7288                                                          "tableoid, oid, rulename, "
7289                                                          "ev_class AS ruletable, ev_type, is_instead, "
7290                                                          "'O'::char AS ev_enabled "
7291                                                          "FROM pg_rewrite "
7292                                                          "ORDER BY oid");
7293         }
7294
7295         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7296
7297         ntups = PQntuples(res);
7298
7299         *numRules = ntups;
7300
7301         ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
7302
7303         i_tableoid = PQfnumber(res, "tableoid");
7304         i_oid = PQfnumber(res, "oid");
7305         i_rulename = PQfnumber(res, "rulename");
7306         i_ruletable = PQfnumber(res, "ruletable");
7307         i_ev_type = PQfnumber(res, "ev_type");
7308         i_is_instead = PQfnumber(res, "is_instead");
7309         i_ev_enabled = PQfnumber(res, "ev_enabled");
7310
7311         for (i = 0; i < ntups; i++)
7312         {
7313                 Oid                     ruletableoid;
7314
7315                 ruleinfo[i].dobj.objType = DO_RULE;
7316                 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7317                 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7318                 AssignDumpId(&ruleinfo[i].dobj);
7319                 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
7320                 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
7321                 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
7322                 if (ruleinfo[i].ruletable == NULL)
7323                         exit_horribly(NULL, "failed sanity check, parent table with OID %u of pg_rewrite entry with OID %u not found\n",
7324                                                   ruletableoid, ruleinfo[i].dobj.catId.oid);
7325                 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
7326                 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
7327                 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
7328                 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
7329                 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
7330                 if (ruleinfo[i].ruletable)
7331                 {
7332                         /*
7333                          * If the table is a view or materialized view, force its ON
7334                          * SELECT rule to be sorted before the view itself --- this
7335                          * ensures that any dependencies for the rule affect the table's
7336                          * positioning. Other rules are forced to appear after their
7337                          * table.
7338                          */
7339                         if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
7340                                  ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
7341                                 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
7342                         {
7343                                 addObjectDependency(&ruleinfo[i].ruletable->dobj,
7344                                                                         ruleinfo[i].dobj.dumpId);
7345                                 /* We'll merge the rule into CREATE VIEW, if possible */
7346                                 ruleinfo[i].separate = false;
7347                         }
7348                         else
7349                         {
7350                                 addObjectDependency(&ruleinfo[i].dobj,
7351                                                                         ruleinfo[i].ruletable->dobj.dumpId);
7352                                 ruleinfo[i].separate = true;
7353                         }
7354                 }
7355                 else
7356                         ruleinfo[i].separate = true;
7357         }
7358
7359         PQclear(res);
7360
7361         destroyPQExpBuffer(query);
7362
7363         return ruleinfo;
7364 }
7365
7366 /*
7367  * getTriggers
7368  *        get information about every trigger on a dumpable table
7369  *
7370  * Note: trigger data is not returned directly to the caller, but it
7371  * does get entered into the DumpableObject tables.
7372  */
7373 void
7374 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
7375 {
7376         int                     i,
7377                                 j;
7378         PQExpBuffer query = createPQExpBuffer();
7379         PGresult   *res;
7380         TriggerInfo *tginfo;
7381         int                     i_tableoid,
7382                                 i_oid,
7383                                 i_tgname,
7384                                 i_tgfname,
7385                                 i_tgtype,
7386                                 i_tgnargs,
7387                                 i_tgargs,
7388                                 i_tgisconstraint,
7389                                 i_tgconstrname,
7390                                 i_tgconstrrelid,
7391                                 i_tgconstrrelname,
7392                                 i_tgenabled,
7393                                 i_tgdeferrable,
7394                                 i_tginitdeferred,
7395                                 i_tgdef;
7396         int                     ntups;
7397
7398         for (i = 0; i < numTables; i++)
7399         {
7400                 TableInfo  *tbinfo = &tblinfo[i];
7401
7402                 if (!tbinfo->hastriggers ||
7403                         !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7404                         continue;
7405
7406                 if (g_verbose)
7407                         write_msg(NULL, "reading triggers for table \"%s.%s\"\n",
7408                                           tbinfo->dobj.namespace->dobj.name,
7409                                           tbinfo->dobj.name);
7410
7411                 resetPQExpBuffer(query);
7412                 if (fout->remoteVersion >= 90000)
7413                 {
7414                         /*
7415                          * NB: think not to use pretty=true in pg_get_triggerdef.  It
7416                          * could result in non-forward-compatible dumps of WHEN clauses
7417                          * due to under-parenthesization.
7418                          */
7419                         appendPQExpBuffer(query,
7420                                                           "SELECT tgname, "
7421                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
7422                                                           "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
7423                                                           "tgenabled, tableoid, oid "
7424                                                           "FROM pg_catalog.pg_trigger t "
7425                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
7426                                                           "AND NOT tgisinternal",
7427                                                           tbinfo->dobj.catId.oid);
7428                 }
7429                 else if (fout->remoteVersion >= 80300)
7430                 {
7431                         /*
7432                          * We ignore triggers that are tied to a foreign-key constraint
7433                          */
7434                         appendPQExpBuffer(query,
7435                                                           "SELECT tgname, "
7436                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
7437                                                           "tgtype, tgnargs, tgargs, tgenabled, "
7438                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
7439                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
7440                                                           "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7441                                                           "FROM pg_catalog.pg_trigger t "
7442                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
7443                                                           "AND tgconstraint = 0",
7444                                                           tbinfo->dobj.catId.oid);
7445                 }
7446                 else
7447                 {
7448                         /*
7449                          * We ignore triggers that are tied to a foreign-key constraint,
7450                          * but in these versions we have to grovel through pg_constraint
7451                          * to find out
7452                          */
7453                         appendPQExpBuffer(query,
7454                                                           "SELECT tgname, "
7455                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
7456                                                           "tgtype, tgnargs, tgargs, tgenabled, "
7457                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
7458                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
7459                                                           "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7460                                                           "FROM pg_catalog.pg_trigger t "
7461                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
7462                                                           "AND (NOT tgisconstraint "
7463                                                           " OR NOT EXISTS"
7464                                                           "  (SELECT 1 FROM pg_catalog.pg_depend d "
7465                                                           "   JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
7466                                                           "   WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
7467                                                           tbinfo->dobj.catId.oid);
7468                 }
7469
7470                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7471
7472                 ntups = PQntuples(res);
7473
7474                 i_tableoid = PQfnumber(res, "tableoid");
7475                 i_oid = PQfnumber(res, "oid");
7476                 i_tgname = PQfnumber(res, "tgname");
7477                 i_tgfname = PQfnumber(res, "tgfname");
7478                 i_tgtype = PQfnumber(res, "tgtype");
7479                 i_tgnargs = PQfnumber(res, "tgnargs");
7480                 i_tgargs = PQfnumber(res, "tgargs");
7481                 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
7482                 i_tgconstrname = PQfnumber(res, "tgconstrname");
7483                 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
7484                 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
7485                 i_tgenabled = PQfnumber(res, "tgenabled");
7486                 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
7487                 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
7488                 i_tgdef = PQfnumber(res, "tgdef");
7489
7490                 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
7491
7492                 tbinfo->numTriggers = ntups;
7493                 tbinfo->triggers = tginfo;
7494
7495                 for (j = 0; j < ntups; j++)
7496                 {
7497                         tginfo[j].dobj.objType = DO_TRIGGER;
7498                         tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
7499                         tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
7500                         AssignDumpId(&tginfo[j].dobj);
7501                         tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
7502                         tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
7503                         tginfo[j].tgtable = tbinfo;
7504                         tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
7505                         if (i_tgdef >= 0)
7506                         {
7507                                 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
7508
7509                                 /* remaining fields are not valid if we have tgdef */
7510                                 tginfo[j].tgfname = NULL;
7511                                 tginfo[j].tgtype = 0;
7512                                 tginfo[j].tgnargs = 0;
7513                                 tginfo[j].tgargs = NULL;
7514                                 tginfo[j].tgisconstraint = false;
7515                                 tginfo[j].tgdeferrable = false;
7516                                 tginfo[j].tginitdeferred = false;
7517                                 tginfo[j].tgconstrname = NULL;
7518                                 tginfo[j].tgconstrrelid = InvalidOid;
7519                                 tginfo[j].tgconstrrelname = NULL;
7520                         }
7521                         else
7522                         {
7523                                 tginfo[j].tgdef = NULL;
7524
7525                                 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
7526                                 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
7527                                 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
7528                                 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
7529                                 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
7530                                 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
7531                                 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
7532
7533                                 if (tginfo[j].tgisconstraint)
7534                                 {
7535                                         tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
7536                                         tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
7537                                         if (OidIsValid(tginfo[j].tgconstrrelid))
7538                                         {
7539                                                 if (PQgetisnull(res, j, i_tgconstrrelname))
7540                                                         exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
7541                                                                                   tginfo[j].dobj.name,
7542                                                                                   tbinfo->dobj.name,
7543                                                                                   tginfo[j].tgconstrrelid);
7544                                                 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
7545                                         }
7546                                         else
7547                                                 tginfo[j].tgconstrrelname = NULL;
7548                                 }
7549                                 else
7550                                 {
7551                                         tginfo[j].tgconstrname = NULL;
7552                                         tginfo[j].tgconstrrelid = InvalidOid;
7553                                         tginfo[j].tgconstrrelname = NULL;
7554                                 }
7555                         }
7556                 }
7557
7558                 PQclear(res);
7559         }
7560
7561         destroyPQExpBuffer(query);
7562 }
7563
7564 /*
7565  * getEventTriggers
7566  *        get information about event triggers
7567  */
7568 EventTriggerInfo *
7569 getEventTriggers(Archive *fout, int *numEventTriggers)
7570 {
7571         int                     i;
7572         PQExpBuffer query;
7573         PGresult   *res;
7574         EventTriggerInfo *evtinfo;
7575         int                     i_tableoid,
7576                                 i_oid,
7577                                 i_evtname,
7578                                 i_evtevent,
7579                                 i_evtowner,
7580                                 i_evttags,
7581                                 i_evtfname,
7582                                 i_evtenabled;
7583         int                     ntups;
7584
7585         /* Before 9.3, there are no event triggers */
7586         if (fout->remoteVersion < 90300)
7587         {
7588                 *numEventTriggers = 0;
7589                 return NULL;
7590         }
7591
7592         query = createPQExpBuffer();
7593
7594         appendPQExpBuffer(query,
7595                                           "SELECT e.tableoid, e.oid, evtname, evtenabled, "
7596                                           "evtevent, (%s evtowner) AS evtowner, "
7597                                           "array_to_string(array("
7598                                           "select quote_literal(x) "
7599                                           " from unnest(evttags) as t(x)), ', ') as evttags, "
7600                                           "e.evtfoid::regproc as evtfname "
7601                                           "FROM pg_event_trigger e "
7602                                           "ORDER BY e.oid",
7603                                           username_subquery);
7604
7605         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7606
7607         ntups = PQntuples(res);
7608
7609         *numEventTriggers = ntups;
7610
7611         evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
7612
7613         i_tableoid = PQfnumber(res, "tableoid");
7614         i_oid = PQfnumber(res, "oid");
7615         i_evtname = PQfnumber(res, "evtname");
7616         i_evtevent = PQfnumber(res, "evtevent");
7617         i_evtowner = PQfnumber(res, "evtowner");
7618         i_evttags = PQfnumber(res, "evttags");
7619         i_evtfname = PQfnumber(res, "evtfname");
7620         i_evtenabled = PQfnumber(res, "evtenabled");
7621
7622         for (i = 0; i < ntups; i++)
7623         {
7624                 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
7625                 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7626                 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7627                 AssignDumpId(&evtinfo[i].dobj);
7628                 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
7629                 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
7630                 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
7631                 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
7632                 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
7633                 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
7634                 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
7635
7636                 /* Decide whether we want to dump it */
7637                 selectDumpableObject(&(evtinfo[i].dobj), fout);
7638
7639                 /* Event Triggers do not currently have ACLs. */
7640                 evtinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7641         }
7642
7643         PQclear(res);
7644
7645         destroyPQExpBuffer(query);
7646
7647         return evtinfo;
7648 }
7649
7650 /*
7651  * getProcLangs
7652  *        get basic information about every procedural language in the system
7653  *
7654  * numProcLangs is set to the number of langs read in
7655  *
7656  * NB: this must run after getFuncs() because we assume we can do
7657  * findFuncByOid().
7658  */
7659 ProcLangInfo *
7660 getProcLangs(Archive *fout, int *numProcLangs)
7661 {
7662         DumpOptions *dopt = fout->dopt;
7663         PGresult   *res;
7664         int                     ntups;
7665         int                     i;
7666         PQExpBuffer query = createPQExpBuffer();
7667         ProcLangInfo *planginfo;
7668         int                     i_tableoid;
7669         int                     i_oid;
7670         int                     i_lanname;
7671         int                     i_lanpltrusted;
7672         int                     i_lanplcallfoid;
7673         int                     i_laninline;
7674         int                     i_lanvalidator;
7675         int                     i_lanacl;
7676         int                     i_rlanacl;
7677         int                     i_initlanacl;
7678         int                     i_initrlanacl;
7679         int                     i_lanowner;
7680
7681         if (fout->remoteVersion >= 90600)
7682         {
7683                 PQExpBuffer acl_subquery = createPQExpBuffer();
7684                 PQExpBuffer racl_subquery = createPQExpBuffer();
7685                 PQExpBuffer initacl_subquery = createPQExpBuffer();
7686                 PQExpBuffer initracl_subquery = createPQExpBuffer();
7687
7688                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
7689                                                 initracl_subquery, "l.lanacl", "l.lanowner", "'l'",
7690                                                 dopt->binary_upgrade);
7691
7692                 /* pg_language has a laninline column */
7693                 appendPQExpBuffer(query, "SELECT l.tableoid, l.oid, "
7694                                                   "l.lanname, l.lanpltrusted, l.lanplcallfoid, "
7695                                                   "l.laninline, l.lanvalidator, "
7696                                                   "%s AS lanacl, "
7697                                                   "%s AS rlanacl, "
7698                                                   "%s AS initlanacl, "
7699                                                   "%s AS initrlanacl, "
7700                                                   "(%s l.lanowner) AS lanowner "
7701                                                   "FROM pg_language l "
7702                                                   "LEFT JOIN pg_init_privs pip ON "
7703                                                   "(l.oid = pip.objoid "
7704                                                   "AND pip.classoid = 'pg_language'::regclass "
7705                                                   "AND pip.objsubid = 0) "
7706                                                   "WHERE l.lanispl "
7707                                                   "ORDER BY l.oid",
7708                                                   acl_subquery->data,
7709                                                   racl_subquery->data,
7710                                                   initacl_subquery->data,
7711                                                   initracl_subquery->data,
7712                                                   username_subquery);
7713
7714                 destroyPQExpBuffer(acl_subquery);
7715                 destroyPQExpBuffer(racl_subquery);
7716                 destroyPQExpBuffer(initacl_subquery);
7717                 destroyPQExpBuffer(initracl_subquery);
7718         }
7719         else if (fout->remoteVersion >= 90000)
7720         {
7721                 /* pg_language has a laninline column */
7722                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7723                                                   "lanname, lanpltrusted, lanplcallfoid, "
7724                                                   "laninline, lanvalidator, lanacl, NULL AS rlanacl, "
7725                                                   "NULL AS initlanacl, NULL AS initrlanacl, "
7726                                                   "(%s lanowner) AS lanowner "
7727                                                   "FROM pg_language "
7728                                                   "WHERE lanispl "
7729                                                   "ORDER BY oid",
7730                                                   username_subquery);
7731         }
7732         else if (fout->remoteVersion >= 80300)
7733         {
7734                 /* pg_language has a lanowner column */
7735                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7736                                                   "lanname, lanpltrusted, lanplcallfoid, "
7737                                                   "0 AS laninline, lanvalidator, lanacl, "
7738                                                   "NULL AS rlanacl, "
7739                                                   "NULL AS initlanacl, NULL AS initrlanacl, "
7740                                                   "(%s lanowner) AS lanowner "
7741                                                   "FROM pg_language "
7742                                                   "WHERE lanispl "
7743                                                   "ORDER BY oid",
7744                                                   username_subquery);
7745         }
7746         else if (fout->remoteVersion >= 80100)
7747         {
7748                 /* Languages are owned by the bootstrap superuser, OID 10 */
7749                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7750                                                   "lanname, lanpltrusted, lanplcallfoid, "
7751                                                   "0 AS laninline, lanvalidator, lanacl, "
7752                                                   "NULL AS rlanacl, "
7753                                                   "NULL AS initlanacl, NULL AS initrlanacl, "
7754                                                   "(%s '10') AS lanowner "
7755                                                   "FROM pg_language "
7756                                                   "WHERE lanispl "
7757                                                   "ORDER BY oid",
7758                                                   username_subquery);
7759         }
7760         else
7761         {
7762                 /* Languages are owned by the bootstrap superuser, sysid 1 */
7763                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7764                                                   "lanname, lanpltrusted, lanplcallfoid, "
7765                                                   "0 AS laninline, lanvalidator, lanacl, "
7766                                                   "NULL AS rlanacl, "
7767                                                   "NULL AS initlanacl, NULL AS initrlanacl, "
7768                                                   "(%s '1') AS lanowner "
7769                                                   "FROM pg_language "
7770                                                   "WHERE lanispl "
7771                                                   "ORDER BY oid",
7772                                                   username_subquery);
7773         }
7774
7775         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7776
7777         ntups = PQntuples(res);
7778
7779         *numProcLangs = ntups;
7780
7781         planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
7782
7783         i_tableoid = PQfnumber(res, "tableoid");
7784         i_oid = PQfnumber(res, "oid");
7785         i_lanname = PQfnumber(res, "lanname");
7786         i_lanpltrusted = PQfnumber(res, "lanpltrusted");
7787         i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
7788         i_laninline = PQfnumber(res, "laninline");
7789         i_lanvalidator = PQfnumber(res, "lanvalidator");
7790         i_lanacl = PQfnumber(res, "lanacl");
7791         i_rlanacl = PQfnumber(res, "rlanacl");
7792         i_initlanacl = PQfnumber(res, "initlanacl");
7793         i_initrlanacl = PQfnumber(res, "initrlanacl");
7794         i_lanowner = PQfnumber(res, "lanowner");
7795
7796         for (i = 0; i < ntups; i++)
7797         {
7798                 planginfo[i].dobj.objType = DO_PROCLANG;
7799                 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7800                 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7801                 AssignDumpId(&planginfo[i].dobj);
7802
7803                 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
7804                 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
7805                 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
7806                 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
7807                 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
7808                 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
7809                 planginfo[i].rlanacl = pg_strdup(PQgetvalue(res, i, i_rlanacl));
7810                 planginfo[i].initlanacl = pg_strdup(PQgetvalue(res, i, i_initlanacl));
7811                 planginfo[i].initrlanacl = pg_strdup(PQgetvalue(res, i, i_initrlanacl));
7812                 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
7813
7814                 /* Decide whether we want to dump it */
7815                 selectDumpableProcLang(&(planginfo[i]), fout);
7816
7817                 /* Do not try to dump ACL if no ACL exists. */
7818                 if (PQgetisnull(res, i, i_lanacl) && PQgetisnull(res, i, i_rlanacl) &&
7819                         PQgetisnull(res, i, i_initlanacl) &&
7820                         PQgetisnull(res, i, i_initrlanacl))
7821                         planginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7822         }
7823
7824         PQclear(res);
7825
7826         destroyPQExpBuffer(query);
7827
7828         return planginfo;
7829 }
7830
7831 /*
7832  * getCasts
7833  *        get basic information about every cast in the system
7834  *
7835  * numCasts is set to the number of casts read in
7836  */
7837 CastInfo *
7838 getCasts(Archive *fout, int *numCasts)
7839 {
7840         PGresult   *res;
7841         int                     ntups;
7842         int                     i;
7843         PQExpBuffer query = createPQExpBuffer();
7844         CastInfo   *castinfo;
7845         int                     i_tableoid;
7846         int                     i_oid;
7847         int                     i_castsource;
7848         int                     i_casttarget;
7849         int                     i_castfunc;
7850         int                     i_castcontext;
7851         int                     i_castmethod;
7852
7853         if (fout->remoteVersion >= 80400)
7854         {
7855                 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7856                                                          "castsource, casttarget, castfunc, castcontext, "
7857                                                          "castmethod "
7858                                                          "FROM pg_cast ORDER BY 3,4");
7859         }
7860         else
7861         {
7862                 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7863                                                          "castsource, casttarget, castfunc, castcontext, "
7864                                                          "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
7865                                                          "FROM pg_cast ORDER BY 3,4");
7866         }
7867
7868         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7869
7870         ntups = PQntuples(res);
7871
7872         *numCasts = ntups;
7873
7874         castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
7875
7876         i_tableoid = PQfnumber(res, "tableoid");
7877         i_oid = PQfnumber(res, "oid");
7878         i_castsource = PQfnumber(res, "castsource");
7879         i_casttarget = PQfnumber(res, "casttarget");
7880         i_castfunc = PQfnumber(res, "castfunc");
7881         i_castcontext = PQfnumber(res, "castcontext");
7882         i_castmethod = PQfnumber(res, "castmethod");
7883
7884         for (i = 0; i < ntups; i++)
7885         {
7886                 PQExpBufferData namebuf;
7887                 TypeInfo   *sTypeInfo;
7888                 TypeInfo   *tTypeInfo;
7889
7890                 castinfo[i].dobj.objType = DO_CAST;
7891                 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7892                 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7893                 AssignDumpId(&castinfo[i].dobj);
7894                 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
7895                 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
7896                 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
7897                 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
7898                 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
7899
7900                 /*
7901                  * Try to name cast as concatenation of typnames.  This is only used
7902                  * for purposes of sorting.  If we fail to find either type, the name
7903                  * will be an empty string.
7904                  */
7905                 initPQExpBuffer(&namebuf);
7906                 sTypeInfo = findTypeByOid(castinfo[i].castsource);
7907                 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
7908                 if (sTypeInfo && tTypeInfo)
7909                         appendPQExpBuffer(&namebuf, "%s %s",
7910                                                           sTypeInfo->dobj.name, tTypeInfo->dobj.name);
7911                 castinfo[i].dobj.name = namebuf.data;
7912
7913                 /* Decide whether we want to dump it */
7914                 selectDumpableCast(&(castinfo[i]), fout);
7915
7916                 /* Casts do not currently have ACLs. */
7917                 castinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7918         }
7919
7920         PQclear(res);
7921
7922         destroyPQExpBuffer(query);
7923
7924         return castinfo;
7925 }
7926
7927 static char *
7928 get_language_name(Archive *fout, Oid langid)
7929 {
7930         PQExpBuffer query;
7931         PGresult   *res;
7932         char       *lanname;
7933
7934         query = createPQExpBuffer();
7935         appendPQExpBuffer(query, "SELECT lanname FROM pg_language WHERE oid = %u", langid);
7936         res = ExecuteSqlQueryForSingleRow(fout, query->data);
7937         lanname = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
7938         destroyPQExpBuffer(query);
7939         PQclear(res);
7940
7941         return lanname;
7942 }
7943
7944 /*
7945  * getTransforms
7946  *        get basic information about every transform in the system
7947  *
7948  * numTransforms is set to the number of transforms read in
7949  */
7950 TransformInfo *
7951 getTransforms(Archive *fout, int *numTransforms)
7952 {
7953         PGresult   *res;
7954         int                     ntups;
7955         int                     i;
7956         PQExpBuffer query;
7957         TransformInfo *transforminfo;
7958         int                     i_tableoid;
7959         int                     i_oid;
7960         int                     i_trftype;
7961         int                     i_trflang;
7962         int                     i_trffromsql;
7963         int                     i_trftosql;
7964
7965         /* Transforms didn't exist pre-9.5 */
7966         if (fout->remoteVersion < 90500)
7967         {
7968                 *numTransforms = 0;
7969                 return NULL;
7970         }
7971
7972         query = createPQExpBuffer();
7973
7974         appendPQExpBuffer(query, "SELECT tableoid, oid, "
7975                                           "trftype, trflang, trffromsql::oid, trftosql::oid "
7976                                           "FROM pg_transform "
7977                                           "ORDER BY 3,4");
7978
7979         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7980
7981         ntups = PQntuples(res);
7982
7983         *numTransforms = ntups;
7984
7985         transforminfo = (TransformInfo *) pg_malloc(ntups * sizeof(TransformInfo));
7986
7987         i_tableoid = PQfnumber(res, "tableoid");
7988         i_oid = PQfnumber(res, "oid");
7989         i_trftype = PQfnumber(res, "trftype");
7990         i_trflang = PQfnumber(res, "trflang");
7991         i_trffromsql = PQfnumber(res, "trffromsql");
7992         i_trftosql = PQfnumber(res, "trftosql");
7993
7994         for (i = 0; i < ntups; i++)
7995         {
7996                 PQExpBufferData namebuf;
7997                 TypeInfo   *typeInfo;
7998                 char       *lanname;
7999
8000                 transforminfo[i].dobj.objType = DO_TRANSFORM;
8001                 transforminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8002                 transforminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8003                 AssignDumpId(&transforminfo[i].dobj);
8004                 transforminfo[i].trftype = atooid(PQgetvalue(res, i, i_trftype));
8005                 transforminfo[i].trflang = atooid(PQgetvalue(res, i, i_trflang));
8006                 transforminfo[i].trffromsql = atooid(PQgetvalue(res, i, i_trffromsql));
8007                 transforminfo[i].trftosql = atooid(PQgetvalue(res, i, i_trftosql));
8008
8009                 /*
8010                  * Try to name transform as concatenation of type and language name.
8011                  * This is only used for purposes of sorting.  If we fail to find
8012                  * either, the name will be an empty string.
8013                  */
8014                 initPQExpBuffer(&namebuf);
8015                 typeInfo = findTypeByOid(transforminfo[i].trftype);
8016                 lanname = get_language_name(fout, transforminfo[i].trflang);
8017                 if (typeInfo && lanname)
8018                         appendPQExpBuffer(&namebuf, "%s %s",
8019                                                           typeInfo->dobj.name, lanname);
8020                 transforminfo[i].dobj.name = namebuf.data;
8021                 free(lanname);
8022
8023                 /* Decide whether we want to dump it */
8024                 selectDumpableObject(&(transforminfo[i].dobj), fout);
8025         }
8026
8027         PQclear(res);
8028
8029         destroyPQExpBuffer(query);
8030
8031         return transforminfo;
8032 }
8033
8034 /*
8035  * getTableAttrs -
8036  *        for each interesting table, read info about its attributes
8037  *        (names, types, default values, CHECK constraints, etc)
8038  *
8039  * This is implemented in a very inefficient way right now, looping
8040  * through the tblinfo and doing a join per table to find the attrs and their
8041  * types.  However, because we want type names and so forth to be named
8042  * relative to the schema of each table, we couldn't do it in just one
8043  * query.  (Maybe one query per schema?)
8044  *
8045  *      modifies tblinfo
8046  */
8047 void
8048 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
8049 {
8050         DumpOptions *dopt = fout->dopt;
8051         int                     i,
8052                                 j;
8053         PQExpBuffer q = createPQExpBuffer();
8054         int                     i_attnum;
8055         int                     i_attname;
8056         int                     i_atttypname;
8057         int                     i_atttypmod;
8058         int                     i_attstattarget;
8059         int                     i_attstorage;
8060         int                     i_typstorage;
8061         int                     i_attnotnull;
8062         int                     i_atthasdef;
8063         int                     i_attidentity;
8064         int                     i_attisdropped;
8065         int                     i_attlen;
8066         int                     i_attalign;
8067         int                     i_attislocal;
8068         int                     i_attoptions;
8069         int                     i_attcollation;
8070         int                     i_attfdwoptions;
8071         PGresult   *res;
8072         int                     ntups;
8073         bool            hasdefaults;
8074
8075         for (i = 0; i < numTables; i++)
8076         {
8077                 TableInfo  *tbinfo = &tblinfo[i];
8078
8079                 /* Don't bother to collect info for sequences */
8080                 if (tbinfo->relkind == RELKIND_SEQUENCE)
8081                         continue;
8082
8083                 /* Don't bother with uninteresting tables, either */
8084                 if (!tbinfo->interesting)
8085                         continue;
8086
8087                 /* find all the user attributes and their types */
8088
8089                 /*
8090                  * we must read the attribute names in attribute number order! because
8091                  * we will use the attnum to index into the attnames array later.
8092                  */
8093                 if (g_verbose)
8094                         write_msg(NULL, "finding the columns and types of table \"%s.%s\"\n",
8095                                           tbinfo->dobj.namespace->dobj.name,
8096                                           tbinfo->dobj.name);
8097
8098                 resetPQExpBuffer(q);
8099
8100                 if (fout->remoteVersion >= 100000)
8101                 {
8102                         /*
8103                          * attidentity is new in version 10.
8104                          */
8105                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8106                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8107                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8108                                                           "a.attlen, a.attalign, a.attislocal, "
8109                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8110                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
8111                                                           "CASE WHEN a.attcollation <> t.typcollation "
8112                                                           "THEN a.attcollation ELSE 0 END AS attcollation, "
8113                                                           "a.attidentity, "
8114                                                           "pg_catalog.array_to_string(ARRAY("
8115                                                           "SELECT pg_catalog.quote_ident(option_name) || "
8116                                                           "' ' || pg_catalog.quote_literal(option_value) "
8117                                                           "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8118                                                           "ORDER BY option_name"
8119                                                           "), E',\n    ') AS attfdwoptions "
8120                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8121                                                           "ON a.atttypid = t.oid "
8122                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8123                                                           "AND a.attnum > 0::pg_catalog.int2 "
8124                                                           "ORDER BY a.attnum",
8125                                                           tbinfo->dobj.catId.oid);
8126                 }
8127                 else if (fout->remoteVersion >= 90200)
8128                 {
8129                         /*
8130                          * attfdwoptions is new in 9.2.
8131                          */
8132                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8133                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8134                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8135                                                           "a.attlen, a.attalign, a.attislocal, "
8136                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8137                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
8138                                                           "CASE WHEN a.attcollation <> t.typcollation "
8139                                                           "THEN a.attcollation ELSE 0 END AS attcollation, "
8140                                                           "pg_catalog.array_to_string(ARRAY("
8141                                                           "SELECT pg_catalog.quote_ident(option_name) || "
8142                                                           "' ' || pg_catalog.quote_literal(option_value) "
8143                                                           "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8144                                                           "ORDER BY option_name"
8145                                                           "), E',\n    ') AS attfdwoptions "
8146                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8147                                                           "ON a.atttypid = t.oid "
8148                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8149                                                           "AND a.attnum > 0::pg_catalog.int2 "
8150                                                           "ORDER BY a.attnum",
8151                                                           tbinfo->dobj.catId.oid);
8152                 }
8153                 else if (fout->remoteVersion >= 90100)
8154                 {
8155                         /*
8156                          * attcollation is new in 9.1.  Since we only want to dump COLLATE
8157                          * clauses for attributes whose collation is different from their
8158                          * type's default, we use a CASE here to suppress uninteresting
8159                          * attcollations cheaply.
8160                          */
8161                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8162                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8163                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8164                                                           "a.attlen, a.attalign, a.attislocal, "
8165                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8166                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
8167                                                           "CASE WHEN a.attcollation <> t.typcollation "
8168                                                           "THEN a.attcollation ELSE 0 END AS attcollation, "
8169                                                           "NULL AS attfdwoptions "
8170                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8171                                                           "ON a.atttypid = t.oid "
8172                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8173                                                           "AND a.attnum > 0::pg_catalog.int2 "
8174                                                           "ORDER BY a.attnum",
8175                                                           tbinfo->dobj.catId.oid);
8176                 }
8177                 else if (fout->remoteVersion >= 90000)
8178                 {
8179                         /* attoptions is new in 9.0 */
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                                                           "0 AS attcollation, "
8187                                                           "NULL AS attfdwoptions "
8188                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8189                                                           "ON a.atttypid = t.oid "
8190                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8191                                                           "AND a.attnum > 0::pg_catalog.int2 "
8192                                                           "ORDER BY a.attnum",
8193                                                           tbinfo->dobj.catId.oid);
8194                 }
8195                 else
8196                 {
8197                         /* need left join here to not fail on dropped columns ... */
8198                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8199                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8200                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8201                                                           "a.attlen, a.attalign, a.attislocal, "
8202                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8203                                                           "'' AS attoptions, 0 AS attcollation, "
8204                                                           "NULL AS attfdwoptions "
8205                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8206                                                           "ON a.atttypid = t.oid "
8207                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8208                                                           "AND a.attnum > 0::pg_catalog.int2 "
8209                                                           "ORDER BY a.attnum",
8210                                                           tbinfo->dobj.catId.oid);
8211                 }
8212
8213                 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8214
8215                 ntups = PQntuples(res);
8216
8217                 i_attnum = PQfnumber(res, "attnum");
8218                 i_attname = PQfnumber(res, "attname");
8219                 i_atttypname = PQfnumber(res, "atttypname");
8220                 i_atttypmod = PQfnumber(res, "atttypmod");
8221                 i_attstattarget = PQfnumber(res, "attstattarget");
8222                 i_attstorage = PQfnumber(res, "attstorage");
8223                 i_typstorage = PQfnumber(res, "typstorage");
8224                 i_attnotnull = PQfnumber(res, "attnotnull");
8225                 i_atthasdef = PQfnumber(res, "atthasdef");
8226                 i_attidentity = PQfnumber(res, "attidentity");
8227                 i_attisdropped = PQfnumber(res, "attisdropped");
8228                 i_attlen = PQfnumber(res, "attlen");
8229                 i_attalign = PQfnumber(res, "attalign");
8230                 i_attislocal = PQfnumber(res, "attislocal");
8231                 i_attoptions = PQfnumber(res, "attoptions");
8232                 i_attcollation = PQfnumber(res, "attcollation");
8233                 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
8234
8235                 tbinfo->numatts = ntups;
8236                 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
8237                 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
8238                 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
8239                 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
8240                 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
8241                 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
8242                 tbinfo->attidentity = (char *) pg_malloc(ntups * sizeof(char));
8243                 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
8244                 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
8245                 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
8246                 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
8247                 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
8248                 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
8249                 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
8250                 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
8251                 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
8252                 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
8253                 hasdefaults = false;
8254
8255                 for (j = 0; j < ntups; j++)
8256                 {
8257                         if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
8258                                 exit_horribly(NULL,
8259                                                           "invalid column numbering in table \"%s\"\n",
8260                                                           tbinfo->dobj.name);
8261                         tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
8262                         tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
8263                         tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
8264                         tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
8265                         tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
8266                         tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
8267                         tbinfo->attidentity[j] = (i_attidentity >= 0 ? *(PQgetvalue(res, j, i_attidentity)) : '\0');
8268                         tbinfo->needs_override = tbinfo->needs_override || (tbinfo->attidentity[j] == ATTRIBUTE_IDENTITY_ALWAYS);
8269                         tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
8270                         tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
8271                         tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
8272                         tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
8273                         tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
8274                         tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
8275                         tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
8276                         tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
8277                         tbinfo->attrdefs[j] = NULL; /* fix below */
8278                         if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
8279                                 hasdefaults = true;
8280                         /* these flags will be set in flagInhAttrs() */
8281                         tbinfo->inhNotNull[j] = false;
8282                 }
8283
8284                 PQclear(res);
8285
8286                 /*
8287                  * Get info about column defaults
8288                  */
8289                 if (hasdefaults)
8290                 {
8291                         AttrDefInfo *attrdefs;
8292                         int                     numDefaults;
8293
8294                         if (g_verbose)
8295                                 write_msg(NULL, "finding default expressions of table \"%s.%s\"\n",
8296                                                   tbinfo->dobj.namespace->dobj.name,
8297                                                   tbinfo->dobj.name);
8298
8299                         printfPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
8300                                                           "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
8301                                                           "FROM pg_catalog.pg_attrdef "
8302                                                           "WHERE adrelid = '%u'::pg_catalog.oid",
8303                                                           tbinfo->dobj.catId.oid);
8304
8305                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8306
8307                         numDefaults = PQntuples(res);
8308                         attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
8309
8310                         for (j = 0; j < numDefaults; j++)
8311                         {
8312                                 int                     adnum;
8313
8314                                 adnum = atoi(PQgetvalue(res, j, 2));
8315
8316                                 if (adnum <= 0 || adnum > ntups)
8317                                         exit_horribly(NULL,
8318                                                                   "invalid adnum value %d for table \"%s\"\n",
8319                                                                   adnum, tbinfo->dobj.name);
8320
8321                                 /*
8322                                  * dropped columns shouldn't have defaults, but just in case,
8323                                  * ignore 'em
8324                                  */
8325                                 if (tbinfo->attisdropped[adnum - 1])
8326                                         continue;
8327
8328                                 attrdefs[j].dobj.objType = DO_ATTRDEF;
8329                                 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8330                                 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8331                                 AssignDumpId(&attrdefs[j].dobj);
8332                                 attrdefs[j].adtable = tbinfo;
8333                                 attrdefs[j].adnum = adnum;
8334                                 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
8335
8336                                 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
8337                                 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
8338
8339                                 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
8340
8341                                 /*
8342                                  * Defaults on a VIEW must always be dumped as separate ALTER
8343                                  * TABLE commands.  Defaults on regular tables are dumped as
8344                                  * part of the CREATE TABLE if possible, which it won't be if
8345                                  * the column is not going to be emitted explicitly.
8346                                  */
8347                                 if (tbinfo->relkind == RELKIND_VIEW)
8348                                 {
8349                                         attrdefs[j].separate = true;
8350                                 }
8351                                 else if (!shouldPrintColumn(dopt, tbinfo, adnum - 1))
8352                                 {
8353                                         /* column will be suppressed, print default separately */
8354                                         attrdefs[j].separate = true;
8355                                 }
8356                                 else
8357                                 {
8358                                         attrdefs[j].separate = false;
8359
8360                                         /*
8361                                          * Mark the default as needing to appear before the table,
8362                                          * so that any dependencies it has must be emitted before
8363                                          * the CREATE TABLE.  If this is not possible, we'll
8364                                          * change to "separate" mode while sorting dependencies.
8365                                          */
8366                                         addObjectDependency(&tbinfo->dobj,
8367                                                                                 attrdefs[j].dobj.dumpId);
8368                                 }
8369
8370                                 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
8371                         }
8372                         PQclear(res);
8373                 }
8374
8375                 /*
8376                  * Get info about table CHECK constraints
8377                  */
8378                 if (tbinfo->ncheck > 0)
8379                 {
8380                         ConstraintInfo *constrs;
8381                         int                     numConstrs;
8382
8383                         if (g_verbose)
8384                                 write_msg(NULL, "finding check constraints for table \"%s.%s\"\n",
8385                                                   tbinfo->dobj.namespace->dobj.name,
8386                                                   tbinfo->dobj.name);
8387
8388                         resetPQExpBuffer(q);
8389                         if (fout->remoteVersion >= 90200)
8390                         {
8391                                 /*
8392                                  * convalidated is new in 9.2 (actually, it is there in 9.1,
8393                                  * but it wasn't ever false for check constraints until 9.2).
8394                                  */
8395                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8396                                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8397                                                                   "conislocal, convalidated "
8398                                                                   "FROM pg_catalog.pg_constraint "
8399                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
8400                                                                   "   AND contype = 'c' "
8401                                                                   "ORDER BY conname",
8402                                                                   tbinfo->dobj.catId.oid);
8403                         }
8404                         else if (fout->remoteVersion >= 80400)
8405                         {
8406                                 /* conislocal is new in 8.4 */
8407                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8408                                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8409                                                                   "conislocal, true AS convalidated "
8410                                                                   "FROM pg_catalog.pg_constraint "
8411                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
8412                                                                   "   AND contype = 'c' "
8413                                                                   "ORDER BY conname",
8414                                                                   tbinfo->dobj.catId.oid);
8415                         }
8416                         else
8417                         {
8418                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8419                                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8420                                                                   "true AS conislocal, true AS convalidated "
8421                                                                   "FROM pg_catalog.pg_constraint "
8422                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
8423                                                                   "   AND contype = 'c' "
8424                                                                   "ORDER BY conname",
8425                                                                   tbinfo->dobj.catId.oid);
8426                         }
8427
8428                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8429
8430                         numConstrs = PQntuples(res);
8431                         if (numConstrs != tbinfo->ncheck)
8432                         {
8433                                 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
8434                                                                                  "expected %d check constraints on table \"%s\" but found %d\n",
8435                                                                                  tbinfo->ncheck),
8436                                                   tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
8437                                 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
8438                                 exit_nicely(1);
8439                         }
8440
8441                         constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
8442                         tbinfo->checkexprs = constrs;
8443
8444                         for (j = 0; j < numConstrs; j++)
8445                         {
8446                                 bool            validated = PQgetvalue(res, j, 5)[0] == 't';
8447
8448                                 constrs[j].dobj.objType = DO_CONSTRAINT;
8449                                 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8450                                 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8451                                 AssignDumpId(&constrs[j].dobj);
8452                                 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
8453                                 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
8454                                 constrs[j].contable = tbinfo;
8455                                 constrs[j].condomain = NULL;
8456                                 constrs[j].contype = 'c';
8457                                 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
8458                                 constrs[j].confrelid = InvalidOid;
8459                                 constrs[j].conindex = 0;
8460                                 constrs[j].condeferrable = false;
8461                                 constrs[j].condeferred = false;
8462                                 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
8463
8464                                 /*
8465                                  * An unvalidated constraint needs to be dumped separately, so
8466                                  * that potentially-violating existing data is loaded before
8467                                  * the constraint.
8468                                  */
8469                                 constrs[j].separate = !validated;
8470
8471                                 constrs[j].dobj.dump = tbinfo->dobj.dump;
8472
8473                                 /*
8474                                  * Mark the constraint as needing to appear before the table
8475                                  * --- this is so that any other dependencies of the
8476                                  * constraint will be emitted before we try to create the
8477                                  * table.  If the constraint is to be dumped separately, it
8478                                  * will be dumped after data is loaded anyway, so don't do it.
8479                                  * (There's an automatic dependency in the opposite direction
8480                                  * anyway, so don't need to add one manually here.)
8481                                  */
8482                                 if (!constrs[j].separate)
8483                                         addObjectDependency(&tbinfo->dobj,
8484                                                                                 constrs[j].dobj.dumpId);
8485
8486                                 /*
8487                                  * If the constraint is inherited, this will be detected later
8488                                  * (in pre-8.4 databases).  We also detect later if the
8489                                  * constraint must be split out from the table definition.
8490                                  */
8491                         }
8492                         PQclear(res);
8493                 }
8494         }
8495
8496         destroyPQExpBuffer(q);
8497 }
8498
8499 /*
8500  * Test whether a column should be printed as part of table's CREATE TABLE.
8501  * Column number is zero-based.
8502  *
8503  * Normally this is always true, but it's false for dropped columns, as well
8504  * as those that were inherited without any local definition.  (If we print
8505  * such a column it will mistakenly get pg_attribute.attislocal set to true.)
8506  * However, in binary_upgrade mode, we must print all such columns anyway and
8507  * fix the attislocal/attisdropped state later, so as to keep control of the
8508  * physical column order.
8509  *
8510  * This function exists because there are scattered nonobvious places that
8511  * must be kept in sync with this decision.
8512  */
8513 bool
8514 shouldPrintColumn(DumpOptions *dopt, TableInfo *tbinfo, int colno)
8515 {
8516         if (dopt->binary_upgrade)
8517                 return true;
8518         return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
8519 }
8520
8521
8522 /*
8523  * getTSParsers:
8524  *        read all text search parsers in the system catalogs and return them
8525  *        in the TSParserInfo* structure
8526  *
8527  *      numTSParsers is set to the number of parsers read in
8528  */
8529 TSParserInfo *
8530 getTSParsers(Archive *fout, int *numTSParsers)
8531 {
8532         PGresult   *res;
8533         int                     ntups;
8534         int                     i;
8535         PQExpBuffer query;
8536         TSParserInfo *prsinfo;
8537         int                     i_tableoid;
8538         int                     i_oid;
8539         int                     i_prsname;
8540         int                     i_prsnamespace;
8541         int                     i_prsstart;
8542         int                     i_prstoken;
8543         int                     i_prsend;
8544         int                     i_prsheadline;
8545         int                     i_prslextype;
8546
8547         /* Before 8.3, there is no built-in text search support */
8548         if (fout->remoteVersion < 80300)
8549         {
8550                 *numTSParsers = 0;
8551                 return NULL;
8552         }
8553
8554         query = createPQExpBuffer();
8555
8556         /*
8557          * find all text search objects, including builtin ones; we filter out
8558          * system-defined objects at dump-out time.
8559          */
8560
8561         appendPQExpBufferStr(query, "SELECT tableoid, oid, prsname, prsnamespace, "
8562                                                  "prsstart::oid, prstoken::oid, "
8563                                                  "prsend::oid, prsheadline::oid, prslextype::oid "
8564                                                  "FROM pg_ts_parser");
8565
8566         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8567
8568         ntups = PQntuples(res);
8569         *numTSParsers = ntups;
8570
8571         prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
8572
8573         i_tableoid = PQfnumber(res, "tableoid");
8574         i_oid = PQfnumber(res, "oid");
8575         i_prsname = PQfnumber(res, "prsname");
8576         i_prsnamespace = PQfnumber(res, "prsnamespace");
8577         i_prsstart = PQfnumber(res, "prsstart");
8578         i_prstoken = PQfnumber(res, "prstoken");
8579         i_prsend = PQfnumber(res, "prsend");
8580         i_prsheadline = PQfnumber(res, "prsheadline");
8581         i_prslextype = PQfnumber(res, "prslextype");
8582
8583         for (i = 0; i < ntups; i++)
8584         {
8585                 prsinfo[i].dobj.objType = DO_TSPARSER;
8586                 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8587                 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8588                 AssignDumpId(&prsinfo[i].dobj);
8589                 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
8590                 prsinfo[i].dobj.namespace =
8591                         findNamespace(fout,
8592                                                   atooid(PQgetvalue(res, i, i_prsnamespace)));
8593                 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
8594                 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
8595                 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
8596                 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
8597                 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
8598
8599                 /* Decide whether we want to dump it */
8600                 selectDumpableObject(&(prsinfo[i].dobj), fout);
8601
8602                 /* Text Search Parsers do not currently have ACLs. */
8603                 prsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8604         }
8605
8606         PQclear(res);
8607
8608         destroyPQExpBuffer(query);
8609
8610         return prsinfo;
8611 }
8612
8613 /*
8614  * getTSDictionaries:
8615  *        read all text search dictionaries in the system catalogs and return them
8616  *        in the TSDictInfo* structure
8617  *
8618  *      numTSDicts is set to the number of dictionaries read in
8619  */
8620 TSDictInfo *
8621 getTSDictionaries(Archive *fout, int *numTSDicts)
8622 {
8623         PGresult   *res;
8624         int                     ntups;
8625         int                     i;
8626         PQExpBuffer query;
8627         TSDictInfo *dictinfo;
8628         int                     i_tableoid;
8629         int                     i_oid;
8630         int                     i_dictname;
8631         int                     i_dictnamespace;
8632         int                     i_rolname;
8633         int                     i_dicttemplate;
8634         int                     i_dictinitoption;
8635
8636         /* Before 8.3, there is no built-in text search support */
8637         if (fout->remoteVersion < 80300)
8638         {
8639                 *numTSDicts = 0;
8640                 return NULL;
8641         }
8642
8643         query = createPQExpBuffer();
8644
8645         appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
8646                                           "dictnamespace, (%s dictowner) AS rolname, "
8647                                           "dicttemplate, dictinitoption "
8648                                           "FROM pg_ts_dict",
8649                                           username_subquery);
8650
8651         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8652
8653         ntups = PQntuples(res);
8654         *numTSDicts = ntups;
8655
8656         dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
8657
8658         i_tableoid = PQfnumber(res, "tableoid");
8659         i_oid = PQfnumber(res, "oid");
8660         i_dictname = PQfnumber(res, "dictname");
8661         i_dictnamespace = PQfnumber(res, "dictnamespace");
8662         i_rolname = PQfnumber(res, "rolname");
8663         i_dictinitoption = PQfnumber(res, "dictinitoption");
8664         i_dicttemplate = PQfnumber(res, "dicttemplate");
8665
8666         for (i = 0; i < ntups; i++)
8667         {
8668                 dictinfo[i].dobj.objType = DO_TSDICT;
8669                 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8670                 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8671                 AssignDumpId(&dictinfo[i].dobj);
8672                 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
8673                 dictinfo[i].dobj.namespace =
8674                         findNamespace(fout,
8675                                                   atooid(PQgetvalue(res, i, i_dictnamespace)));
8676                 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8677                 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
8678                 if (PQgetisnull(res, i, i_dictinitoption))
8679                         dictinfo[i].dictinitoption = NULL;
8680                 else
8681                         dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
8682
8683                 /* Decide whether we want to dump it */
8684                 selectDumpableObject(&(dictinfo[i].dobj), fout);
8685
8686                 /* Text Search Dictionaries do not currently have ACLs. */
8687                 dictinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8688         }
8689
8690         PQclear(res);
8691
8692         destroyPQExpBuffer(query);
8693
8694         return dictinfo;
8695 }
8696
8697 /*
8698  * getTSTemplates:
8699  *        read all text search templates in the system catalogs and return them
8700  *        in the TSTemplateInfo* structure
8701  *
8702  *      numTSTemplates is set to the number of templates read in
8703  */
8704 TSTemplateInfo *
8705 getTSTemplates(Archive *fout, int *numTSTemplates)
8706 {
8707         PGresult   *res;
8708         int                     ntups;
8709         int                     i;
8710         PQExpBuffer query;
8711         TSTemplateInfo *tmplinfo;
8712         int                     i_tableoid;
8713         int                     i_oid;
8714         int                     i_tmplname;
8715         int                     i_tmplnamespace;
8716         int                     i_tmplinit;
8717         int                     i_tmpllexize;
8718
8719         /* Before 8.3, there is no built-in text search support */
8720         if (fout->remoteVersion < 80300)
8721         {
8722                 *numTSTemplates = 0;
8723                 return NULL;
8724         }
8725
8726         query = createPQExpBuffer();
8727
8728         appendPQExpBufferStr(query, "SELECT tableoid, oid, tmplname, "
8729                                                  "tmplnamespace, tmplinit::oid, tmpllexize::oid "
8730                                                  "FROM pg_ts_template");
8731
8732         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8733
8734         ntups = PQntuples(res);
8735         *numTSTemplates = ntups;
8736
8737         tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
8738
8739         i_tableoid = PQfnumber(res, "tableoid");
8740         i_oid = PQfnumber(res, "oid");
8741         i_tmplname = PQfnumber(res, "tmplname");
8742         i_tmplnamespace = PQfnumber(res, "tmplnamespace");
8743         i_tmplinit = PQfnumber(res, "tmplinit");
8744         i_tmpllexize = PQfnumber(res, "tmpllexize");
8745
8746         for (i = 0; i < ntups; i++)
8747         {
8748                 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
8749                 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8750                 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8751                 AssignDumpId(&tmplinfo[i].dobj);
8752                 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
8753                 tmplinfo[i].dobj.namespace =
8754                         findNamespace(fout,
8755                                                   atooid(PQgetvalue(res, i, i_tmplnamespace)));
8756                 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
8757                 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
8758
8759                 /* Decide whether we want to dump it */
8760                 selectDumpableObject(&(tmplinfo[i].dobj), fout);
8761
8762                 /* Text Search Templates do not currently have ACLs. */
8763                 tmplinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8764         }
8765
8766         PQclear(res);
8767
8768         destroyPQExpBuffer(query);
8769
8770         return tmplinfo;
8771 }
8772
8773 /*
8774  * getTSConfigurations:
8775  *        read all text search configurations in the system catalogs and return
8776  *        them in the TSConfigInfo* structure
8777  *
8778  *      numTSConfigs is set to the number of configurations read in
8779  */
8780 TSConfigInfo *
8781 getTSConfigurations(Archive *fout, int *numTSConfigs)
8782 {
8783         PGresult   *res;
8784         int                     ntups;
8785         int                     i;
8786         PQExpBuffer query;
8787         TSConfigInfo *cfginfo;
8788         int                     i_tableoid;
8789         int                     i_oid;
8790         int                     i_cfgname;
8791         int                     i_cfgnamespace;
8792         int                     i_rolname;
8793         int                     i_cfgparser;
8794
8795         /* Before 8.3, there is no built-in text search support */
8796         if (fout->remoteVersion < 80300)
8797         {
8798                 *numTSConfigs = 0;
8799                 return NULL;
8800         }
8801
8802         query = createPQExpBuffer();
8803
8804         appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
8805                                           "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
8806                                           "FROM pg_ts_config",
8807                                           username_subquery);
8808
8809         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8810
8811         ntups = PQntuples(res);
8812         *numTSConfigs = ntups;
8813
8814         cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
8815
8816         i_tableoid = PQfnumber(res, "tableoid");
8817         i_oid = PQfnumber(res, "oid");
8818         i_cfgname = PQfnumber(res, "cfgname");
8819         i_cfgnamespace = PQfnumber(res, "cfgnamespace");
8820         i_rolname = PQfnumber(res, "rolname");
8821         i_cfgparser = PQfnumber(res, "cfgparser");
8822
8823         for (i = 0; i < ntups; i++)
8824         {
8825                 cfginfo[i].dobj.objType = DO_TSCONFIG;
8826                 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8827                 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8828                 AssignDumpId(&cfginfo[i].dobj);
8829                 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
8830                 cfginfo[i].dobj.namespace =
8831                         findNamespace(fout,
8832                                                   atooid(PQgetvalue(res, i, i_cfgnamespace)));
8833                 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8834                 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
8835
8836                 /* Decide whether we want to dump it */
8837                 selectDumpableObject(&(cfginfo[i].dobj), fout);
8838
8839                 /* Text Search Configurations do not currently have ACLs. */
8840                 cfginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8841         }
8842
8843         PQclear(res);
8844
8845         destroyPQExpBuffer(query);
8846
8847         return cfginfo;
8848 }
8849
8850 /*
8851  * getForeignDataWrappers:
8852  *        read all foreign-data wrappers in the system catalogs and return
8853  *        them in the FdwInfo* structure
8854  *
8855  *      numForeignDataWrappers is set to the number of fdws read in
8856  */
8857 FdwInfo *
8858 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
8859 {
8860         DumpOptions *dopt = fout->dopt;
8861         PGresult   *res;
8862         int                     ntups;
8863         int                     i;
8864         PQExpBuffer query;
8865         FdwInfo    *fdwinfo;
8866         int                     i_tableoid;
8867         int                     i_oid;
8868         int                     i_fdwname;
8869         int                     i_rolname;
8870         int                     i_fdwhandler;
8871         int                     i_fdwvalidator;
8872         int                     i_fdwacl;
8873         int                     i_rfdwacl;
8874         int                     i_initfdwacl;
8875         int                     i_initrfdwacl;
8876         int                     i_fdwoptions;
8877
8878         /* Before 8.4, there are no foreign-data wrappers */
8879         if (fout->remoteVersion < 80400)
8880         {
8881                 *numForeignDataWrappers = 0;
8882                 return NULL;
8883         }
8884
8885         query = createPQExpBuffer();
8886
8887         if (fout->remoteVersion >= 90600)
8888         {
8889                 PQExpBuffer acl_subquery = createPQExpBuffer();
8890                 PQExpBuffer racl_subquery = createPQExpBuffer();
8891                 PQExpBuffer initacl_subquery = createPQExpBuffer();
8892                 PQExpBuffer initracl_subquery = createPQExpBuffer();
8893
8894                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
8895                                                 initracl_subquery, "f.fdwacl", "f.fdwowner", "'F'",
8896                                                 dopt->binary_upgrade);
8897
8898                 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.fdwname, "
8899                                                   "(%s f.fdwowner) AS rolname, "
8900                                                   "f.fdwhandler::pg_catalog.regproc, "
8901                                                   "f.fdwvalidator::pg_catalog.regproc, "
8902                                                   "%s AS fdwacl, "
8903                                                   "%s AS rfdwacl, "
8904                                                   "%s AS initfdwacl, "
8905                                                   "%s AS initrfdwacl, "
8906                                                   "array_to_string(ARRAY("
8907                                                   "SELECT quote_ident(option_name) || ' ' || "
8908                                                   "quote_literal(option_value) "
8909                                                   "FROM pg_options_to_table(f.fdwoptions) "
8910                                                   "ORDER BY option_name"
8911                                                   "), E',\n    ') AS fdwoptions "
8912                                                   "FROM pg_foreign_data_wrapper f "
8913                                                   "LEFT JOIN pg_init_privs pip ON "
8914                                                   "(f.oid = pip.objoid "
8915                                                   "AND pip.classoid = 'pg_foreign_data_wrapper'::regclass "
8916                                                   "AND pip.objsubid = 0) ",
8917                                                   username_subquery,
8918                                                   acl_subquery->data,
8919                                                   racl_subquery->data,
8920                                                   initacl_subquery->data,
8921                                                   initracl_subquery->data);
8922
8923                 destroyPQExpBuffer(acl_subquery);
8924                 destroyPQExpBuffer(racl_subquery);
8925                 destroyPQExpBuffer(initacl_subquery);
8926                 destroyPQExpBuffer(initracl_subquery);
8927         }
8928         else if (fout->remoteVersion >= 90100)
8929         {
8930                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
8931                                                   "(%s fdwowner) AS rolname, "
8932                                                   "fdwhandler::pg_catalog.regproc, "
8933                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
8934                                                   "NULL as rfdwacl, "
8935                                                   "NULL as initfdwacl, NULL AS initrfdwacl, "
8936                                                   "array_to_string(ARRAY("
8937                                                   "SELECT quote_ident(option_name) || ' ' || "
8938                                                   "quote_literal(option_value) "
8939                                                   "FROM pg_options_to_table(fdwoptions) "
8940                                                   "ORDER BY option_name"
8941                                                   "), E',\n    ') AS fdwoptions "
8942                                                   "FROM pg_foreign_data_wrapper",
8943                                                   username_subquery);
8944         }
8945         else
8946         {
8947                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
8948                                                   "(%s fdwowner) AS rolname, "
8949                                                   "'-' AS fdwhandler, "
8950                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
8951                                                   "NULL as rfdwacl, "
8952                                                   "NULL as initfdwacl, NULL AS initrfdwacl, "
8953                                                   "array_to_string(ARRAY("
8954                                                   "SELECT quote_ident(option_name) || ' ' || "
8955                                                   "quote_literal(option_value) "
8956                                                   "FROM pg_options_to_table(fdwoptions) "
8957                                                   "ORDER BY option_name"
8958                                                   "), E',\n    ') AS fdwoptions "
8959                                                   "FROM pg_foreign_data_wrapper",
8960                                                   username_subquery);
8961         }
8962
8963         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8964
8965         ntups = PQntuples(res);
8966         *numForeignDataWrappers = ntups;
8967
8968         fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
8969
8970         i_tableoid = PQfnumber(res, "tableoid");
8971         i_oid = PQfnumber(res, "oid");
8972         i_fdwname = PQfnumber(res, "fdwname");
8973         i_rolname = PQfnumber(res, "rolname");
8974         i_fdwhandler = PQfnumber(res, "fdwhandler");
8975         i_fdwvalidator = PQfnumber(res, "fdwvalidator");
8976         i_fdwacl = PQfnumber(res, "fdwacl");
8977         i_rfdwacl = PQfnumber(res, "rfdwacl");
8978         i_initfdwacl = PQfnumber(res, "initfdwacl");
8979         i_initrfdwacl = PQfnumber(res, "initrfdwacl");
8980         i_fdwoptions = PQfnumber(res, "fdwoptions");
8981
8982         for (i = 0; i < ntups; i++)
8983         {
8984                 fdwinfo[i].dobj.objType = DO_FDW;
8985                 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8986                 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8987                 AssignDumpId(&fdwinfo[i].dobj);
8988                 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
8989                 fdwinfo[i].dobj.namespace = NULL;
8990                 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8991                 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
8992                 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
8993                 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
8994                 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
8995                 fdwinfo[i].rfdwacl = pg_strdup(PQgetvalue(res, i, i_rfdwacl));
8996                 fdwinfo[i].initfdwacl = pg_strdup(PQgetvalue(res, i, i_initfdwacl));
8997                 fdwinfo[i].initrfdwacl = pg_strdup(PQgetvalue(res, i, i_initrfdwacl));
8998
8999                 /* Decide whether we want to dump it */
9000                 selectDumpableObject(&(fdwinfo[i].dobj), fout);
9001
9002                 /* Do not try to dump ACL if no ACL exists. */
9003                 if (PQgetisnull(res, i, i_fdwacl) && PQgetisnull(res, i, i_rfdwacl) &&
9004                         PQgetisnull(res, i, i_initfdwacl) &&
9005                         PQgetisnull(res, i, i_initrfdwacl))
9006                         fdwinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9007         }
9008
9009         PQclear(res);
9010
9011         destroyPQExpBuffer(query);
9012
9013         return fdwinfo;
9014 }
9015
9016 /*
9017  * getForeignServers:
9018  *        read all foreign servers in the system catalogs and return
9019  *        them in the ForeignServerInfo * structure
9020  *
9021  *      numForeignServers is set to the number of servers read in
9022  */
9023 ForeignServerInfo *
9024 getForeignServers(Archive *fout, int *numForeignServers)
9025 {
9026         DumpOptions *dopt = fout->dopt;
9027         PGresult   *res;
9028         int                     ntups;
9029         int                     i;
9030         PQExpBuffer query;
9031         ForeignServerInfo *srvinfo;
9032         int                     i_tableoid;
9033         int                     i_oid;
9034         int                     i_srvname;
9035         int                     i_rolname;
9036         int                     i_srvfdw;
9037         int                     i_srvtype;
9038         int                     i_srvversion;
9039         int                     i_srvacl;
9040         int                     i_rsrvacl;
9041         int                     i_initsrvacl;
9042         int                     i_initrsrvacl;
9043         int                     i_srvoptions;
9044
9045         /* Before 8.4, there are no foreign servers */
9046         if (fout->remoteVersion < 80400)
9047         {
9048                 *numForeignServers = 0;
9049                 return NULL;
9050         }
9051
9052         query = createPQExpBuffer();
9053
9054         if (fout->remoteVersion >= 90600)
9055         {
9056                 PQExpBuffer acl_subquery = createPQExpBuffer();
9057                 PQExpBuffer racl_subquery = createPQExpBuffer();
9058                 PQExpBuffer initacl_subquery = createPQExpBuffer();
9059                 PQExpBuffer initracl_subquery = createPQExpBuffer();
9060
9061                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9062                                                 initracl_subquery, "f.srvacl", "f.srvowner", "'S'",
9063                                                 dopt->binary_upgrade);
9064
9065                 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.srvname, "
9066                                                   "(%s f.srvowner) AS rolname, "
9067                                                   "f.srvfdw, f.srvtype, f.srvversion, "
9068                                                   "%s AS srvacl, "
9069                                                   "%s AS rsrvacl, "
9070                                                   "%s AS initsrvacl, "
9071                                                   "%s AS initrsrvacl, "
9072                                                   "array_to_string(ARRAY("
9073                                                   "SELECT quote_ident(option_name) || ' ' || "
9074                                                   "quote_literal(option_value) "
9075                                                   "FROM pg_options_to_table(f.srvoptions) "
9076                                                   "ORDER BY option_name"
9077                                                   "), E',\n    ') AS srvoptions "
9078                                                   "FROM pg_foreign_server f "
9079                                                   "LEFT JOIN pg_init_privs pip "
9080                                                   "ON (f.oid = pip.objoid "
9081                                                   "AND pip.classoid = 'pg_foreign_server'::regclass "
9082                                                   "AND pip.objsubid = 0) ",
9083                                                   username_subquery,
9084                                                   acl_subquery->data,
9085                                                   racl_subquery->data,
9086                                                   initacl_subquery->data,
9087                                                   initracl_subquery->data);
9088
9089                 destroyPQExpBuffer(acl_subquery);
9090                 destroyPQExpBuffer(racl_subquery);
9091                 destroyPQExpBuffer(initacl_subquery);
9092                 destroyPQExpBuffer(initracl_subquery);
9093         }
9094         else
9095         {
9096                 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
9097                                                   "(%s srvowner) AS rolname, "
9098                                                   "srvfdw, srvtype, srvversion, srvacl, "
9099                                                   "NULL AS rsrvacl, "
9100                                                   "NULL AS initsrvacl, NULL AS initrsrvacl, "
9101                                                   "array_to_string(ARRAY("
9102                                                   "SELECT quote_ident(option_name) || ' ' || "
9103                                                   "quote_literal(option_value) "
9104                                                   "FROM pg_options_to_table(srvoptions) "
9105                                                   "ORDER BY option_name"
9106                                                   "), E',\n    ') AS srvoptions "
9107                                                   "FROM pg_foreign_server",
9108                                                   username_subquery);
9109         }
9110
9111         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9112
9113         ntups = PQntuples(res);
9114         *numForeignServers = ntups;
9115
9116         srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
9117
9118         i_tableoid = PQfnumber(res, "tableoid");
9119         i_oid = PQfnumber(res, "oid");
9120         i_srvname = PQfnumber(res, "srvname");
9121         i_rolname = PQfnumber(res, "rolname");
9122         i_srvfdw = PQfnumber(res, "srvfdw");
9123         i_srvtype = PQfnumber(res, "srvtype");
9124         i_srvversion = PQfnumber(res, "srvversion");
9125         i_srvacl = PQfnumber(res, "srvacl");
9126         i_rsrvacl = PQfnumber(res, "rsrvacl");
9127         i_initsrvacl = PQfnumber(res, "initsrvacl");
9128         i_initrsrvacl = PQfnumber(res, "initrsrvacl");
9129         i_srvoptions = PQfnumber(res, "srvoptions");
9130
9131         for (i = 0; i < ntups; i++)
9132         {
9133                 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
9134                 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9135                 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9136                 AssignDumpId(&srvinfo[i].dobj);
9137                 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
9138                 srvinfo[i].dobj.namespace = NULL;
9139                 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
9140                 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
9141                 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
9142                 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
9143                 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
9144                 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
9145                 srvinfo[i].rsrvacl = pg_strdup(PQgetvalue(res, i, i_rsrvacl));
9146                 srvinfo[i].initsrvacl = pg_strdup(PQgetvalue(res, i, i_initsrvacl));
9147                 srvinfo[i].initrsrvacl = pg_strdup(PQgetvalue(res, i, i_initrsrvacl));
9148
9149                 /* Decide whether we want to dump it */
9150                 selectDumpableObject(&(srvinfo[i].dobj), fout);
9151
9152                 /* Do not try to dump ACL if no ACL exists. */
9153                 if (PQgetisnull(res, i, i_srvacl) && PQgetisnull(res, i, i_rsrvacl) &&
9154                         PQgetisnull(res, i, i_initsrvacl) &&
9155                         PQgetisnull(res, i, i_initrsrvacl))
9156                         srvinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9157         }
9158
9159         PQclear(res);
9160
9161         destroyPQExpBuffer(query);
9162
9163         return srvinfo;
9164 }
9165
9166 /*
9167  * getDefaultACLs:
9168  *        read all default ACL information in the system catalogs and return
9169  *        them in the DefaultACLInfo structure
9170  *
9171  *      numDefaultACLs is set to the number of ACLs read in
9172  */
9173 DefaultACLInfo *
9174 getDefaultACLs(Archive *fout, int *numDefaultACLs)
9175 {
9176         DumpOptions *dopt = fout->dopt;
9177         DefaultACLInfo *daclinfo;
9178         PQExpBuffer query;
9179         PGresult   *res;
9180         int                     i_oid;
9181         int                     i_tableoid;
9182         int                     i_defaclrole;
9183         int                     i_defaclnamespace;
9184         int                     i_defaclobjtype;
9185         int                     i_defaclacl;
9186         int                     i_rdefaclacl;
9187         int                     i_initdefaclacl;
9188         int                     i_initrdefaclacl;
9189         int                     i,
9190                                 ntups;
9191
9192         if (fout->remoteVersion < 90000)
9193         {
9194                 *numDefaultACLs = 0;
9195                 return NULL;
9196         }
9197
9198         query = createPQExpBuffer();
9199
9200         if (fout->remoteVersion >= 90600)
9201         {
9202                 PQExpBuffer acl_subquery = createPQExpBuffer();
9203                 PQExpBuffer racl_subquery = createPQExpBuffer();
9204                 PQExpBuffer initacl_subquery = createPQExpBuffer();
9205                 PQExpBuffer initracl_subquery = createPQExpBuffer();
9206
9207                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9208                                                 initracl_subquery, "defaclacl", "defaclrole",
9209                                                 "CASE WHEN defaclobjtype = 'S' THEN 's' ELSE defaclobjtype END::\"char\"",
9210                                                 dopt->binary_upgrade);
9211
9212                 appendPQExpBuffer(query, "SELECT d.oid, d.tableoid, "
9213                                                   "(%s d.defaclrole) AS defaclrole, "
9214                                                   "d.defaclnamespace, "
9215                                                   "d.defaclobjtype, "
9216                                                   "%s AS defaclacl, "
9217                                                   "%s AS rdefaclacl, "
9218                                                   "%s AS initdefaclacl, "
9219                                                   "%s AS initrdefaclacl "
9220                                                   "FROM pg_default_acl d "
9221                                                   "LEFT JOIN pg_init_privs pip ON "
9222                                                   "(d.oid = pip.objoid "
9223                                                   "AND pip.classoid = 'pg_default_acl'::regclass "
9224                                                   "AND pip.objsubid = 0) ",
9225                                                   username_subquery,
9226                                                   acl_subquery->data,
9227                                                   racl_subquery->data,
9228                                                   initacl_subquery->data,
9229                                                   initracl_subquery->data);
9230         }
9231         else
9232         {
9233                 appendPQExpBuffer(query, "SELECT oid, tableoid, "
9234                                                   "(%s defaclrole) AS defaclrole, "
9235                                                   "defaclnamespace, "
9236                                                   "defaclobjtype, "
9237                                                   "defaclacl, "
9238                                                   "NULL AS rdefaclacl, "
9239                                                   "NULL AS initdefaclacl, "
9240                                                   "NULL AS initrdefaclacl "
9241                                                   "FROM pg_default_acl",
9242                                                   username_subquery);
9243         }
9244
9245         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9246
9247         ntups = PQntuples(res);
9248         *numDefaultACLs = ntups;
9249
9250         daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
9251
9252         i_oid = PQfnumber(res, "oid");
9253         i_tableoid = PQfnumber(res, "tableoid");
9254         i_defaclrole = PQfnumber(res, "defaclrole");
9255         i_defaclnamespace = PQfnumber(res, "defaclnamespace");
9256         i_defaclobjtype = PQfnumber(res, "defaclobjtype");
9257         i_defaclacl = PQfnumber(res, "defaclacl");
9258         i_rdefaclacl = PQfnumber(res, "rdefaclacl");
9259         i_initdefaclacl = PQfnumber(res, "initdefaclacl");
9260         i_initrdefaclacl = PQfnumber(res, "initrdefaclacl");
9261
9262         for (i = 0; i < ntups; i++)
9263         {
9264                 Oid                     nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
9265
9266                 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
9267                 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9268                 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9269                 AssignDumpId(&daclinfo[i].dobj);
9270                 /* cheesy ... is it worth coming up with a better object name? */
9271                 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
9272
9273                 if (nspid != InvalidOid)
9274                         daclinfo[i].dobj.namespace = findNamespace(fout, nspid);
9275                 else
9276                         daclinfo[i].dobj.namespace = NULL;
9277
9278                 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
9279                 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
9280                 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
9281                 daclinfo[i].rdefaclacl = pg_strdup(PQgetvalue(res, i, i_rdefaclacl));
9282                 daclinfo[i].initdefaclacl = pg_strdup(PQgetvalue(res, i, i_initdefaclacl));
9283                 daclinfo[i].initrdefaclacl = pg_strdup(PQgetvalue(res, i, i_initrdefaclacl));
9284
9285                 /* Decide whether we want to dump it */
9286                 selectDumpableDefaultACL(&(daclinfo[i]), dopt);
9287         }
9288
9289         PQclear(res);
9290
9291         destroyPQExpBuffer(query);
9292
9293         return daclinfo;
9294 }
9295
9296 /*
9297  * dumpComment --
9298  *
9299  * This routine is used to dump any comments associated with the
9300  * object handed to this routine. The routine takes the object type
9301  * and object name (ready to print, except for schema decoration), plus
9302  * the namespace and owner of the object (for labeling the ArchiveEntry),
9303  * plus catalog ID and subid which are the lookup key for pg_description,
9304  * plus the dump ID for the object (for setting a dependency).
9305  * If a matching pg_description entry is found, it is dumped.
9306  *
9307  * Note: in some cases, such as comments for triggers and rules, the "type"
9308  * string really looks like, e.g., "TRIGGER name ON".  This is a bit of a hack
9309  * but it doesn't seem worth complicating the API for all callers to make
9310  * it cleaner.
9311  *
9312  * Note: although this routine takes a dumpId for dependency purposes,
9313  * that purpose is just to mark the dependency in the emitted dump file
9314  * for possible future use by pg_restore.  We do NOT use it for determining
9315  * ordering of the comment in the dump file, because this routine is called
9316  * after dependency sorting occurs.  This routine should be called just after
9317  * calling ArchiveEntry() for the specified object.
9318  */
9319 static void
9320 dumpComment(Archive *fout, const char *type, const char *name,
9321                         const char *namespace, const char *owner,
9322                         CatalogId catalogId, int subid, DumpId dumpId)
9323 {
9324         DumpOptions *dopt = fout->dopt;
9325         CommentItem *comments;
9326         int                     ncomments;
9327
9328         /* do nothing, if --no-comments is supplied */
9329         if (dopt->no_comments)
9330                 return;
9331
9332         /* Comments are schema not data ... except blob comments are data */
9333         if (strcmp(type, "LARGE OBJECT") != 0)
9334         {
9335                 if (dopt->dataOnly)
9336                         return;
9337         }
9338         else
9339         {
9340                 /* We do dump blob comments in binary-upgrade mode */
9341                 if (dopt->schemaOnly && !dopt->binary_upgrade)
9342                         return;
9343         }
9344
9345         /* Search for comments associated with catalogId, using table */
9346         ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
9347                                                          &comments);
9348
9349         /* Is there one matching the subid? */
9350         while (ncomments > 0)
9351         {
9352                 if (comments->objsubid == subid)
9353                         break;
9354                 comments++;
9355                 ncomments--;
9356         }
9357
9358         /* If a comment exists, build COMMENT ON statement */
9359         if (ncomments > 0)
9360         {
9361                 PQExpBuffer query = createPQExpBuffer();
9362                 PQExpBuffer tag = createPQExpBuffer();
9363
9364                 appendPQExpBuffer(query, "COMMENT ON %s ", type);
9365                 if (namespace && *namespace)
9366                         appendPQExpBuffer(query, "%s.", fmtId(namespace));
9367                 appendPQExpBuffer(query, "%s IS ", name);
9368                 appendStringLiteralAH(query, comments->descr, fout);
9369                 appendPQExpBufferStr(query, ";\n");
9370
9371                 appendPQExpBuffer(tag, "%s %s", type, name);
9372
9373                 /*
9374                  * We mark comments as SECTION_NONE because they really belong in the
9375                  * same section as their parent, whether that is pre-data or
9376                  * post-data.
9377                  */
9378                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9379                                          tag->data, namespace, NULL, owner,
9380                                          false, "COMMENT", SECTION_NONE,
9381                                          query->data, "", NULL,
9382                                          &(dumpId), 1,
9383                                          NULL, NULL);
9384
9385                 destroyPQExpBuffer(query);
9386                 destroyPQExpBuffer(tag);
9387         }
9388 }
9389
9390 /*
9391  * dumpTableComment --
9392  *
9393  * As above, but dump comments for both the specified table (or view)
9394  * and its columns.
9395  */
9396 static void
9397 dumpTableComment(Archive *fout, TableInfo *tbinfo,
9398                                  const char *reltypename)
9399 {
9400         DumpOptions *dopt = fout->dopt;
9401         CommentItem *comments;
9402         int                     ncomments;
9403         PQExpBuffer query;
9404         PQExpBuffer tag;
9405
9406         /* do nothing, if --no-comments is supplied */
9407         if (dopt->no_comments)
9408                 return;
9409
9410         /* Comments are SCHEMA not data */
9411         if (dopt->dataOnly)
9412                 return;
9413
9414         /* Search for comments associated with relation, using table */
9415         ncomments = findComments(fout,
9416                                                          tbinfo->dobj.catId.tableoid,
9417                                                          tbinfo->dobj.catId.oid,
9418                                                          &comments);
9419
9420         /* If comments exist, build COMMENT ON statements */
9421         if (ncomments <= 0)
9422                 return;
9423
9424         query = createPQExpBuffer();
9425         tag = createPQExpBuffer();
9426
9427         while (ncomments > 0)
9428         {
9429                 const char *descr = comments->descr;
9430                 int                     objsubid = comments->objsubid;
9431
9432                 if (objsubid == 0)
9433                 {
9434                         resetPQExpBuffer(tag);
9435                         appendPQExpBuffer(tag, "%s %s", reltypename,
9436                                                           fmtId(tbinfo->dobj.name));
9437
9438                         resetPQExpBuffer(query);
9439                         appendPQExpBuffer(query, "COMMENT ON %s %s IS ", reltypename,
9440                                                           fmtQualifiedDumpable(tbinfo));
9441                         appendStringLiteralAH(query, descr, fout);
9442                         appendPQExpBufferStr(query, ";\n");
9443
9444                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
9445                                                  tag->data,
9446                                                  tbinfo->dobj.namespace->dobj.name,
9447                                                  NULL, tbinfo->rolname,
9448                                                  false, "COMMENT", SECTION_NONE,
9449                                                  query->data, "", NULL,
9450                                                  &(tbinfo->dobj.dumpId), 1,
9451                                                  NULL, NULL);
9452                 }
9453                 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
9454                 {
9455                         resetPQExpBuffer(tag);
9456                         appendPQExpBuffer(tag, "COLUMN %s.",
9457                                                           fmtId(tbinfo->dobj.name));
9458                         appendPQExpBufferStr(tag, fmtId(tbinfo->attnames[objsubid - 1]));
9459
9460                         resetPQExpBuffer(query);
9461                         appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
9462                                                           fmtQualifiedDumpable(tbinfo));
9463                         appendPQExpBuffer(query, "%s IS ",
9464                                                           fmtId(tbinfo->attnames[objsubid - 1]));
9465                         appendStringLiteralAH(query, descr, fout);
9466                         appendPQExpBufferStr(query, ";\n");
9467
9468                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
9469                                                  tag->data,
9470                                                  tbinfo->dobj.namespace->dobj.name,
9471                                                  NULL, tbinfo->rolname,
9472                                                  false, "COMMENT", SECTION_NONE,
9473                                                  query->data, "", NULL,
9474                                                  &(tbinfo->dobj.dumpId), 1,
9475                                                  NULL, NULL);
9476                 }
9477
9478                 comments++;
9479                 ncomments--;
9480         }
9481
9482         destroyPQExpBuffer(query);
9483         destroyPQExpBuffer(tag);
9484 }
9485
9486 /*
9487  * findComments --
9488  *
9489  * Find the comment(s), if any, associated with the given object.  All the
9490  * objsubid values associated with the given classoid/objoid are found with
9491  * one search.
9492  */
9493 static int
9494 findComments(Archive *fout, Oid classoid, Oid objoid,
9495                          CommentItem **items)
9496 {
9497         /* static storage for table of comments */
9498         static CommentItem *comments = NULL;
9499         static int      ncomments = -1;
9500
9501         CommentItem *middle = NULL;
9502         CommentItem *low;
9503         CommentItem *high;
9504         int                     nmatch;
9505
9506         /* Get comments if we didn't already */
9507         if (ncomments < 0)
9508                 ncomments = collectComments(fout, &comments);
9509
9510         /*
9511          * Do binary search to find some item matching the object.
9512          */
9513         low = &comments[0];
9514         high = &comments[ncomments - 1];
9515         while (low <= high)
9516         {
9517                 middle = low + (high - low) / 2;
9518
9519                 if (classoid < middle->classoid)
9520                         high = middle - 1;
9521                 else if (classoid > middle->classoid)
9522                         low = middle + 1;
9523                 else if (objoid < middle->objoid)
9524                         high = middle - 1;
9525                 else if (objoid > middle->objoid)
9526                         low = middle + 1;
9527                 else
9528                         break;                          /* found a match */
9529         }
9530
9531         if (low > high)                         /* no matches */
9532         {
9533                 *items = NULL;
9534                 return 0;
9535         }
9536
9537         /*
9538          * Now determine how many items match the object.  The search loop
9539          * invariant still holds: only items between low and high inclusive could
9540          * match.
9541          */
9542         nmatch = 1;
9543         while (middle > low)
9544         {
9545                 if (classoid != middle[-1].classoid ||
9546                         objoid != middle[-1].objoid)
9547                         break;
9548                 middle--;
9549                 nmatch++;
9550         }
9551
9552         *items = middle;
9553
9554         middle += nmatch;
9555         while (middle <= high)
9556         {
9557                 if (classoid != middle->classoid ||
9558                         objoid != middle->objoid)
9559                         break;
9560                 middle++;
9561                 nmatch++;
9562         }
9563
9564         return nmatch;
9565 }
9566
9567 /*
9568  * collectComments --
9569  *
9570  * Construct a table of all comments available for database objects.
9571  * We used to do per-object queries for the comments, but it's much faster
9572  * to pull them all over at once, and on most databases the memory cost
9573  * isn't high.
9574  *
9575  * The table is sorted by classoid/objid/objsubid for speed in lookup.
9576  */
9577 static int
9578 collectComments(Archive *fout, CommentItem **items)
9579 {
9580         PGresult   *res;
9581         PQExpBuffer query;
9582         int                     i_description;
9583         int                     i_classoid;
9584         int                     i_objoid;
9585         int                     i_objsubid;
9586         int                     ntups;
9587         int                     i;
9588         CommentItem *comments;
9589
9590         query = createPQExpBuffer();
9591
9592         appendPQExpBufferStr(query, "SELECT description, classoid, objoid, objsubid "
9593                                                  "FROM pg_catalog.pg_description "
9594                                                  "ORDER BY classoid, objoid, objsubid");
9595
9596         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9597
9598         /* Construct lookup table containing OIDs in numeric form */
9599
9600         i_description = PQfnumber(res, "description");
9601         i_classoid = PQfnumber(res, "classoid");
9602         i_objoid = PQfnumber(res, "objoid");
9603         i_objsubid = PQfnumber(res, "objsubid");
9604
9605         ntups = PQntuples(res);
9606
9607         comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
9608
9609         for (i = 0; i < ntups; i++)
9610         {
9611                 comments[i].descr = PQgetvalue(res, i, i_description);
9612                 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
9613                 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
9614                 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
9615         }
9616
9617         /* Do NOT free the PGresult since we are keeping pointers into it */
9618         destroyPQExpBuffer(query);
9619
9620         *items = comments;
9621         return ntups;
9622 }
9623
9624 /*
9625  * dumpDumpableObject
9626  *
9627  * This routine and its subsidiaries are responsible for creating
9628  * ArchiveEntries (TOC objects) for each object to be dumped.
9629  */
9630 static void
9631 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
9632 {
9633         switch (dobj->objType)
9634         {
9635                 case DO_NAMESPACE:
9636                         dumpNamespace(fout, (NamespaceInfo *) dobj);
9637                         break;
9638                 case DO_EXTENSION:
9639                         dumpExtension(fout, (ExtensionInfo *) dobj);
9640                         break;
9641                 case DO_TYPE:
9642                         dumpType(fout, (TypeInfo *) dobj);
9643                         break;
9644                 case DO_SHELL_TYPE:
9645                         dumpShellType(fout, (ShellTypeInfo *) dobj);
9646                         break;
9647                 case DO_FUNC:
9648                         dumpFunc(fout, (FuncInfo *) dobj);
9649                         break;
9650                 case DO_AGG:
9651                         dumpAgg(fout, (AggInfo *) dobj);
9652                         break;
9653                 case DO_OPERATOR:
9654                         dumpOpr(fout, (OprInfo *) dobj);
9655                         break;
9656                 case DO_ACCESS_METHOD:
9657                         dumpAccessMethod(fout, (AccessMethodInfo *) dobj);
9658                         break;
9659                 case DO_OPCLASS:
9660                         dumpOpclass(fout, (OpclassInfo *) dobj);
9661                         break;
9662                 case DO_OPFAMILY:
9663                         dumpOpfamily(fout, (OpfamilyInfo *) dobj);
9664                         break;
9665                 case DO_COLLATION:
9666                         dumpCollation(fout, (CollInfo *) dobj);
9667                         break;
9668                 case DO_CONVERSION:
9669                         dumpConversion(fout, (ConvInfo *) dobj);
9670                         break;
9671                 case DO_TABLE:
9672                         dumpTable(fout, (TableInfo *) dobj);
9673                         break;
9674                 case DO_ATTRDEF:
9675                         dumpAttrDef(fout, (AttrDefInfo *) dobj);
9676                         break;
9677                 case DO_INDEX:
9678                         dumpIndex(fout, (IndxInfo *) dobj);
9679                         break;
9680                 case DO_INDEX_ATTACH:
9681                         dumpIndexAttach(fout, (IndexAttachInfo *) dobj);
9682                         break;
9683                 case DO_STATSEXT:
9684                         dumpStatisticsExt(fout, (StatsExtInfo *) dobj);
9685                         break;
9686                 case DO_REFRESH_MATVIEW:
9687                         refreshMatViewData(fout, (TableDataInfo *) dobj);
9688                         break;
9689                 case DO_RULE:
9690                         dumpRule(fout, (RuleInfo *) dobj);
9691                         break;
9692                 case DO_TRIGGER:
9693                         dumpTrigger(fout, (TriggerInfo *) dobj);
9694                         break;
9695                 case DO_EVENT_TRIGGER:
9696                         dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
9697                         break;
9698                 case DO_CONSTRAINT:
9699                         dumpConstraint(fout, (ConstraintInfo *) dobj);
9700                         break;
9701                 case DO_FK_CONSTRAINT:
9702                         dumpConstraint(fout, (ConstraintInfo *) dobj);
9703                         break;
9704                 case DO_PROCLANG:
9705                         dumpProcLang(fout, (ProcLangInfo *) dobj);
9706                         break;
9707                 case DO_CAST:
9708                         dumpCast(fout, (CastInfo *) dobj);
9709                         break;
9710                 case DO_TRANSFORM:
9711                         dumpTransform(fout, (TransformInfo *) dobj);
9712                         break;
9713                 case DO_SEQUENCE_SET:
9714                         dumpSequenceData(fout, (TableDataInfo *) dobj);
9715                         break;
9716                 case DO_TABLE_DATA:
9717                         dumpTableData(fout, (TableDataInfo *) dobj);
9718                         break;
9719                 case DO_DUMMY_TYPE:
9720                         /* table rowtypes and array types are never dumped separately */
9721                         break;
9722                 case DO_TSPARSER:
9723                         dumpTSParser(fout, (TSParserInfo *) dobj);
9724                         break;
9725                 case DO_TSDICT:
9726                         dumpTSDictionary(fout, (TSDictInfo *) dobj);
9727                         break;
9728                 case DO_TSTEMPLATE:
9729                         dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
9730                         break;
9731                 case DO_TSCONFIG:
9732                         dumpTSConfig(fout, (TSConfigInfo *) dobj);
9733                         break;
9734                 case DO_FDW:
9735                         dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
9736                         break;
9737                 case DO_FOREIGN_SERVER:
9738                         dumpForeignServer(fout, (ForeignServerInfo *) dobj);
9739                         break;
9740                 case DO_DEFAULT_ACL:
9741                         dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
9742                         break;
9743                 case DO_BLOB:
9744                         dumpBlob(fout, (BlobInfo *) dobj);
9745                         break;
9746                 case DO_BLOB_DATA:
9747                         if (dobj->dump & DUMP_COMPONENT_DATA)
9748                                 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
9749                                                          dobj->name, NULL, NULL, "",
9750                                                          false, "BLOBS", SECTION_DATA,
9751                                                          "", "", NULL,
9752                                                          NULL, 0,
9753                                                          dumpBlobs, NULL);
9754                         break;
9755                 case DO_POLICY:
9756                         dumpPolicy(fout, (PolicyInfo *) dobj);
9757                         break;
9758                 case DO_PUBLICATION:
9759                         dumpPublication(fout, (PublicationInfo *) dobj);
9760                         break;
9761                 case DO_PUBLICATION_REL:
9762                         dumpPublicationTable(fout, (PublicationRelInfo *) dobj);
9763                         break;
9764                 case DO_SUBSCRIPTION:
9765                         dumpSubscription(fout, (SubscriptionInfo *) dobj);
9766                         break;
9767                 case DO_PRE_DATA_BOUNDARY:
9768                 case DO_POST_DATA_BOUNDARY:
9769                         /* never dumped, nothing to do */
9770                         break;
9771         }
9772 }
9773
9774 /*
9775  * dumpNamespace
9776  *        writes out to fout the queries to recreate a user-defined namespace
9777  */
9778 static void
9779 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
9780 {
9781         DumpOptions *dopt = fout->dopt;
9782         PQExpBuffer q;
9783         PQExpBuffer delq;
9784         char       *qnspname;
9785
9786         /* Skip if not to be dumped */
9787         if (!nspinfo->dobj.dump || dopt->dataOnly)
9788                 return;
9789
9790         q = createPQExpBuffer();
9791         delq = createPQExpBuffer();
9792
9793         qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
9794
9795         appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
9796
9797         appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
9798
9799         if (dopt->binary_upgrade)
9800                 binary_upgrade_extension_member(q, &nspinfo->dobj,
9801                                                                                 "SCHEMA", qnspname, NULL);
9802
9803         if (nspinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9804                 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
9805                                          nspinfo->dobj.name,
9806                                          NULL, NULL,
9807                                          nspinfo->rolname,
9808                                          false, "SCHEMA", SECTION_PRE_DATA,
9809                                          q->data, delq->data, NULL,
9810                                          NULL, 0,
9811                                          NULL, NULL);
9812
9813         /* Dump Schema Comments and Security Labels */
9814         if (nspinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9815                 dumpComment(fout, "SCHEMA", qnspname,
9816                                         NULL, nspinfo->rolname,
9817                                         nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9818
9819         if (nspinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9820                 dumpSecLabel(fout, "SCHEMA", qnspname,
9821                                          NULL, nspinfo->rolname,
9822                                          nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9823
9824         if (nspinfo->dobj.dump & DUMP_COMPONENT_ACL)
9825                 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
9826                                 qnspname, NULL, NULL,
9827                                 nspinfo->rolname, nspinfo->nspacl, nspinfo->rnspacl,
9828                                 nspinfo->initnspacl, nspinfo->initrnspacl);
9829
9830         free(qnspname);
9831
9832         destroyPQExpBuffer(q);
9833         destroyPQExpBuffer(delq);
9834 }
9835
9836 /*
9837  * dumpExtension
9838  *        writes out to fout the queries to recreate an extension
9839  */
9840 static void
9841 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
9842 {
9843         DumpOptions *dopt = fout->dopt;
9844         PQExpBuffer q;
9845         PQExpBuffer delq;
9846         char       *qextname;
9847
9848         /* Skip if not to be dumped */
9849         if (!extinfo->dobj.dump || dopt->dataOnly)
9850                 return;
9851
9852         q = createPQExpBuffer();
9853         delq = createPQExpBuffer();
9854
9855         qextname = pg_strdup(fmtId(extinfo->dobj.name));
9856
9857         appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
9858
9859         if (!dopt->binary_upgrade)
9860         {
9861                 /*
9862                  * In a regular dump, we simply create the extension, intentionally
9863                  * not specifying a version, so that the destination installation's
9864                  * default version is used.
9865                  *
9866                  * Use of IF NOT EXISTS here is unlike our behavior for other object
9867                  * types; but there are various scenarios in which it's convenient to
9868                  * manually create the desired extension before restoring, so we
9869                  * prefer to allow it to exist already.
9870                  */
9871                 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
9872                                                   qextname, fmtId(extinfo->namespace));
9873         }
9874         else
9875         {
9876                 /*
9877                  * In binary-upgrade mode, it's critical to reproduce the state of the
9878                  * database exactly, so our procedure is to create an empty extension,
9879                  * restore all the contained objects normally, and add them to the
9880                  * extension one by one.  This function performs just the first of
9881                  * those steps.  binary_upgrade_extension_member() takes care of
9882                  * adding member objects as they're created.
9883                  */
9884                 int                     i;
9885                 int                     n;
9886
9887                 appendPQExpBufferStr(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
9888
9889                 /*
9890                  * We unconditionally create the extension, so we must drop it if it
9891                  * exists.  This could happen if the user deleted 'plpgsql' and then
9892                  * readded it, causing its oid to be greater than g_last_builtin_oid.
9893                  */
9894                 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
9895
9896                 appendPQExpBufferStr(q,
9897                                                          "SELECT pg_catalog.binary_upgrade_create_empty_extension(");
9898                 appendStringLiteralAH(q, extinfo->dobj.name, fout);
9899                 appendPQExpBufferStr(q, ", ");
9900                 appendStringLiteralAH(q, extinfo->namespace, fout);
9901                 appendPQExpBufferStr(q, ", ");
9902                 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
9903                 appendStringLiteralAH(q, extinfo->extversion, fout);
9904                 appendPQExpBufferStr(q, ", ");
9905
9906                 /*
9907                  * Note that we're pushing extconfig (an OID array) back into
9908                  * pg_extension exactly as-is.  This is OK because pg_class OIDs are
9909                  * preserved in binary upgrade.
9910                  */
9911                 if (strlen(extinfo->extconfig) > 2)
9912                         appendStringLiteralAH(q, extinfo->extconfig, fout);
9913                 else
9914                         appendPQExpBufferStr(q, "NULL");
9915                 appendPQExpBufferStr(q, ", ");
9916                 if (strlen(extinfo->extcondition) > 2)
9917                         appendStringLiteralAH(q, extinfo->extcondition, fout);
9918                 else
9919                         appendPQExpBufferStr(q, "NULL");
9920                 appendPQExpBufferStr(q, ", ");
9921                 appendPQExpBufferStr(q, "ARRAY[");
9922                 n = 0;
9923                 for (i = 0; i < extinfo->dobj.nDeps; i++)
9924                 {
9925                         DumpableObject *extobj;
9926
9927                         extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
9928                         if (extobj && extobj->objType == DO_EXTENSION)
9929                         {
9930                                 if (n++ > 0)
9931                                         appendPQExpBufferChar(q, ',');
9932                                 appendStringLiteralAH(q, extobj->name, fout);
9933                         }
9934                 }
9935                 appendPQExpBufferStr(q, "]::pg_catalog.text[]");
9936                 appendPQExpBufferStr(q, ");\n");
9937         }
9938
9939         if (extinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9940                 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
9941                                          extinfo->dobj.name,
9942                                          NULL, NULL,
9943                                          "",
9944                                          false, "EXTENSION", SECTION_PRE_DATA,
9945                                          q->data, delq->data, NULL,
9946                                          NULL, 0,
9947                                          NULL, NULL);
9948
9949         /* Dump Extension Comments and Security Labels */
9950         if (extinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9951                 dumpComment(fout, "EXTENSION", qextname,
9952                                         NULL, "",
9953                                         extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
9954
9955         if (extinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9956                 dumpSecLabel(fout, "EXTENSION", qextname,
9957                                          NULL, "",
9958                                          extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
9959
9960         free(qextname);
9961
9962         destroyPQExpBuffer(q);
9963         destroyPQExpBuffer(delq);
9964 }
9965
9966 /*
9967  * dumpType
9968  *        writes out to fout the queries to recreate a user-defined type
9969  */
9970 static void
9971 dumpType(Archive *fout, TypeInfo *tyinfo)
9972 {
9973         DumpOptions *dopt = fout->dopt;
9974
9975         /* Skip if not to be dumped */
9976         if (!tyinfo->dobj.dump || dopt->dataOnly)
9977                 return;
9978
9979         /* Dump out in proper style */
9980         if (tyinfo->typtype == TYPTYPE_BASE)
9981                 dumpBaseType(fout, tyinfo);
9982         else if (tyinfo->typtype == TYPTYPE_DOMAIN)
9983                 dumpDomain(fout, tyinfo);
9984         else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
9985                 dumpCompositeType(fout, tyinfo);
9986         else if (tyinfo->typtype == TYPTYPE_ENUM)
9987                 dumpEnumType(fout, tyinfo);
9988         else if (tyinfo->typtype == TYPTYPE_RANGE)
9989                 dumpRangeType(fout, tyinfo);
9990         else if (tyinfo->typtype == TYPTYPE_PSEUDO && !tyinfo->isDefined)
9991                 dumpUndefinedType(fout, tyinfo);
9992         else
9993                 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
9994                                   tyinfo->dobj.name);
9995 }
9996
9997 /*
9998  * dumpEnumType
9999  *        writes out to fout the queries to recreate a user-defined enum type
10000  */
10001 static void
10002 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
10003 {
10004         DumpOptions *dopt = fout->dopt;
10005         PQExpBuffer q = createPQExpBuffer();
10006         PQExpBuffer delq = createPQExpBuffer();
10007         PQExpBuffer query = createPQExpBuffer();
10008         PGresult   *res;
10009         int                     num,
10010                                 i;
10011         Oid                     enum_oid;
10012         char       *qtypname;
10013         char       *qualtypname;
10014         char       *label;
10015
10016         if (fout->remoteVersion >= 90100)
10017                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10018                                                   "FROM pg_catalog.pg_enum "
10019                                                   "WHERE enumtypid = '%u'"
10020                                                   "ORDER BY enumsortorder",
10021                                                   tyinfo->dobj.catId.oid);
10022         else
10023                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10024                                                   "FROM pg_catalog.pg_enum "
10025                                                   "WHERE enumtypid = '%u'"
10026                                                   "ORDER BY oid",
10027                                                   tyinfo->dobj.catId.oid);
10028
10029         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10030
10031         num = PQntuples(res);
10032
10033         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10034         qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10035
10036         /*
10037          * CASCADE shouldn't be required here as for normal types since the I/O
10038          * functions are generic and do not get dropped.
10039          */
10040         appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10041
10042         if (dopt->binary_upgrade)
10043                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10044                                                                                                  tyinfo->dobj.catId.oid,
10045                                                                                                  false);
10046
10047         appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
10048                                           qualtypname);
10049
10050         if (!dopt->binary_upgrade)
10051         {
10052                 /* Labels with server-assigned oids */
10053                 for (i = 0; i < num; i++)
10054                 {
10055                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10056                         if (i > 0)
10057                                 appendPQExpBufferChar(q, ',');
10058                         appendPQExpBufferStr(q, "\n    ");
10059                         appendStringLiteralAH(q, label, fout);
10060                 }
10061         }
10062
10063         appendPQExpBufferStr(q, "\n);\n");
10064
10065         if (dopt->binary_upgrade)
10066         {
10067                 /* Labels with dump-assigned (preserved) oids */
10068                 for (i = 0; i < num; i++)
10069                 {
10070                         enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
10071                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10072
10073                         if (i == 0)
10074                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
10075                         appendPQExpBuffer(q,
10076                                                           "SELECT pg_catalog.binary_upgrade_set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
10077                                                           enum_oid);
10078                         appendPQExpBuffer(q, "ALTER TYPE %s ADD VALUE ", qualtypname);
10079                         appendStringLiteralAH(q, label, fout);
10080                         appendPQExpBufferStr(q, ";\n\n");
10081                 }
10082         }
10083
10084         if (dopt->binary_upgrade)
10085                 binary_upgrade_extension_member(q, &tyinfo->dobj,
10086                                                                                 "TYPE", qtypname,
10087                                                                                 tyinfo->dobj.namespace->dobj.name);
10088
10089         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10090                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10091                                          tyinfo->dobj.name,
10092                                          tyinfo->dobj.namespace->dobj.name,
10093                                          NULL,
10094                                          tyinfo->rolname, false,
10095                                          "TYPE", SECTION_PRE_DATA,
10096                                          q->data, delq->data, NULL,
10097                                          NULL, 0,
10098                                          NULL, NULL);
10099
10100         /* Dump Type Comments and Security Labels */
10101         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10102                 dumpComment(fout, "TYPE", qtypname,
10103                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10104                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10105
10106         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10107                 dumpSecLabel(fout, "TYPE", qtypname,
10108                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10109                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10110
10111         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10112                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10113                                 qtypname, NULL,
10114                                 tyinfo->dobj.namespace->dobj.name,
10115                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10116                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10117
10118         PQclear(res);
10119         destroyPQExpBuffer(q);
10120         destroyPQExpBuffer(delq);
10121         destroyPQExpBuffer(query);
10122         free(qtypname);
10123         free(qualtypname);
10124 }
10125
10126 /*
10127  * dumpRangeType
10128  *        writes out to fout the queries to recreate a user-defined range type
10129  */
10130 static void
10131 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
10132 {
10133         DumpOptions *dopt = fout->dopt;
10134         PQExpBuffer q = createPQExpBuffer();
10135         PQExpBuffer delq = createPQExpBuffer();
10136         PQExpBuffer query = createPQExpBuffer();
10137         PGresult   *res;
10138         Oid                     collationOid;
10139         char       *qtypname;
10140         char       *qualtypname;
10141         char       *procname;
10142
10143         appendPQExpBuffer(query,
10144                                           "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
10145                                           "opc.opcname AS opcname, "
10146                                           "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
10147                                           "  WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
10148                                           "opc.opcdefault, "
10149                                           "CASE WHEN rngcollation = st.typcollation THEN 0 "
10150                                           "     ELSE rngcollation END AS collation, "
10151                                           "rngcanonical, rngsubdiff "
10152                                           "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
10153                                           "     pg_catalog.pg_opclass opc "
10154                                           "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
10155                                           "rngtypid = '%u'",
10156                                           tyinfo->dobj.catId.oid);
10157
10158         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10159
10160         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10161         qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10162
10163         /*
10164          * CASCADE shouldn't be required here as for normal types since the I/O
10165          * functions are generic and do not get dropped.
10166          */
10167         appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10168
10169         if (dopt->binary_upgrade)
10170                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10171                                                                                                  tyinfo->dobj.catId.oid,
10172                                                                                                  false);
10173
10174         appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
10175                                           qualtypname);
10176
10177         appendPQExpBuffer(q, "\n    subtype = %s",
10178                                           PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
10179
10180         /* print subtype_opclass only if not default for subtype */
10181         if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
10182         {
10183                 char       *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
10184                 char       *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
10185
10186                 appendPQExpBuffer(q, ",\n    subtype_opclass = %s.",
10187                                                   fmtId(nspname));
10188                 appendPQExpBufferStr(q, fmtId(opcname));
10189         }
10190
10191         collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
10192         if (OidIsValid(collationOid))
10193         {
10194                 CollInfo   *coll = findCollationByOid(collationOid);
10195
10196                 if (coll)
10197                         appendPQExpBuffer(q, ",\n    collation = %s",
10198                                                           fmtQualifiedDumpable(coll));
10199         }
10200
10201         procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
10202         if (strcmp(procname, "-") != 0)
10203                 appendPQExpBuffer(q, ",\n    canonical = %s", procname);
10204
10205         procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
10206         if (strcmp(procname, "-") != 0)
10207                 appendPQExpBuffer(q, ",\n    subtype_diff = %s", procname);
10208
10209         appendPQExpBufferStr(q, "\n);\n");
10210
10211         if (dopt->binary_upgrade)
10212                 binary_upgrade_extension_member(q, &tyinfo->dobj,
10213                                                                                 "TYPE", qtypname,
10214                                                                                 tyinfo->dobj.namespace->dobj.name);
10215
10216         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10217                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10218                                          tyinfo->dobj.name,
10219                                          tyinfo->dobj.namespace->dobj.name,
10220                                          NULL,
10221                                          tyinfo->rolname, false,
10222                                          "TYPE", SECTION_PRE_DATA,
10223                                          q->data, delq->data, NULL,
10224                                          NULL, 0,
10225                                          NULL, NULL);
10226
10227         /* Dump Type Comments and Security Labels */
10228         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10229                 dumpComment(fout, "TYPE", qtypname,
10230                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10231                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10232
10233         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10234                 dumpSecLabel(fout, "TYPE", qtypname,
10235                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10236                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10237
10238         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10239                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10240                                 qtypname, NULL,
10241                                 tyinfo->dobj.namespace->dobj.name,
10242                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10243                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10244
10245         PQclear(res);
10246         destroyPQExpBuffer(q);
10247         destroyPQExpBuffer(delq);
10248         destroyPQExpBuffer(query);
10249         free(qtypname);
10250         free(qualtypname);
10251 }
10252
10253 /*
10254  * dumpUndefinedType
10255  *        writes out to fout the queries to recreate a !typisdefined type
10256  *
10257  * This is a shell type, but we use different terminology to distinguish
10258  * this case from where we have to emit a shell type definition to break
10259  * circular dependencies.  An undefined type shouldn't ever have anything
10260  * depending on it.
10261  */
10262 static void
10263 dumpUndefinedType(Archive *fout, TypeInfo *tyinfo)
10264 {
10265         DumpOptions *dopt = fout->dopt;
10266         PQExpBuffer q = createPQExpBuffer();
10267         PQExpBuffer delq = createPQExpBuffer();
10268         char       *qtypname;
10269         char       *qualtypname;
10270
10271         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10272         qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10273
10274         appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10275
10276         if (dopt->binary_upgrade)
10277                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10278                                                                                                  tyinfo->dobj.catId.oid,
10279                                                                                                  false);
10280
10281         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
10282                                           qualtypname);
10283
10284         if (dopt->binary_upgrade)
10285                 binary_upgrade_extension_member(q, &tyinfo->dobj,
10286                                                                                 "TYPE", qtypname,
10287                                                                                 tyinfo->dobj.namespace->dobj.name);
10288
10289         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10290                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10291                                          tyinfo->dobj.name,
10292                                          tyinfo->dobj.namespace->dobj.name,
10293                                          NULL,
10294                                          tyinfo->rolname, false,
10295                                          "TYPE", SECTION_PRE_DATA,
10296                                          q->data, delq->data, NULL,
10297                                          NULL, 0,
10298                                          NULL, NULL);
10299
10300         /* Dump Type Comments and Security Labels */
10301         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10302                 dumpComment(fout, "TYPE", qtypname,
10303                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10304                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10305
10306         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10307                 dumpSecLabel(fout, "TYPE", qtypname,
10308                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10309                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10310
10311         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10312                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10313                                 qtypname, NULL,
10314                                 tyinfo->dobj.namespace->dobj.name,
10315                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10316                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10317
10318         destroyPQExpBuffer(q);
10319         destroyPQExpBuffer(delq);
10320         free(qtypname);
10321         free(qualtypname);
10322 }
10323
10324 /*
10325  * dumpBaseType
10326  *        writes out to fout the queries to recreate a user-defined base type
10327  */
10328 static void
10329 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
10330 {
10331         DumpOptions *dopt = fout->dopt;
10332         PQExpBuffer q = createPQExpBuffer();
10333         PQExpBuffer delq = createPQExpBuffer();
10334         PQExpBuffer query = createPQExpBuffer();
10335         PGresult   *res;
10336         char       *qtypname;
10337         char       *qualtypname;
10338         char       *typlen;
10339         char       *typinput;
10340         char       *typoutput;
10341         char       *typreceive;
10342         char       *typsend;
10343         char       *typmodin;
10344         char       *typmodout;
10345         char       *typanalyze;
10346         Oid                     typreceiveoid;
10347         Oid                     typsendoid;
10348         Oid                     typmodinoid;
10349         Oid                     typmodoutoid;
10350         Oid                     typanalyzeoid;
10351         char       *typcategory;
10352         char       *typispreferred;
10353         char       *typdelim;
10354         char       *typbyval;
10355         char       *typalign;
10356         char       *typstorage;
10357         char       *typcollatable;
10358         char       *typdefault;
10359         bool            typdefault_is_literal = false;
10360
10361         /* Fetch type-specific details */
10362         if (fout->remoteVersion >= 90100)
10363         {
10364                 appendPQExpBuffer(query, "SELECT typlen, "
10365                                                   "typinput, typoutput, typreceive, typsend, "
10366                                                   "typmodin, typmodout, typanalyze, "
10367                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
10368                                                   "typsend::pg_catalog.oid AS typsendoid, "
10369                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
10370                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
10371                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10372                                                   "typcategory, typispreferred, "
10373                                                   "typdelim, typbyval, typalign, typstorage, "
10374                                                   "(typcollation <> 0) AS typcollatable, "
10375                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10376                                                   "FROM pg_catalog.pg_type "
10377                                                   "WHERE oid = '%u'::pg_catalog.oid",
10378                                                   tyinfo->dobj.catId.oid);
10379         }
10380         else if (fout->remoteVersion >= 80400)
10381         {
10382                 appendPQExpBuffer(query, "SELECT typlen, "
10383                                                   "typinput, typoutput, typreceive, typsend, "
10384                                                   "typmodin, typmodout, typanalyze, "
10385                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
10386                                                   "typsend::pg_catalog.oid AS typsendoid, "
10387                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
10388                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
10389                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10390                                                   "typcategory, typispreferred, "
10391                                                   "typdelim, typbyval, typalign, typstorage, "
10392                                                   "false AS typcollatable, "
10393                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10394                                                   "FROM pg_catalog.pg_type "
10395                                                   "WHERE oid = '%u'::pg_catalog.oid",
10396                                                   tyinfo->dobj.catId.oid);
10397         }
10398         else if (fout->remoteVersion >= 80300)
10399         {
10400                 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
10401                 appendPQExpBuffer(query, "SELECT typlen, "
10402                                                   "typinput, typoutput, typreceive, typsend, "
10403                                                   "typmodin, typmodout, typanalyze, "
10404                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
10405                                                   "typsend::pg_catalog.oid AS typsendoid, "
10406                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
10407                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
10408                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10409                                                   "'U' AS typcategory, false AS typispreferred, "
10410                                                   "typdelim, typbyval, typalign, typstorage, "
10411                                                   "false AS typcollatable, "
10412                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10413                                                   "FROM pg_catalog.pg_type "
10414                                                   "WHERE oid = '%u'::pg_catalog.oid",
10415                                                   tyinfo->dobj.catId.oid);
10416         }
10417         else
10418         {
10419                 appendPQExpBuffer(query, "SELECT typlen, "
10420                                                   "typinput, typoutput, typreceive, typsend, "
10421                                                   "'-' AS typmodin, '-' AS typmodout, "
10422                                                   "typanalyze, "
10423                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
10424                                                   "typsend::pg_catalog.oid AS typsendoid, "
10425                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
10426                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10427                                                   "'U' AS typcategory, false AS typispreferred, "
10428                                                   "typdelim, typbyval, typalign, typstorage, "
10429                                                   "false AS typcollatable, "
10430                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10431                                                   "FROM pg_catalog.pg_type "
10432                                                   "WHERE oid = '%u'::pg_catalog.oid",
10433                                                   tyinfo->dobj.catId.oid);
10434         }
10435
10436         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10437
10438         typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
10439         typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
10440         typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
10441         typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
10442         typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
10443         typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
10444         typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
10445         typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
10446         typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
10447         typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
10448         typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
10449         typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
10450         typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
10451         typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
10452         typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
10453         typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
10454         typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
10455         typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
10456         typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
10457         typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
10458         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10459                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10460         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10461         {
10462                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10463                 typdefault_is_literal = true;   /* it needs quotes */
10464         }
10465         else
10466                 typdefault = NULL;
10467
10468         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10469         qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10470
10471         /*
10472          * The reason we include CASCADE is that the circular dependency between
10473          * the type and its I/O functions makes it impossible to drop the type any
10474          * other way.
10475          */
10476         appendPQExpBuffer(delq, "DROP TYPE %s CASCADE;\n", qualtypname);
10477
10478         /*
10479          * We might already have a shell type, but setting pg_type_oid is
10480          * harmless, and in any case we'd better set the array type OID.
10481          */
10482         if (dopt->binary_upgrade)
10483                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10484                                                                                                  tyinfo->dobj.catId.oid,
10485                                                                                                  false);
10486
10487         appendPQExpBuffer(q,
10488                                           "CREATE TYPE %s (\n"
10489                                           "    INTERNALLENGTH = %s",
10490                                           qualtypname,
10491                                           (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
10492
10493         /* regproc result is sufficiently quoted already */
10494         appendPQExpBuffer(q, ",\n    INPUT = %s", typinput);
10495         appendPQExpBuffer(q, ",\n    OUTPUT = %s", typoutput);
10496         if (OidIsValid(typreceiveoid))
10497                 appendPQExpBuffer(q, ",\n    RECEIVE = %s", typreceive);
10498         if (OidIsValid(typsendoid))
10499                 appendPQExpBuffer(q, ",\n    SEND = %s", typsend);
10500         if (OidIsValid(typmodinoid))
10501                 appendPQExpBuffer(q, ",\n    TYPMOD_IN = %s", typmodin);
10502         if (OidIsValid(typmodoutoid))
10503                 appendPQExpBuffer(q, ",\n    TYPMOD_OUT = %s", typmodout);
10504         if (OidIsValid(typanalyzeoid))
10505                 appendPQExpBuffer(q, ",\n    ANALYZE = %s", typanalyze);
10506
10507         if (strcmp(typcollatable, "t") == 0)
10508                 appendPQExpBufferStr(q, ",\n    COLLATABLE = true");
10509
10510         if (typdefault != NULL)
10511         {
10512                 appendPQExpBufferStr(q, ",\n    DEFAULT = ");
10513                 if (typdefault_is_literal)
10514                         appendStringLiteralAH(q, typdefault, fout);
10515                 else
10516                         appendPQExpBufferStr(q, typdefault);
10517         }
10518
10519         if (OidIsValid(tyinfo->typelem))
10520         {
10521                 char       *elemType;
10522
10523                 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
10524                 appendPQExpBuffer(q, ",\n    ELEMENT = %s", elemType);
10525                 free(elemType);
10526         }
10527
10528         if (strcmp(typcategory, "U") != 0)
10529         {
10530                 appendPQExpBufferStr(q, ",\n    CATEGORY = ");
10531                 appendStringLiteralAH(q, typcategory, fout);
10532         }
10533
10534         if (strcmp(typispreferred, "t") == 0)
10535                 appendPQExpBufferStr(q, ",\n    PREFERRED = true");
10536
10537         if (typdelim && strcmp(typdelim, ",") != 0)
10538         {
10539                 appendPQExpBufferStr(q, ",\n    DELIMITER = ");
10540                 appendStringLiteralAH(q, typdelim, fout);
10541         }
10542
10543         if (strcmp(typalign, "c") == 0)
10544                 appendPQExpBufferStr(q, ",\n    ALIGNMENT = char");
10545         else if (strcmp(typalign, "s") == 0)
10546                 appendPQExpBufferStr(q, ",\n    ALIGNMENT = int2");
10547         else if (strcmp(typalign, "i") == 0)
10548                 appendPQExpBufferStr(q, ",\n    ALIGNMENT = int4");
10549         else if (strcmp(typalign, "d") == 0)
10550                 appendPQExpBufferStr(q, ",\n    ALIGNMENT = double");
10551
10552         if (strcmp(typstorage, "p") == 0)
10553                 appendPQExpBufferStr(q, ",\n    STORAGE = plain");
10554         else if (strcmp(typstorage, "e") == 0)
10555                 appendPQExpBufferStr(q, ",\n    STORAGE = external");
10556         else if (strcmp(typstorage, "x") == 0)
10557                 appendPQExpBufferStr(q, ",\n    STORAGE = extended");
10558         else if (strcmp(typstorage, "m") == 0)
10559                 appendPQExpBufferStr(q, ",\n    STORAGE = main");
10560
10561         if (strcmp(typbyval, "t") == 0)
10562                 appendPQExpBufferStr(q, ",\n    PASSEDBYVALUE");
10563
10564         appendPQExpBufferStr(q, "\n);\n");
10565
10566         if (dopt->binary_upgrade)
10567                 binary_upgrade_extension_member(q, &tyinfo->dobj,
10568                                                                                 "TYPE", qtypname,
10569                                                                                 tyinfo->dobj.namespace->dobj.name);
10570
10571         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10572                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10573                                          tyinfo->dobj.name,
10574                                          tyinfo->dobj.namespace->dobj.name,
10575                                          NULL,
10576                                          tyinfo->rolname, false,
10577                                          "TYPE", SECTION_PRE_DATA,
10578                                          q->data, delq->data, NULL,
10579                                          NULL, 0,
10580                                          NULL, NULL);
10581
10582         /* Dump Type Comments and Security Labels */
10583         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10584                 dumpComment(fout, "TYPE", qtypname,
10585                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10586                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10587
10588         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10589                 dumpSecLabel(fout, "TYPE", qtypname,
10590                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10591                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10592
10593         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10594                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10595                                 qtypname, NULL,
10596                                 tyinfo->dobj.namespace->dobj.name,
10597                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10598                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10599
10600         PQclear(res);
10601         destroyPQExpBuffer(q);
10602         destroyPQExpBuffer(delq);
10603         destroyPQExpBuffer(query);
10604         free(qtypname);
10605         free(qualtypname);
10606 }
10607
10608 /*
10609  * dumpDomain
10610  *        writes out to fout the queries to recreate a user-defined domain
10611  */
10612 static void
10613 dumpDomain(Archive *fout, TypeInfo *tyinfo)
10614 {
10615         DumpOptions *dopt = fout->dopt;
10616         PQExpBuffer q = createPQExpBuffer();
10617         PQExpBuffer delq = createPQExpBuffer();
10618         PQExpBuffer query = createPQExpBuffer();
10619         PGresult   *res;
10620         int                     i;
10621         char       *qtypname;
10622         char       *qualtypname;
10623         char       *typnotnull;
10624         char       *typdefn;
10625         char       *typdefault;
10626         Oid                     typcollation;
10627         bool            typdefault_is_literal = false;
10628
10629         /* Fetch domain specific details */
10630         if (fout->remoteVersion >= 90100)
10631         {
10632                 /* typcollation is new in 9.1 */
10633                 appendPQExpBuffer(query, "SELECT t.typnotnull, "
10634                                                   "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
10635                                                   "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10636                                                   "t.typdefault, "
10637                                                   "CASE WHEN t.typcollation <> u.typcollation "
10638                                                   "THEN t.typcollation ELSE 0 END AS typcollation "
10639                                                   "FROM pg_catalog.pg_type t "
10640                                                   "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
10641                                                   "WHERE t.oid = '%u'::pg_catalog.oid",
10642                                                   tyinfo->dobj.catId.oid);
10643         }
10644         else
10645         {
10646                 appendPQExpBuffer(query, "SELECT typnotnull, "
10647                                                   "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
10648                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10649                                                   "typdefault, 0 AS typcollation "
10650                                                   "FROM pg_catalog.pg_type "
10651                                                   "WHERE oid = '%u'::pg_catalog.oid",
10652                                                   tyinfo->dobj.catId.oid);
10653         }
10654
10655         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10656
10657         typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
10658         typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
10659         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10660                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10661         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10662         {
10663                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10664                 typdefault_is_literal = true;   /* it needs quotes */
10665         }
10666         else
10667                 typdefault = NULL;
10668         typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
10669
10670         if (dopt->binary_upgrade)
10671                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10672                                                                                                  tyinfo->dobj.catId.oid,
10673                                                                                                  true); /* force array type */
10674
10675         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10676         qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10677
10678         appendPQExpBuffer(q,
10679                                           "CREATE DOMAIN %s AS %s",
10680                                           qualtypname,
10681                                           typdefn);
10682
10683         /* Print collation only if different from base type's collation */
10684         if (OidIsValid(typcollation))
10685         {
10686                 CollInfo   *coll;
10687
10688                 coll = findCollationByOid(typcollation);
10689                 if (coll)
10690                         appendPQExpBuffer(q, " COLLATE %s", fmtQualifiedDumpable(coll));
10691         }
10692
10693         if (typnotnull[0] == 't')
10694                 appendPQExpBufferStr(q, " NOT NULL");
10695
10696         if (typdefault != NULL)
10697         {
10698                 appendPQExpBufferStr(q, " DEFAULT ");
10699                 if (typdefault_is_literal)
10700                         appendStringLiteralAH(q, typdefault, fout);
10701                 else
10702                         appendPQExpBufferStr(q, typdefault);
10703         }
10704
10705         PQclear(res);
10706
10707         /*
10708          * Add any CHECK constraints for the domain
10709          */
10710         for (i = 0; i < tyinfo->nDomChecks; i++)
10711         {
10712                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10713
10714                 if (!domcheck->separate)
10715                         appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
10716                                                           fmtId(domcheck->dobj.name), domcheck->condef);
10717         }
10718
10719         appendPQExpBufferStr(q, ";\n");
10720
10721         appendPQExpBuffer(delq, "DROP DOMAIN %s;\n", qualtypname);
10722
10723         if (dopt->binary_upgrade)
10724                 binary_upgrade_extension_member(q, &tyinfo->dobj,
10725                                                                                 "DOMAIN", qtypname,
10726                                                                                 tyinfo->dobj.namespace->dobj.name);
10727
10728         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10729                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10730                                          tyinfo->dobj.name,
10731                                          tyinfo->dobj.namespace->dobj.name,
10732                                          NULL,
10733                                          tyinfo->rolname, false,
10734                                          "DOMAIN", SECTION_PRE_DATA,
10735                                          q->data, delq->data, NULL,
10736                                          NULL, 0,
10737                                          NULL, NULL);
10738
10739         /* Dump Domain Comments and Security Labels */
10740         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10741                 dumpComment(fout, "DOMAIN", qtypname,
10742                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10743                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10744
10745         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10746                 dumpSecLabel(fout, "DOMAIN", qtypname,
10747                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10748                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10749
10750         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10751                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10752                                 qtypname, NULL,
10753                                 tyinfo->dobj.namespace->dobj.name,
10754                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10755                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10756
10757         /* Dump any per-constraint comments */
10758         for (i = 0; i < tyinfo->nDomChecks; i++)
10759         {
10760                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10761                 PQExpBuffer conprefix = createPQExpBuffer();
10762
10763                 appendPQExpBuffer(conprefix, "CONSTRAINT %s ON DOMAIN",
10764                                                   fmtId(domcheck->dobj.name));
10765
10766                 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10767                         dumpComment(fout, conprefix->data, qtypname,
10768                                                 tyinfo->dobj.namespace->dobj.name,
10769                                                 tyinfo->rolname,
10770                                                 domcheck->dobj.catId, 0, tyinfo->dobj.dumpId);
10771
10772                 destroyPQExpBuffer(conprefix);
10773         }
10774
10775         destroyPQExpBuffer(q);
10776         destroyPQExpBuffer(delq);
10777         destroyPQExpBuffer(query);
10778         free(qtypname);
10779         free(qualtypname);
10780 }
10781
10782 /*
10783  * dumpCompositeType
10784  *        writes out to fout the queries to recreate a user-defined stand-alone
10785  *        composite type
10786  */
10787 static void
10788 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
10789 {
10790         DumpOptions *dopt = fout->dopt;
10791         PQExpBuffer q = createPQExpBuffer();
10792         PQExpBuffer dropped = createPQExpBuffer();
10793         PQExpBuffer delq = createPQExpBuffer();
10794         PQExpBuffer query = createPQExpBuffer();
10795         PGresult   *res;
10796         char       *qtypname;
10797         char       *qualtypname;
10798         int                     ntups;
10799         int                     i_attname;
10800         int                     i_atttypdefn;
10801         int                     i_attlen;
10802         int                     i_attalign;
10803         int                     i_attisdropped;
10804         int                     i_attcollation;
10805         int                     i;
10806         int                     actual_atts;
10807
10808         /* Fetch type specific details */
10809         if (fout->remoteVersion >= 90100)
10810         {
10811                 /*
10812                  * attcollation is new in 9.1.  Since we only want to dump COLLATE
10813                  * clauses for attributes whose collation is different from their
10814                  * type's default, we use a CASE here to suppress uninteresting
10815                  * attcollations cheaply.  atttypid will be 0 for dropped columns;
10816                  * collation does not matter for those.
10817                  */
10818                 appendPQExpBuffer(query, "SELECT a.attname, "
10819                                                   "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10820                                                   "a.attlen, a.attalign, a.attisdropped, "
10821                                                   "CASE WHEN a.attcollation <> at.typcollation "
10822                                                   "THEN a.attcollation ELSE 0 END AS attcollation "
10823                                                   "FROM pg_catalog.pg_type ct "
10824                                                   "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
10825                                                   "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
10826                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
10827                                                   "ORDER BY a.attnum ",
10828                                                   tyinfo->dobj.catId.oid);
10829         }
10830         else
10831         {
10832                 /*
10833                  * Since ALTER TYPE could not drop columns until 9.1, attisdropped
10834                  * should always be false.
10835                  */
10836                 appendPQExpBuffer(query, "SELECT a.attname, "
10837                                                   "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10838                                                   "a.attlen, a.attalign, a.attisdropped, "
10839                                                   "0 AS attcollation "
10840                                                   "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
10841                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
10842                                                   "AND a.attrelid = ct.typrelid "
10843                                                   "ORDER BY a.attnum ",
10844                                                   tyinfo->dobj.catId.oid);
10845         }
10846
10847         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10848
10849         ntups = PQntuples(res);
10850
10851         i_attname = PQfnumber(res, "attname");
10852         i_atttypdefn = PQfnumber(res, "atttypdefn");
10853         i_attlen = PQfnumber(res, "attlen");
10854         i_attalign = PQfnumber(res, "attalign");
10855         i_attisdropped = PQfnumber(res, "attisdropped");
10856         i_attcollation = PQfnumber(res, "attcollation");
10857
10858         if (dopt->binary_upgrade)
10859         {
10860                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10861                                                                                                  tyinfo->dobj.catId.oid,
10862                                                                                                  false);
10863                 binary_upgrade_set_pg_class_oids(fout, q, tyinfo->typrelid, false);
10864         }
10865
10866         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10867         qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10868
10869         appendPQExpBuffer(q, "CREATE TYPE %s AS (",
10870                                           qualtypname);
10871
10872         actual_atts = 0;
10873         for (i = 0; i < ntups; i++)
10874         {
10875                 char       *attname;
10876                 char       *atttypdefn;
10877                 char       *attlen;
10878                 char       *attalign;
10879                 bool            attisdropped;
10880                 Oid                     attcollation;
10881
10882                 attname = PQgetvalue(res, i, i_attname);
10883                 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
10884                 attlen = PQgetvalue(res, i, i_attlen);
10885                 attalign = PQgetvalue(res, i, i_attalign);
10886                 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
10887                 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
10888
10889                 if (attisdropped && !dopt->binary_upgrade)
10890                         continue;
10891
10892                 /* Format properly if not first attr */
10893                 if (actual_atts++ > 0)
10894                         appendPQExpBufferChar(q, ',');
10895                 appendPQExpBufferStr(q, "\n\t");
10896
10897                 if (!attisdropped)
10898                 {
10899                         appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
10900
10901                         /* Add collation if not default for the column type */
10902                         if (OidIsValid(attcollation))
10903                         {
10904                                 CollInfo   *coll;
10905
10906                                 coll = findCollationByOid(attcollation);
10907                                 if (coll)
10908                                         appendPQExpBuffer(q, " COLLATE %s",
10909                                                                           fmtQualifiedDumpable(coll));
10910                         }
10911                 }
10912                 else
10913                 {
10914                         /*
10915                          * This is a dropped attribute and we're in binary_upgrade mode.
10916                          * Insert a placeholder for it in the CREATE TYPE command, and set
10917                          * length and alignment with direct UPDATE to the catalogs
10918                          * afterwards. See similar code in dumpTableSchema().
10919                          */
10920                         appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
10921
10922                         /* stash separately for insertion after the CREATE TYPE */
10923                         appendPQExpBufferStr(dropped,
10924                                                                  "\n-- For binary upgrade, recreate dropped column.\n");
10925                         appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
10926                                                           "SET attlen = %s, "
10927                                                           "attalign = '%s', attbyval = false\n"
10928                                                           "WHERE attname = ", attlen, attalign);
10929                         appendStringLiteralAH(dropped, attname, fout);
10930                         appendPQExpBufferStr(dropped, "\n  AND attrelid = ");
10931                         appendStringLiteralAH(dropped, qualtypname, fout);
10932                         appendPQExpBufferStr(dropped, "::pg_catalog.regclass;\n");
10933
10934                         appendPQExpBuffer(dropped, "ALTER TYPE %s ",
10935                                                           qualtypname);
10936                         appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
10937                                                           fmtId(attname));
10938                 }
10939         }
10940         appendPQExpBufferStr(q, "\n);\n");
10941         appendPQExpBufferStr(q, dropped->data);
10942
10943         appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10944
10945         if (dopt->binary_upgrade)
10946                 binary_upgrade_extension_member(q, &tyinfo->dobj,
10947                                                                                 "TYPE", qtypname,
10948                                                                                 tyinfo->dobj.namespace->dobj.name);
10949
10950         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10951                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10952                                          tyinfo->dobj.name,
10953                                          tyinfo->dobj.namespace->dobj.name,
10954                                          NULL,
10955                                          tyinfo->rolname, false,
10956                                          "TYPE", SECTION_PRE_DATA,
10957                                          q->data, delq->data, NULL,
10958                                          NULL, 0,
10959                                          NULL, NULL);
10960
10961
10962         /* Dump Type Comments and Security Labels */
10963         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10964                 dumpComment(fout, "TYPE", qtypname,
10965                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10966                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10967
10968         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10969                 dumpSecLabel(fout, "TYPE", qtypname,
10970                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10971                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10972
10973         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10974                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10975                                 qtypname, NULL,
10976                                 tyinfo->dobj.namespace->dobj.name,
10977                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10978                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10979
10980         PQclear(res);
10981         destroyPQExpBuffer(q);
10982         destroyPQExpBuffer(dropped);
10983         destroyPQExpBuffer(delq);
10984         destroyPQExpBuffer(query);
10985         free(qtypname);
10986         free(qualtypname);
10987
10988         /* Dump any per-column comments */
10989         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10990                 dumpCompositeTypeColComments(fout, tyinfo);
10991 }
10992
10993 /*
10994  * dumpCompositeTypeColComments
10995  *        writes out to fout the queries to recreate comments on the columns of
10996  *        a user-defined stand-alone composite type
10997  */
10998 static void
10999 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
11000 {
11001         CommentItem *comments;
11002         int                     ncomments;
11003         PGresult   *res;
11004         PQExpBuffer query;
11005         PQExpBuffer target;
11006         Oid                     pgClassOid;
11007         int                     i;
11008         int                     ntups;
11009         int                     i_attname;
11010         int                     i_attnum;
11011
11012         /* do nothing, if --no-comments is supplied */
11013         if (fout->dopt->no_comments)
11014                 return;
11015
11016         query = createPQExpBuffer();
11017
11018         appendPQExpBuffer(query,
11019                                           "SELECT c.tableoid, a.attname, a.attnum "
11020                                           "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
11021                                           "WHERE c.oid = '%u' AND c.oid = a.attrelid "
11022                                           "  AND NOT a.attisdropped "
11023                                           "ORDER BY a.attnum ",
11024                                           tyinfo->typrelid);
11025
11026         /* Fetch column attnames */
11027         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11028
11029         ntups = PQntuples(res);
11030         if (ntups < 1)
11031         {
11032                 PQclear(res);
11033                 destroyPQExpBuffer(query);
11034                 return;
11035         }
11036
11037         pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
11038
11039         /* Search for comments associated with type's pg_class OID */
11040         ncomments = findComments(fout,
11041                                                          pgClassOid,
11042                                                          tyinfo->typrelid,
11043                                                          &comments);
11044
11045         /* If no comments exist, we're done */
11046         if (ncomments <= 0)
11047         {
11048                 PQclear(res);
11049                 destroyPQExpBuffer(query);
11050                 return;
11051         }
11052
11053         /* Build COMMENT ON statements */
11054         target = createPQExpBuffer();
11055
11056         i_attnum = PQfnumber(res, "attnum");
11057         i_attname = PQfnumber(res, "attname");
11058         while (ncomments > 0)
11059         {
11060                 const char *attname;
11061
11062                 attname = NULL;
11063                 for (i = 0; i < ntups; i++)
11064                 {
11065                         if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
11066                         {
11067                                 attname = PQgetvalue(res, i, i_attname);
11068                                 break;
11069                         }
11070                 }
11071                 if (attname)                    /* just in case we don't find it */
11072                 {
11073                         const char *descr = comments->descr;
11074
11075                         resetPQExpBuffer(target);
11076                         appendPQExpBuffer(target, "COLUMN %s.",
11077                                                           fmtId(tyinfo->dobj.name));
11078                         appendPQExpBufferStr(target, fmtId(attname));
11079
11080                         resetPQExpBuffer(query);
11081                         appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
11082                                                           fmtQualifiedDumpable(tyinfo));
11083                         appendPQExpBuffer(query, "%s IS ", fmtId(attname));
11084                         appendStringLiteralAH(query, descr, fout);
11085                         appendPQExpBufferStr(query, ";\n");
11086
11087                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
11088                                                  target->data,
11089                                                  tyinfo->dobj.namespace->dobj.name,
11090                                                  NULL, tyinfo->rolname,
11091                                                  false, "COMMENT", SECTION_NONE,
11092                                                  query->data, "", NULL,
11093                                                  &(tyinfo->dobj.dumpId), 1,
11094                                                  NULL, NULL);
11095                 }
11096
11097                 comments++;
11098                 ncomments--;
11099         }
11100
11101         PQclear(res);
11102         destroyPQExpBuffer(query);
11103         destroyPQExpBuffer(target);
11104 }
11105
11106 /*
11107  * dumpShellType
11108  *        writes out to fout the queries to create a shell type
11109  *
11110  * We dump a shell definition in advance of the I/O functions for the type.
11111  */
11112 static void
11113 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
11114 {
11115         DumpOptions *dopt = fout->dopt;
11116         PQExpBuffer q;
11117
11118         /* Skip if not to be dumped */
11119         if (!stinfo->dobj.dump || dopt->dataOnly)
11120                 return;
11121
11122         q = createPQExpBuffer();
11123
11124         /*
11125          * Note the lack of a DROP command for the shell type; any required DROP
11126          * is driven off the base type entry, instead.  This interacts with
11127          * _printTocEntry()'s use of the presence of a DROP command to decide
11128          * whether an entry needs an ALTER OWNER command.  We don't want to alter
11129          * the shell type's owner immediately on creation; that should happen only
11130          * after it's filled in, otherwise the backend complains.
11131          */
11132
11133         if (dopt->binary_upgrade)
11134                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
11135                                                                                                  stinfo->baseType->dobj.catId.oid,
11136                                                                                                  false);
11137
11138         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
11139                                           fmtQualifiedDumpable(stinfo));
11140
11141         if (stinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11142                 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
11143                                          stinfo->dobj.name,
11144                                          stinfo->dobj.namespace->dobj.name,
11145                                          NULL,
11146                                          stinfo->baseType->rolname, false,
11147                                          "SHELL TYPE", SECTION_PRE_DATA,
11148                                          q->data, "", NULL,
11149                                          NULL, 0,
11150                                          NULL, NULL);
11151
11152         destroyPQExpBuffer(q);
11153 }
11154
11155 /*
11156  * dumpProcLang
11157  *                writes out to fout the queries to recreate a user-defined
11158  *                procedural language
11159  */
11160 static void
11161 dumpProcLang(Archive *fout, ProcLangInfo *plang)
11162 {
11163         DumpOptions *dopt = fout->dopt;
11164         PQExpBuffer defqry;
11165         PQExpBuffer delqry;
11166         bool            useParams;
11167         char       *qlanname;
11168         FuncInfo   *funcInfo;
11169         FuncInfo   *inlineInfo = NULL;
11170         FuncInfo   *validatorInfo = NULL;
11171
11172         /* Skip if not to be dumped */
11173         if (!plang->dobj.dump || dopt->dataOnly)
11174                 return;
11175
11176         /*
11177          * Try to find the support function(s).  It is not an error if we don't
11178          * find them --- if the functions are in the pg_catalog schema, as is
11179          * standard in 8.1 and up, then we won't have loaded them. (In this case
11180          * we will emit a parameterless CREATE LANGUAGE command, which will
11181          * require PL template knowledge in the backend to reload.)
11182          */
11183
11184         funcInfo = findFuncByOid(plang->lanplcallfoid);
11185         if (funcInfo != NULL && !funcInfo->dobj.dump)
11186                 funcInfo = NULL;                /* treat not-dumped same as not-found */
11187
11188         if (OidIsValid(plang->laninline))
11189         {
11190                 inlineInfo = findFuncByOid(plang->laninline);
11191                 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
11192                         inlineInfo = NULL;
11193         }
11194
11195         if (OidIsValid(plang->lanvalidator))
11196         {
11197                 validatorInfo = findFuncByOid(plang->lanvalidator);
11198                 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
11199                         validatorInfo = NULL;
11200         }
11201
11202         /*
11203          * If the functions are dumpable then emit a traditional CREATE LANGUAGE
11204          * with parameters.  Otherwise, we'll write a parameterless command, which
11205          * will rely on data from pg_pltemplate.
11206          */
11207         useParams = (funcInfo != NULL &&
11208                                  (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
11209                                  (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
11210
11211         defqry = createPQExpBuffer();
11212         delqry = createPQExpBuffer();
11213
11214         qlanname = pg_strdup(fmtId(plang->dobj.name));
11215
11216         appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
11217                                           qlanname);
11218
11219         if (useParams)
11220         {
11221                 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
11222                                                   plang->lanpltrusted ? "TRUSTED " : "",
11223                                                   qlanname);
11224                 appendPQExpBuffer(defqry, " HANDLER %s",
11225                                                   fmtQualifiedDumpable(funcInfo));
11226                 if (OidIsValid(plang->laninline))
11227                         appendPQExpBuffer(defqry, " INLINE %s",
11228                                                           fmtQualifiedDumpable(inlineInfo));
11229                 if (OidIsValid(plang->lanvalidator))
11230                         appendPQExpBuffer(defqry, " VALIDATOR %s",
11231                                                           fmtQualifiedDumpable(validatorInfo));
11232         }
11233         else
11234         {
11235                 /*
11236                  * If not dumping parameters, then use CREATE OR REPLACE so that the
11237                  * command will not fail if the language is preinstalled in the target
11238                  * database.  We restrict the use of REPLACE to this case so as to
11239                  * eliminate the risk of replacing a language with incompatible
11240                  * parameter settings: this command will only succeed at all if there
11241                  * is a pg_pltemplate entry, and if there is one, the existing entry
11242                  * must match it too.
11243                  */
11244                 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
11245                                                   qlanname);
11246         }
11247         appendPQExpBufferStr(defqry, ";\n");
11248
11249         if (dopt->binary_upgrade)
11250                 binary_upgrade_extension_member(defqry, &plang->dobj,
11251                                                                                 "LANGUAGE", qlanname, NULL);
11252
11253         if (plang->dobj.dump & DUMP_COMPONENT_DEFINITION)
11254                 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
11255                                          plang->dobj.name,
11256                                          NULL, NULL, plang->lanowner,
11257                                          false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
11258                                          defqry->data, delqry->data, NULL,
11259                                          NULL, 0,
11260                                          NULL, NULL);
11261
11262         /* Dump Proc Lang Comments and Security Labels */
11263         if (plang->dobj.dump & DUMP_COMPONENT_COMMENT)
11264                 dumpComment(fout, "LANGUAGE", qlanname,
11265                                         NULL, plang->lanowner,
11266                                         plang->dobj.catId, 0, plang->dobj.dumpId);
11267
11268         if (plang->dobj.dump & DUMP_COMPONENT_SECLABEL)
11269                 dumpSecLabel(fout, "LANGUAGE", qlanname,
11270                                          NULL, plang->lanowner,
11271                                          plang->dobj.catId, 0, plang->dobj.dumpId);
11272
11273         if (plang->lanpltrusted && plang->dobj.dump & DUMP_COMPONENT_ACL)
11274                 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
11275                                 qlanname, NULL, NULL,
11276                                 plang->lanowner, plang->lanacl, plang->rlanacl,
11277                                 plang->initlanacl, plang->initrlanacl);
11278
11279         free(qlanname);
11280
11281         destroyPQExpBuffer(defqry);
11282         destroyPQExpBuffer(delqry);
11283 }
11284
11285 /*
11286  * format_function_arguments: generate function name and argument list
11287  *
11288  * This is used when we can rely on pg_get_function_arguments to format
11289  * the argument list.  Note, however, that pg_get_function_arguments
11290  * does not special-case zero-argument aggregates.
11291  */
11292 static char *
11293 format_function_arguments(FuncInfo *finfo, char *funcargs, bool is_agg)
11294 {
11295         PQExpBufferData fn;
11296
11297         initPQExpBuffer(&fn);
11298         appendPQExpBufferStr(&fn, fmtId(finfo->dobj.name));
11299         if (is_agg && finfo->nargs == 0)
11300                 appendPQExpBufferStr(&fn, "(*)");
11301         else
11302                 appendPQExpBuffer(&fn, "(%s)", funcargs);
11303         return fn.data;
11304 }
11305
11306 /*
11307  * format_function_arguments_old: generate function name and argument list
11308  *
11309  * The argument type names are qualified if needed.  The function name
11310  * is never qualified.
11311  *
11312  * This is used only with pre-8.4 servers, so we aren't expecting to see
11313  * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
11314  *
11315  * Any or all of allargtypes, argmodes, argnames may be NULL.
11316  */
11317 static char *
11318 format_function_arguments_old(Archive *fout,
11319                                                           FuncInfo *finfo, int nallargs,
11320                                                           char **allargtypes,
11321                                                           char **argmodes,
11322                                                           char **argnames)
11323 {
11324         PQExpBufferData fn;
11325         int                     j;
11326
11327         initPQExpBuffer(&fn);
11328         appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11329         for (j = 0; j < nallargs; j++)
11330         {
11331                 Oid                     typid;
11332                 char       *typname;
11333                 const char *argmode;
11334                 const char *argname;
11335
11336                 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
11337                 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
11338
11339                 if (argmodes)
11340                 {
11341                         switch (argmodes[j][0])
11342                         {
11343                                 case PROARGMODE_IN:
11344                                         argmode = "";
11345                                         break;
11346                                 case PROARGMODE_OUT:
11347                                         argmode = "OUT ";
11348                                         break;
11349                                 case PROARGMODE_INOUT:
11350                                         argmode = "INOUT ";
11351                                         break;
11352                                 default:
11353                                         write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
11354                                         argmode = "";
11355                                         break;
11356                         }
11357                 }
11358                 else
11359                         argmode = "";
11360
11361                 argname = argnames ? argnames[j] : (char *) NULL;
11362                 if (argname && argname[0] == '\0')
11363                         argname = NULL;
11364
11365                 appendPQExpBuffer(&fn, "%s%s%s%s%s",
11366                                                   (j > 0) ? ", " : "",
11367                                                   argmode,
11368                                                   argname ? fmtId(argname) : "",
11369                                                   argname ? " " : "",
11370                                                   typname);
11371                 free(typname);
11372         }
11373         appendPQExpBufferChar(&fn, ')');
11374         return fn.data;
11375 }
11376
11377 /*
11378  * format_function_signature: generate function name and argument list
11379  *
11380  * This is like format_function_arguments_old except that only a minimal
11381  * list of input argument types is generated; this is sufficient to
11382  * reference the function, but not to define it.
11383  *
11384  * If honor_quotes is false then the function name is never quoted.
11385  * This is appropriate for use in TOC tags, but not in SQL commands.
11386  */
11387 static char *
11388 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
11389 {
11390         PQExpBufferData fn;
11391         int                     j;
11392
11393         initPQExpBuffer(&fn);
11394         if (honor_quotes)
11395                 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11396         else
11397                 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
11398         for (j = 0; j < finfo->nargs; j++)
11399         {
11400                 char       *typname;
11401
11402                 if (j > 0)
11403                         appendPQExpBufferStr(&fn, ", ");
11404
11405                 typname = getFormattedTypeName(fout, finfo->argtypes[j],
11406                                                                            zeroAsOpaque);
11407                 appendPQExpBufferStr(&fn, typname);
11408                 free(typname);
11409         }
11410         appendPQExpBufferChar(&fn, ')');
11411         return fn.data;
11412 }
11413
11414
11415 /*
11416  * dumpFunc:
11417  *        dump out one function
11418  */
11419 static void
11420 dumpFunc(Archive *fout, FuncInfo *finfo)
11421 {
11422         DumpOptions *dopt = fout->dopt;
11423         PQExpBuffer query;
11424         PQExpBuffer q;
11425         PQExpBuffer delqry;
11426         PQExpBuffer asPart;
11427         PGresult   *res;
11428         char       *funcsig;            /* identity signature */
11429         char       *funcfullsig = NULL; /* full signature */
11430         char       *funcsig_tag;
11431         char       *proretset;
11432         char       *prosrc;
11433         char       *probin;
11434         char       *funcargs;
11435         char       *funciargs;
11436         char       *funcresult;
11437         char       *proallargtypes;
11438         char       *proargmodes;
11439         char       *proargnames;
11440         char       *protrftypes;
11441         char       *prokind;
11442         char       *provolatile;
11443         char       *proisstrict;
11444         char       *prosecdef;
11445         char       *proleakproof;
11446         char       *proconfig;
11447         char       *procost;
11448         char       *prorows;
11449         char       *proparallel;
11450         char       *lanname;
11451         char       *rettypename;
11452         int                     nallargs;
11453         char      **allargtypes = NULL;
11454         char      **argmodes = NULL;
11455         char      **argnames = NULL;
11456         char      **configitems = NULL;
11457         int                     nconfigitems = 0;
11458         const char *keyword;
11459         int                     i;
11460
11461         /* Skip if not to be dumped */
11462         if (!finfo->dobj.dump || dopt->dataOnly)
11463                 return;
11464
11465         query = createPQExpBuffer();
11466         q = createPQExpBuffer();
11467         delqry = createPQExpBuffer();
11468         asPart = createPQExpBuffer();
11469
11470         /* Fetch function-specific details */
11471         if (fout->remoteVersion >= 110000)
11472         {
11473                 /*
11474                  * prokind was added in 11
11475                  */
11476                 appendPQExpBuffer(query,
11477                                                   "SELECT proretset, prosrc, probin, "
11478                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11479                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11480                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11481                                                   "array_to_string(protrftypes, ' ') AS protrftypes, "
11482                                                   "prokind, provolatile, proisstrict, prosecdef, "
11483                                                   "proleakproof, proconfig, procost, prorows, "
11484                                                   "proparallel, "
11485                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11486                                                   "FROM pg_catalog.pg_proc "
11487                                                   "WHERE oid = '%u'::pg_catalog.oid",
11488                                                   finfo->dobj.catId.oid);
11489         }
11490         else if (fout->remoteVersion >= 90600)
11491         {
11492                 /*
11493                  * proparallel was added in 9.6
11494                  */
11495                 appendPQExpBuffer(query,
11496                                                   "SELECT proretset, prosrc, probin, "
11497                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11498                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11499                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11500                                                   "array_to_string(protrftypes, ' ') AS protrftypes, "
11501                                                   "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11502                                                   "provolatile, proisstrict, prosecdef, "
11503                                                   "proleakproof, proconfig, procost, prorows, "
11504                                                   "proparallel, "
11505                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11506                                                   "FROM pg_catalog.pg_proc "
11507                                                   "WHERE oid = '%u'::pg_catalog.oid",
11508                                                   finfo->dobj.catId.oid);
11509         }
11510         else if (fout->remoteVersion >= 90500)
11511         {
11512                 /*
11513                  * protrftypes was added in 9.5
11514                  */
11515                 appendPQExpBuffer(query,
11516                                                   "SELECT proretset, prosrc, probin, "
11517                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11518                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11519                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11520                                                   "array_to_string(protrftypes, ' ') AS protrftypes, "
11521                                                   "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11522                                                   "provolatile, proisstrict, prosecdef, "
11523                                                   "proleakproof, proconfig, procost, prorows, "
11524                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11525                                                   "FROM pg_catalog.pg_proc "
11526                                                   "WHERE oid = '%u'::pg_catalog.oid",
11527                                                   finfo->dobj.catId.oid);
11528         }
11529         else if (fout->remoteVersion >= 90200)
11530         {
11531                 /*
11532                  * proleakproof was added in 9.2
11533                  */
11534                 appendPQExpBuffer(query,
11535                                                   "SELECT proretset, prosrc, probin, "
11536                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11537                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11538                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11539                                                   "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11540                                                   "provolatile, proisstrict, prosecdef, "
11541                                                   "proleakproof, proconfig, procost, prorows, "
11542                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11543                                                   "FROM pg_catalog.pg_proc "
11544                                                   "WHERE oid = '%u'::pg_catalog.oid",
11545                                                   finfo->dobj.catId.oid);
11546         }
11547         else if (fout->remoteVersion >= 80400)
11548         {
11549                 /*
11550                  * In 8.4 and up we rely on pg_get_function_arguments and
11551                  * pg_get_function_result instead of examining proallargtypes etc.
11552                  */
11553                 appendPQExpBuffer(query,
11554                                                   "SELECT proretset, prosrc, probin, "
11555                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11556                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11557                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11558                                                   "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11559                                                   "provolatile, proisstrict, prosecdef, "
11560                                                   "false AS proleakproof, "
11561                                                   " proconfig, procost, prorows, "
11562                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11563                                                   "FROM pg_catalog.pg_proc "
11564                                                   "WHERE oid = '%u'::pg_catalog.oid",
11565                                                   finfo->dobj.catId.oid);
11566         }
11567         else if (fout->remoteVersion >= 80300)
11568         {
11569                 appendPQExpBuffer(query,
11570                                                   "SELECT proretset, prosrc, probin, "
11571                                                   "proallargtypes, proargmodes, proargnames, "
11572                                                   "'f' AS prokind, "
11573                                                   "provolatile, proisstrict, prosecdef, "
11574                                                   "false AS proleakproof, "
11575                                                   "proconfig, procost, prorows, "
11576                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11577                                                   "FROM pg_catalog.pg_proc "
11578                                                   "WHERE oid = '%u'::pg_catalog.oid",
11579                                                   finfo->dobj.catId.oid);
11580         }
11581         else if (fout->remoteVersion >= 80100)
11582         {
11583                 appendPQExpBuffer(query,
11584                                                   "SELECT proretset, prosrc, probin, "
11585                                                   "proallargtypes, proargmodes, proargnames, "
11586                                                   "'f' AS prokind, "
11587                                                   "provolatile, proisstrict, prosecdef, "
11588                                                   "false AS proleakproof, "
11589                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
11590                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11591                                                   "FROM pg_catalog.pg_proc "
11592                                                   "WHERE oid = '%u'::pg_catalog.oid",
11593                                                   finfo->dobj.catId.oid);
11594         }
11595         else
11596         {
11597                 appendPQExpBuffer(query,
11598                                                   "SELECT proretset, prosrc, probin, "
11599                                                   "null AS proallargtypes, "
11600                                                   "null AS proargmodes, "
11601                                                   "proargnames, "
11602                                                   "'f' AS prokind, "
11603                                                   "provolatile, proisstrict, prosecdef, "
11604                                                   "false AS proleakproof, "
11605                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
11606                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11607                                                   "FROM pg_catalog.pg_proc "
11608                                                   "WHERE oid = '%u'::pg_catalog.oid",
11609                                                   finfo->dobj.catId.oid);
11610         }
11611
11612         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11613
11614         proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
11615         prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
11616         probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
11617         if (fout->remoteVersion >= 80400)
11618         {
11619                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
11620                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
11621                 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
11622                 proallargtypes = proargmodes = proargnames = NULL;
11623         }
11624         else
11625         {
11626                 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
11627                 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
11628                 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
11629                 funcargs = funciargs = funcresult = NULL;
11630         }
11631         if (PQfnumber(res, "protrftypes") != -1)
11632                 protrftypes = PQgetvalue(res, 0, PQfnumber(res, "protrftypes"));
11633         else
11634                 protrftypes = NULL;
11635         prokind = PQgetvalue(res, 0, PQfnumber(res, "prokind"));
11636         provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
11637         proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
11638         prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
11639         proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
11640         proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
11641         procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
11642         prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
11643
11644         if (PQfnumber(res, "proparallel") != -1)
11645                 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
11646         else
11647                 proparallel = NULL;
11648
11649         lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
11650
11651         /*
11652          * See backend/commands/functioncmds.c for details of how the 'AS' clause
11653          * is used.  In 8.4 and up, an unused probin is NULL (here ""); previous
11654          * versions would set it to "-".  There are no known cases in which prosrc
11655          * is unused, so the tests below for "-" are probably useless.
11656          */
11657         if (probin[0] != '\0' && strcmp(probin, "-") != 0)
11658         {
11659                 appendPQExpBufferStr(asPart, "AS ");
11660                 appendStringLiteralAH(asPart, probin, fout);
11661                 if (strcmp(prosrc, "-") != 0)
11662                 {
11663                         appendPQExpBufferStr(asPart, ", ");
11664
11665                         /*
11666                          * where we have bin, use dollar quoting if allowed and src
11667                          * contains quote or backslash; else use regular quoting.
11668                          */
11669                         if (dopt->disable_dollar_quoting ||
11670                                 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
11671                                 appendStringLiteralAH(asPart, prosrc, fout);
11672                         else
11673                                 appendStringLiteralDQ(asPart, prosrc, NULL);
11674                 }
11675         }
11676         else
11677         {
11678                 if (strcmp(prosrc, "-") != 0)
11679                 {
11680                         appendPQExpBufferStr(asPart, "AS ");
11681                         /* with no bin, dollar quote src unconditionally if allowed */
11682                         if (dopt->disable_dollar_quoting)
11683                                 appendStringLiteralAH(asPart, prosrc, fout);
11684                         else
11685                                 appendStringLiteralDQ(asPart, prosrc, NULL);
11686                 }
11687         }
11688
11689         nallargs = finfo->nargs;        /* unless we learn different from allargs */
11690
11691         if (proallargtypes && *proallargtypes)
11692         {
11693                 int                     nitems = 0;
11694
11695                 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
11696                         nitems < finfo->nargs)
11697                 {
11698                         write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
11699                         if (allargtypes)
11700                                 free(allargtypes);
11701                         allargtypes = NULL;
11702                 }
11703                 else
11704                         nallargs = nitems;
11705         }
11706
11707         if (proargmodes && *proargmodes)
11708         {
11709                 int                     nitems = 0;
11710
11711                 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
11712                         nitems != nallargs)
11713                 {
11714                         write_msg(NULL, "WARNING: could not parse proargmodes array\n");
11715                         if (argmodes)
11716                                 free(argmodes);
11717                         argmodes = NULL;
11718                 }
11719         }
11720
11721         if (proargnames && *proargnames)
11722         {
11723                 int                     nitems = 0;
11724
11725                 if (!parsePGArray(proargnames, &argnames, &nitems) ||
11726                         nitems != nallargs)
11727                 {
11728                         write_msg(NULL, "WARNING: could not parse proargnames array\n");
11729                         if (argnames)
11730                                 free(argnames);
11731                         argnames = NULL;
11732                 }
11733         }
11734
11735         if (proconfig && *proconfig)
11736         {
11737                 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
11738                 {
11739                         write_msg(NULL, "WARNING: could not parse proconfig array\n");
11740                         if (configitems)
11741                                 free(configitems);
11742                         configitems = NULL;
11743                         nconfigitems = 0;
11744                 }
11745         }
11746
11747         if (funcargs)
11748         {
11749                 /* 8.4 or later; we rely on server-side code for most of the work */
11750                 funcfullsig = format_function_arguments(finfo, funcargs, false);
11751                 funcsig = format_function_arguments(finfo, funciargs, false);
11752         }
11753         else
11754                 /* pre-8.4, do it ourselves */
11755                 funcsig = format_function_arguments_old(fout,
11756                                                                                                 finfo, nallargs, allargtypes,
11757                                                                                                 argmodes, argnames);
11758
11759         funcsig_tag = format_function_signature(fout, finfo, false);
11760
11761         if (prokind[0] == PROKIND_PROCEDURE)
11762                 keyword = "PROCEDURE";
11763         else
11764                 keyword = "FUNCTION";   /* works for window functions too */
11765
11766         appendPQExpBuffer(delqry, "DROP %s %s.%s;\n",
11767                                           keyword,
11768                                           fmtId(finfo->dobj.namespace->dobj.name),
11769                                           funcsig);
11770
11771         appendPQExpBuffer(q, "CREATE %s %s.%s",
11772                                           keyword,
11773                                           fmtId(finfo->dobj.namespace->dobj.name),
11774                                           funcfullsig ? funcfullsig :
11775                                           funcsig);
11776
11777         if (prokind[0] == PROKIND_PROCEDURE)
11778                  /* no result type to output */ ;
11779         else if (funcresult)
11780                 appendPQExpBuffer(q, " RETURNS %s", funcresult);
11781         else
11782         {
11783                 rettypename = getFormattedTypeName(fout, finfo->prorettype,
11784                                                                                    zeroAsOpaque);
11785                 appendPQExpBuffer(q, " RETURNS %s%s",
11786                                                   (proretset[0] == 't') ? "SETOF " : "",
11787                                                   rettypename);
11788                 free(rettypename);
11789         }
11790
11791         appendPQExpBuffer(q, "\n    LANGUAGE %s", fmtId(lanname));
11792
11793         if (protrftypes != NULL && strcmp(protrftypes, "") != 0)
11794         {
11795                 Oid                *typeids = palloc(FUNC_MAX_ARGS * sizeof(Oid));
11796                 int                     i;
11797
11798                 appendPQExpBufferStr(q, " TRANSFORM ");
11799                 parseOidArray(protrftypes, typeids, FUNC_MAX_ARGS);
11800                 for (i = 0; typeids[i]; i++)
11801                 {
11802                         if (i != 0)
11803                                 appendPQExpBufferStr(q, ", ");
11804                         appendPQExpBuffer(q, "FOR TYPE %s",
11805                                                           getFormattedTypeName(fout, typeids[i], zeroAsNone));
11806                 }
11807         }
11808
11809         if (prokind[0] == PROKIND_WINDOW)
11810                 appendPQExpBufferStr(q, " WINDOW");
11811
11812         if (provolatile[0] != PROVOLATILE_VOLATILE)
11813         {
11814                 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
11815                         appendPQExpBufferStr(q, " IMMUTABLE");
11816                 else if (provolatile[0] == PROVOLATILE_STABLE)
11817                         appendPQExpBufferStr(q, " STABLE");
11818                 else if (provolatile[0] != PROVOLATILE_VOLATILE)
11819                         exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
11820                                                   finfo->dobj.name);
11821         }
11822
11823         if (proisstrict[0] == 't')
11824                 appendPQExpBufferStr(q, " STRICT");
11825
11826         if (prosecdef[0] == 't')
11827                 appendPQExpBufferStr(q, " SECURITY DEFINER");
11828
11829         if (proleakproof[0] == 't')
11830                 appendPQExpBufferStr(q, " LEAKPROOF");
11831
11832         /*
11833          * COST and ROWS are emitted only if present and not default, so as not to
11834          * break backwards-compatibility of the dump without need.  Keep this code
11835          * in sync with the defaults in functioncmds.c.
11836          */
11837         if (strcmp(procost, "0") != 0)
11838         {
11839                 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
11840                 {
11841                         /* default cost is 1 */
11842                         if (strcmp(procost, "1") != 0)
11843                                 appendPQExpBuffer(q, " COST %s", procost);
11844                 }
11845                 else
11846                 {
11847                         /* default cost is 100 */
11848                         if (strcmp(procost, "100") != 0)
11849                                 appendPQExpBuffer(q, " COST %s", procost);
11850                 }
11851         }
11852         if (proretset[0] == 't' &&
11853                 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
11854                 appendPQExpBuffer(q, " ROWS %s", prorows);
11855
11856         if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
11857         {
11858                 if (proparallel[0] == PROPARALLEL_SAFE)
11859                         appendPQExpBufferStr(q, " PARALLEL SAFE");
11860                 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
11861                         appendPQExpBufferStr(q, " PARALLEL RESTRICTED");
11862                 else if (proparallel[0] != PROPARALLEL_UNSAFE)
11863                         exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
11864                                                   finfo->dobj.name);
11865         }
11866
11867         for (i = 0; i < nconfigitems; i++)
11868         {
11869                 /* we feel free to scribble on configitems[] here */
11870                 char       *configitem = configitems[i];
11871                 char       *pos;
11872
11873                 pos = strchr(configitem, '=');
11874                 if (pos == NULL)
11875                         continue;
11876                 *pos++ = '\0';
11877                 appendPQExpBuffer(q, "\n    SET %s TO ", fmtId(configitem));
11878
11879                 /*
11880                  * Variables that are marked GUC_LIST_QUOTE were already fully quoted
11881                  * by flatten_set_variable_args() before they were put into the
11882                  * proconfig array; we mustn't re-quote them or we'll make a mess.
11883                  * Variables that are not so marked should just be emitted as simple
11884                  * string literals.  If the variable is not known to
11885                  * variable_is_guc_list_quote(), we'll do the latter; this makes it
11886                  * unsafe to use GUC_LIST_QUOTE for extension variables.
11887                  */
11888                 if (variable_is_guc_list_quote(configitem))
11889                         appendPQExpBufferStr(q, pos);
11890                 else
11891                         appendStringLiteralAH(q, pos, fout);
11892         }
11893
11894         appendPQExpBuffer(q, "\n    %s;\n", asPart->data);
11895
11896         if (dopt->binary_upgrade)
11897                 binary_upgrade_extension_member(q, &finfo->dobj,
11898                                                                                 keyword, funcsig,
11899                                                                                 finfo->dobj.namespace->dobj.name);
11900
11901         if (finfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11902                 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
11903                                          funcsig_tag,
11904                                          finfo->dobj.namespace->dobj.name,
11905                                          NULL,
11906                                          finfo->rolname, false,
11907                                          keyword, SECTION_PRE_DATA,
11908                                          q->data, delqry->data, NULL,
11909                                          NULL, 0,
11910                                          NULL, NULL);
11911
11912         /* Dump Function Comments and Security Labels */
11913         if (finfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11914                 dumpComment(fout, keyword, funcsig,
11915                                         finfo->dobj.namespace->dobj.name, finfo->rolname,
11916                                         finfo->dobj.catId, 0, finfo->dobj.dumpId);
11917
11918         if (finfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11919                 dumpSecLabel(fout, keyword, funcsig,
11920                                          finfo->dobj.namespace->dobj.name, finfo->rolname,
11921                                          finfo->dobj.catId, 0, finfo->dobj.dumpId);
11922
11923         if (finfo->dobj.dump & DUMP_COMPONENT_ACL)
11924                 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, keyword,
11925                                 funcsig, NULL,
11926                                 finfo->dobj.namespace->dobj.name,
11927                                 finfo->rolname, finfo->proacl, finfo->rproacl,
11928                                 finfo->initproacl, finfo->initrproacl);
11929
11930         PQclear(res);
11931
11932         destroyPQExpBuffer(query);
11933         destroyPQExpBuffer(q);
11934         destroyPQExpBuffer(delqry);
11935         destroyPQExpBuffer(asPart);
11936         free(funcsig);
11937         if (funcfullsig)
11938                 free(funcfullsig);
11939         free(funcsig_tag);
11940         if (allargtypes)
11941                 free(allargtypes);
11942         if (argmodes)
11943                 free(argmodes);
11944         if (argnames)
11945                 free(argnames);
11946         if (configitems)
11947                 free(configitems);
11948 }
11949
11950
11951 /*
11952  * Dump a user-defined cast
11953  */
11954 static void
11955 dumpCast(Archive *fout, CastInfo *cast)
11956 {
11957         DumpOptions *dopt = fout->dopt;
11958         PQExpBuffer defqry;
11959         PQExpBuffer delqry;
11960         PQExpBuffer labelq;
11961         PQExpBuffer castargs;
11962         FuncInfo   *funcInfo = NULL;
11963         char       *sourceType;
11964         char       *targetType;
11965
11966         /* Skip if not to be dumped */
11967         if (!cast->dobj.dump || dopt->dataOnly)
11968                 return;
11969
11970         /* Cannot dump if we don't have the cast function's info */
11971         if (OidIsValid(cast->castfunc))
11972         {
11973                 funcInfo = findFuncByOid(cast->castfunc);
11974                 if (funcInfo == NULL)
11975                         exit_horribly(NULL, "could not find function definition for function with OID %u\n",
11976                                                   cast->castfunc);
11977         }
11978
11979         defqry = createPQExpBuffer();
11980         delqry = createPQExpBuffer();
11981         labelq = createPQExpBuffer();
11982         castargs = createPQExpBuffer();
11983
11984         sourceType = getFormattedTypeName(fout, cast->castsource, zeroAsNone);
11985         targetType = getFormattedTypeName(fout, cast->casttarget, zeroAsNone);
11986         appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
11987                                           sourceType, targetType);
11988
11989         appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
11990                                           sourceType, targetType);
11991
11992         switch (cast->castmethod)
11993         {
11994                 case COERCION_METHOD_BINARY:
11995                         appendPQExpBufferStr(defqry, "WITHOUT FUNCTION");
11996                         break;
11997                 case COERCION_METHOD_INOUT:
11998                         appendPQExpBufferStr(defqry, "WITH INOUT");
11999                         break;
12000                 case COERCION_METHOD_FUNCTION:
12001                         if (funcInfo)
12002                         {
12003                                 char       *fsig = format_function_signature(fout, funcInfo, true);
12004
12005                                 /*
12006                                  * Always qualify the function name (format_function_signature
12007                                  * won't qualify it).
12008                                  */
12009                                 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
12010                                                                   fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
12011                                 free(fsig);
12012                         }
12013                         else
12014                                 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
12015                         break;
12016                 default:
12017                         write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
12018         }
12019
12020         if (cast->castcontext == 'a')
12021                 appendPQExpBufferStr(defqry, " AS ASSIGNMENT");
12022         else if (cast->castcontext == 'i')
12023                 appendPQExpBufferStr(defqry, " AS IMPLICIT");
12024         appendPQExpBufferStr(defqry, ";\n");
12025
12026         appendPQExpBuffer(labelq, "CAST (%s AS %s)",
12027                                           sourceType, targetType);
12028
12029         appendPQExpBuffer(castargs, "(%s AS %s)",
12030                                           sourceType, targetType);
12031
12032         if (dopt->binary_upgrade)
12033                 binary_upgrade_extension_member(defqry, &cast->dobj,
12034                                                                                 "CAST", castargs->data, NULL);
12035
12036         if (cast->dobj.dump & DUMP_COMPONENT_DEFINITION)
12037                 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
12038                                          labelq->data,
12039                                          NULL, NULL, "",
12040                                          false, "CAST", SECTION_PRE_DATA,
12041                                          defqry->data, delqry->data, NULL,
12042                                          NULL, 0,
12043                                          NULL, NULL);
12044
12045         /* Dump Cast Comments */
12046         if (cast->dobj.dump & DUMP_COMPONENT_COMMENT)
12047                 dumpComment(fout, "CAST", castargs->data,
12048                                         NULL, "",
12049                                         cast->dobj.catId, 0, cast->dobj.dumpId);
12050
12051         free(sourceType);
12052         free(targetType);
12053
12054         destroyPQExpBuffer(defqry);
12055         destroyPQExpBuffer(delqry);
12056         destroyPQExpBuffer(labelq);
12057         destroyPQExpBuffer(castargs);
12058 }
12059
12060 /*
12061  * Dump a transform
12062  */
12063 static void
12064 dumpTransform(Archive *fout, TransformInfo *transform)
12065 {
12066         DumpOptions *dopt = fout->dopt;
12067         PQExpBuffer defqry;
12068         PQExpBuffer delqry;
12069         PQExpBuffer labelq;
12070         PQExpBuffer transformargs;
12071         FuncInfo   *fromsqlFuncInfo = NULL;
12072         FuncInfo   *tosqlFuncInfo = NULL;
12073         char       *lanname;
12074         char       *transformType;
12075
12076         /* Skip if not to be dumped */
12077         if (!transform->dobj.dump || dopt->dataOnly)
12078                 return;
12079
12080         /* Cannot dump if we don't have the transform functions' info */
12081         if (OidIsValid(transform->trffromsql))
12082         {
12083                 fromsqlFuncInfo = findFuncByOid(transform->trffromsql);
12084                 if (fromsqlFuncInfo == NULL)
12085                         exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12086                                                   transform->trffromsql);
12087         }
12088         if (OidIsValid(transform->trftosql))
12089         {
12090                 tosqlFuncInfo = findFuncByOid(transform->trftosql);
12091                 if (tosqlFuncInfo == NULL)
12092                         exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12093                                                   transform->trftosql);
12094         }
12095
12096         defqry = createPQExpBuffer();
12097         delqry = createPQExpBuffer();
12098         labelq = createPQExpBuffer();
12099         transformargs = createPQExpBuffer();
12100
12101         lanname = get_language_name(fout, transform->trflang);
12102         transformType = getFormattedTypeName(fout, transform->trftype, zeroAsNone);
12103
12104         appendPQExpBuffer(delqry, "DROP TRANSFORM FOR %s LANGUAGE %s;\n",
12105                                           transformType, lanname);
12106
12107         appendPQExpBuffer(defqry, "CREATE TRANSFORM FOR %s LANGUAGE %s (",
12108                                           transformType, lanname);
12109
12110         if (!transform->trffromsql && !transform->trftosql)
12111                 write_msg(NULL, "WARNING: bogus transform definition, at least one of trffromsql and trftosql should be nonzero\n");
12112
12113         if (transform->trffromsql)
12114         {
12115                 if (fromsqlFuncInfo)
12116                 {
12117                         char       *fsig = format_function_signature(fout, fromsqlFuncInfo, true);
12118
12119                         /*
12120                          * Always qualify the function name (format_function_signature
12121                          * won't qualify it).
12122                          */
12123                         appendPQExpBuffer(defqry, "FROM SQL WITH FUNCTION %s.%s",
12124                                                           fmtId(fromsqlFuncInfo->dobj.namespace->dobj.name), fsig);
12125                         free(fsig);
12126                 }
12127                 else
12128                         write_msg(NULL, "WARNING: bogus value in pg_transform.trffromsql field\n");
12129         }
12130
12131         if (transform->trftosql)
12132         {
12133                 if (transform->trffromsql)
12134                         appendPQExpBuffer(defqry, ", ");
12135
12136                 if (tosqlFuncInfo)
12137                 {
12138                         char       *fsig = format_function_signature(fout, tosqlFuncInfo, true);
12139
12140                         /*
12141                          * Always qualify the function name (format_function_signature
12142                          * won't qualify it).
12143                          */
12144                         appendPQExpBuffer(defqry, "TO SQL WITH FUNCTION %s.%s",
12145                                                           fmtId(tosqlFuncInfo->dobj.namespace->dobj.name), fsig);
12146                         free(fsig);
12147                 }
12148                 else
12149                         write_msg(NULL, "WARNING: bogus value in pg_transform.trftosql field\n");
12150         }
12151
12152         appendPQExpBuffer(defqry, ");\n");
12153
12154         appendPQExpBuffer(labelq, "TRANSFORM FOR %s LANGUAGE %s",
12155                                           transformType, lanname);
12156
12157         appendPQExpBuffer(transformargs, "FOR %s LANGUAGE %s",
12158                                           transformType, lanname);
12159
12160         if (dopt->binary_upgrade)
12161                 binary_upgrade_extension_member(defqry, &transform->dobj,
12162                                                                                 "TRANSFORM", transformargs->data, NULL);
12163
12164         if (transform->dobj.dump & DUMP_COMPONENT_DEFINITION)
12165                 ArchiveEntry(fout, transform->dobj.catId, transform->dobj.dumpId,
12166                                          labelq->data,
12167                                          NULL, NULL, "",
12168                                          false, "TRANSFORM", SECTION_PRE_DATA,
12169                                          defqry->data, delqry->data, NULL,
12170                                          transform->dobj.dependencies, transform->dobj.nDeps,
12171                                          NULL, NULL);
12172
12173         /* Dump Transform Comments */
12174         if (transform->dobj.dump & DUMP_COMPONENT_COMMENT)
12175                 dumpComment(fout, "TRANSFORM", transformargs->data,
12176                                         NULL, "",
12177                                         transform->dobj.catId, 0, transform->dobj.dumpId);
12178
12179         free(lanname);
12180         free(transformType);
12181         destroyPQExpBuffer(defqry);
12182         destroyPQExpBuffer(delqry);
12183         destroyPQExpBuffer(labelq);
12184         destroyPQExpBuffer(transformargs);
12185 }
12186
12187
12188 /*
12189  * dumpOpr
12190  *        write out a single operator definition
12191  */
12192 static void
12193 dumpOpr(Archive *fout, OprInfo *oprinfo)
12194 {
12195         DumpOptions *dopt = fout->dopt;
12196         PQExpBuffer query;
12197         PQExpBuffer q;
12198         PQExpBuffer delq;
12199         PQExpBuffer oprid;
12200         PQExpBuffer details;
12201         PGresult   *res;
12202         int                     i_oprkind;
12203         int                     i_oprcode;
12204         int                     i_oprleft;
12205         int                     i_oprright;
12206         int                     i_oprcom;
12207         int                     i_oprnegate;
12208         int                     i_oprrest;
12209         int                     i_oprjoin;
12210         int                     i_oprcanmerge;
12211         int                     i_oprcanhash;
12212         char       *oprkind;
12213         char       *oprcode;
12214         char       *oprleft;
12215         char       *oprright;
12216         char       *oprcom;
12217         char       *oprnegate;
12218         char       *oprrest;
12219         char       *oprjoin;
12220         char       *oprcanmerge;
12221         char       *oprcanhash;
12222         char       *oprregproc;
12223         char       *oprref;
12224
12225         /* Skip if not to be dumped */
12226         if (!oprinfo->dobj.dump || dopt->dataOnly)
12227                 return;
12228
12229         /*
12230          * some operators are invalid because they were the result of user
12231          * defining operators before commutators exist
12232          */
12233         if (!OidIsValid(oprinfo->oprcode))
12234                 return;
12235
12236         query = createPQExpBuffer();
12237         q = createPQExpBuffer();
12238         delq = createPQExpBuffer();
12239         oprid = createPQExpBuffer();
12240         details = createPQExpBuffer();
12241
12242         if (fout->remoteVersion >= 80300)
12243         {
12244                 appendPQExpBuffer(query, "SELECT oprkind, "
12245                                                   "oprcode::pg_catalog.regprocedure, "
12246                                                   "oprleft::pg_catalog.regtype, "
12247                                                   "oprright::pg_catalog.regtype, "
12248                                                   "oprcom, "
12249                                                   "oprnegate, "
12250                                                   "oprrest::pg_catalog.regprocedure, "
12251                                                   "oprjoin::pg_catalog.regprocedure, "
12252                                                   "oprcanmerge, oprcanhash "
12253                                                   "FROM pg_catalog.pg_operator "
12254                                                   "WHERE oid = '%u'::pg_catalog.oid",
12255                                                   oprinfo->dobj.catId.oid);
12256         }
12257         else
12258         {
12259                 appendPQExpBuffer(query, "SELECT oprkind, "
12260                                                   "oprcode::pg_catalog.regprocedure, "
12261                                                   "oprleft::pg_catalog.regtype, "
12262                                                   "oprright::pg_catalog.regtype, "
12263                                                   "oprcom, "
12264                                                   "oprnegate, "
12265                                                   "oprrest::pg_catalog.regprocedure, "
12266                                                   "oprjoin::pg_catalog.regprocedure, "
12267                                                   "(oprlsortop != 0) AS oprcanmerge, "
12268                                                   "oprcanhash "
12269                                                   "FROM pg_catalog.pg_operator "
12270                                                   "WHERE oid = '%u'::pg_catalog.oid",
12271                                                   oprinfo->dobj.catId.oid);
12272         }
12273
12274         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12275
12276         i_oprkind = PQfnumber(res, "oprkind");
12277         i_oprcode = PQfnumber(res, "oprcode");
12278         i_oprleft = PQfnumber(res, "oprleft");
12279         i_oprright = PQfnumber(res, "oprright");
12280         i_oprcom = PQfnumber(res, "oprcom");
12281         i_oprnegate = PQfnumber(res, "oprnegate");
12282         i_oprrest = PQfnumber(res, "oprrest");
12283         i_oprjoin = PQfnumber(res, "oprjoin");
12284         i_oprcanmerge = PQfnumber(res, "oprcanmerge");
12285         i_oprcanhash = PQfnumber(res, "oprcanhash");
12286
12287         oprkind = PQgetvalue(res, 0, i_oprkind);
12288         oprcode = PQgetvalue(res, 0, i_oprcode);
12289         oprleft = PQgetvalue(res, 0, i_oprleft);
12290         oprright = PQgetvalue(res, 0, i_oprright);
12291         oprcom = PQgetvalue(res, 0, i_oprcom);
12292         oprnegate = PQgetvalue(res, 0, i_oprnegate);
12293         oprrest = PQgetvalue(res, 0, i_oprrest);
12294         oprjoin = PQgetvalue(res, 0, i_oprjoin);
12295         oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
12296         oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
12297
12298         oprregproc = convertRegProcReference(fout, oprcode);
12299         if (oprregproc)
12300         {
12301                 appendPQExpBuffer(details, "    PROCEDURE = %s", oprregproc);
12302                 free(oprregproc);
12303         }
12304
12305         appendPQExpBuffer(oprid, "%s (",
12306                                           oprinfo->dobj.name);
12307
12308         /*
12309          * right unary means there's a left arg and left unary means there's a
12310          * right arg
12311          */
12312         if (strcmp(oprkind, "r") == 0 ||
12313                 strcmp(oprkind, "b") == 0)
12314         {
12315                 appendPQExpBuffer(details, ",\n    LEFTARG = %s", oprleft);
12316                 appendPQExpBufferStr(oprid, oprleft);
12317         }
12318         else
12319                 appendPQExpBufferStr(oprid, "NONE");
12320
12321         if (strcmp(oprkind, "l") == 0 ||
12322                 strcmp(oprkind, "b") == 0)
12323         {
12324                 appendPQExpBuffer(details, ",\n    RIGHTARG = %s", oprright);
12325                 appendPQExpBuffer(oprid, ", %s)", oprright);
12326         }
12327         else
12328                 appendPQExpBufferStr(oprid, ", NONE)");
12329
12330         oprref = getFormattedOperatorName(fout, oprcom);
12331         if (oprref)
12332         {
12333                 appendPQExpBuffer(details, ",\n    COMMUTATOR = %s", oprref);
12334                 free(oprref);
12335         }
12336
12337         oprref = getFormattedOperatorName(fout, oprnegate);
12338         if (oprref)
12339         {
12340                 appendPQExpBuffer(details, ",\n    NEGATOR = %s", oprref);
12341                 free(oprref);
12342         }
12343
12344         if (strcmp(oprcanmerge, "t") == 0)
12345                 appendPQExpBufferStr(details, ",\n    MERGES");
12346
12347         if (strcmp(oprcanhash, "t") == 0)
12348                 appendPQExpBufferStr(details, ",\n    HASHES");
12349
12350         oprregproc = convertRegProcReference(fout, oprrest);
12351         if (oprregproc)
12352         {
12353                 appendPQExpBuffer(details, ",\n    RESTRICT = %s", oprregproc);
12354                 free(oprregproc);
12355         }
12356
12357         oprregproc = convertRegProcReference(fout, oprjoin);
12358         if (oprregproc)
12359         {
12360                 appendPQExpBuffer(details, ",\n    JOIN = %s", oprregproc);
12361                 free(oprregproc);
12362         }
12363
12364         appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
12365                                           fmtId(oprinfo->dobj.namespace->dobj.name),
12366                                           oprid->data);
12367
12368         appendPQExpBuffer(q, "CREATE OPERATOR %s.%s (\n%s\n);\n",
12369                                           fmtId(oprinfo->dobj.namespace->dobj.name),
12370                                           oprinfo->dobj.name, details->data);
12371
12372         if (dopt->binary_upgrade)
12373                 binary_upgrade_extension_member(q, &oprinfo->dobj,
12374                                                                                 "OPERATOR", oprid->data,
12375                                                                                 oprinfo->dobj.namespace->dobj.name);
12376
12377         if (oprinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12378                 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
12379                                          oprinfo->dobj.name,
12380                                          oprinfo->dobj.namespace->dobj.name,
12381                                          NULL,
12382                                          oprinfo->rolname,
12383                                          false, "OPERATOR", SECTION_PRE_DATA,
12384                                          q->data, delq->data, NULL,
12385                                          NULL, 0,
12386                                          NULL, NULL);
12387
12388         /* Dump Operator Comments */
12389         if (oprinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12390                 dumpComment(fout, "OPERATOR", oprid->data,
12391                                         oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
12392                                         oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
12393
12394         PQclear(res);
12395
12396         destroyPQExpBuffer(query);
12397         destroyPQExpBuffer(q);
12398         destroyPQExpBuffer(delq);
12399         destroyPQExpBuffer(oprid);
12400         destroyPQExpBuffer(details);
12401 }
12402
12403 /*
12404  * Convert a function reference obtained from pg_operator
12405  *
12406  * Returns allocated string of what to print, or NULL if function references
12407  * is InvalidOid. Returned string is expected to be free'd by the caller.
12408  *
12409  * The input is a REGPROCEDURE display; we have to strip the argument-types
12410  * part.
12411  */
12412 static char *
12413 convertRegProcReference(Archive *fout, const char *proc)
12414 {
12415         char       *name;
12416         char       *paren;
12417         bool            inquote;
12418
12419         /* In all cases "-" means a null reference */
12420         if (strcmp(proc, "-") == 0)
12421                 return NULL;
12422
12423         name = pg_strdup(proc);
12424         /* find non-double-quoted left paren */
12425         inquote = false;
12426         for (paren = name; *paren; paren++)
12427         {
12428                 if (*paren == '(' && !inquote)
12429                 {
12430                         *paren = '\0';
12431                         break;
12432                 }
12433                 if (*paren == '"')
12434                         inquote = !inquote;
12435         }
12436         return name;
12437 }
12438
12439 /*
12440  * getFormattedOperatorName - retrieve the operator name for the
12441  * given operator OID (presented in string form).
12442  *
12443  * Returns an allocated string, or NULL if the given OID is invalid.
12444  * Caller is responsible for free'ing result string.
12445  *
12446  * What we produce has the format "OPERATOR(schema.oprname)".  This is only
12447  * useful in commands where the operator's argument types can be inferred from
12448  * context.  We always schema-qualify the name, though.  The predecessor to
12449  * this code tried to skip the schema qualification if possible, but that led
12450  * to wrong results in corner cases, such as if an operator and its negator
12451  * are in different schemas.
12452  */
12453 static char *
12454 getFormattedOperatorName(Archive *fout, const char *oproid)
12455 {
12456         OprInfo    *oprInfo;
12457
12458         /* In all cases "0" means a null reference */
12459         if (strcmp(oproid, "0") == 0)
12460                 return NULL;
12461
12462         oprInfo = findOprByOid(atooid(oproid));
12463         if (oprInfo == NULL)
12464         {
12465                 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
12466                                   oproid);
12467                 return NULL;
12468         }
12469
12470         return psprintf("OPERATOR(%s.%s)",
12471                                         fmtId(oprInfo->dobj.namespace->dobj.name),
12472                                         oprInfo->dobj.name);
12473 }
12474
12475 /*
12476  * Convert a function OID obtained from pg_ts_parser or pg_ts_template
12477  *
12478  * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
12479  * argument lists of these functions are predetermined.  Note that the
12480  * caller should ensure we are in the proper schema, because the results
12481  * are search path dependent!
12482  */
12483 static char *
12484 convertTSFunction(Archive *fout, Oid funcOid)
12485 {
12486         char       *result;
12487         char            query[128];
12488         PGresult   *res;
12489
12490         snprintf(query, sizeof(query),
12491                          "SELECT '%u'::pg_catalog.regproc", funcOid);
12492         res = ExecuteSqlQueryForSingleRow(fout, query);
12493
12494         result = pg_strdup(PQgetvalue(res, 0, 0));
12495
12496         PQclear(res);
12497
12498         return result;
12499 }
12500
12501 /*
12502  * dumpAccessMethod
12503  *        write out a single access method definition
12504  */
12505 static void
12506 dumpAccessMethod(Archive *fout, AccessMethodInfo *aminfo)
12507 {
12508         DumpOptions *dopt = fout->dopt;
12509         PQExpBuffer q;
12510         PQExpBuffer delq;
12511         char       *qamname;
12512
12513         /* Skip if not to be dumped */
12514         if (!aminfo->dobj.dump || dopt->dataOnly)
12515                 return;
12516
12517         q = createPQExpBuffer();
12518         delq = createPQExpBuffer();
12519
12520         qamname = pg_strdup(fmtId(aminfo->dobj.name));
12521
12522         appendPQExpBuffer(q, "CREATE ACCESS METHOD %s ", qamname);
12523
12524         switch (aminfo->amtype)
12525         {
12526                 case AMTYPE_INDEX:
12527                         appendPQExpBuffer(q, "TYPE INDEX ");
12528                         break;
12529                 default:
12530                         write_msg(NULL, "WARNING: invalid type \"%c\" of access method \"%s\"\n",
12531                                           aminfo->amtype, qamname);
12532                         destroyPQExpBuffer(q);
12533                         destroyPQExpBuffer(delq);
12534                         free(qamname);
12535                         return;
12536         }
12537
12538         appendPQExpBuffer(q, "HANDLER %s;\n", aminfo->amhandler);
12539
12540         appendPQExpBuffer(delq, "DROP ACCESS METHOD %s;\n",
12541                                           qamname);
12542
12543         if (dopt->binary_upgrade)
12544                 binary_upgrade_extension_member(q, &aminfo->dobj,
12545                                                                                 "ACCESS METHOD", qamname, NULL);
12546
12547         if (aminfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12548                 ArchiveEntry(fout, aminfo->dobj.catId, aminfo->dobj.dumpId,
12549                                          aminfo->dobj.name,
12550                                          NULL,
12551                                          NULL,
12552                                          "",
12553                                          false, "ACCESS METHOD", SECTION_PRE_DATA,
12554                                          q->data, delq->data, NULL,
12555                                          NULL, 0,
12556                                          NULL, NULL);
12557
12558         /* Dump Access Method Comments */
12559         if (aminfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12560                 dumpComment(fout, "ACCESS METHOD", qamname,
12561                                         NULL, "",
12562                                         aminfo->dobj.catId, 0, aminfo->dobj.dumpId);
12563
12564         destroyPQExpBuffer(q);
12565         destroyPQExpBuffer(delq);
12566         free(qamname);
12567 }
12568
12569 /*
12570  * dumpOpclass
12571  *        write out a single operator class definition
12572  */
12573 static void
12574 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
12575 {
12576         DumpOptions *dopt = fout->dopt;
12577         PQExpBuffer query;
12578         PQExpBuffer q;
12579         PQExpBuffer delq;
12580         PQExpBuffer nameusing;
12581         PGresult   *res;
12582         int                     ntups;
12583         int                     i_opcintype;
12584         int                     i_opckeytype;
12585         int                     i_opcdefault;
12586         int                     i_opcfamily;
12587         int                     i_opcfamilyname;
12588         int                     i_opcfamilynsp;
12589         int                     i_amname;
12590         int                     i_amopstrategy;
12591         int                     i_amopreqcheck;
12592         int                     i_amopopr;
12593         int                     i_sortfamily;
12594         int                     i_sortfamilynsp;
12595         int                     i_amprocnum;
12596         int                     i_amproc;
12597         int                     i_amproclefttype;
12598         int                     i_amprocrighttype;
12599         char       *opcintype;
12600         char       *opckeytype;
12601         char       *opcdefault;
12602         char       *opcfamily;
12603         char       *opcfamilyname;
12604         char       *opcfamilynsp;
12605         char       *amname;
12606         char       *amopstrategy;
12607         char       *amopreqcheck;
12608         char       *amopopr;
12609         char       *sortfamily;
12610         char       *sortfamilynsp;
12611         char       *amprocnum;
12612         char       *amproc;
12613         char       *amproclefttype;
12614         char       *amprocrighttype;
12615         bool            needComma;
12616         int                     i;
12617
12618         /* Skip if not to be dumped */
12619         if (!opcinfo->dobj.dump || dopt->dataOnly)
12620                 return;
12621
12622         query = createPQExpBuffer();
12623         q = createPQExpBuffer();
12624         delq = createPQExpBuffer();
12625         nameusing = createPQExpBuffer();
12626
12627         /* Get additional fields from the pg_opclass row */
12628         if (fout->remoteVersion >= 80300)
12629         {
12630                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12631                                                   "opckeytype::pg_catalog.regtype, "
12632                                                   "opcdefault, opcfamily, "
12633                                                   "opfname AS opcfamilyname, "
12634                                                   "nspname AS opcfamilynsp, "
12635                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
12636                                                   "FROM pg_catalog.pg_opclass c "
12637                                                   "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
12638                                                   "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12639                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
12640                                                   opcinfo->dobj.catId.oid);
12641         }
12642         else
12643         {
12644                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12645                                                   "opckeytype::pg_catalog.regtype, "
12646                                                   "opcdefault, NULL AS opcfamily, "
12647                                                   "NULL AS opcfamilyname, "
12648                                                   "NULL AS opcfamilynsp, "
12649                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
12650                                                   "FROM pg_catalog.pg_opclass "
12651                                                   "WHERE oid = '%u'::pg_catalog.oid",
12652                                                   opcinfo->dobj.catId.oid);
12653         }
12654
12655         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12656
12657         i_opcintype = PQfnumber(res, "opcintype");
12658         i_opckeytype = PQfnumber(res, "opckeytype");
12659         i_opcdefault = PQfnumber(res, "opcdefault");
12660         i_opcfamily = PQfnumber(res, "opcfamily");
12661         i_opcfamilyname = PQfnumber(res, "opcfamilyname");
12662         i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
12663         i_amname = PQfnumber(res, "amname");
12664
12665         /* opcintype may still be needed after we PQclear res */
12666         opcintype = pg_strdup(PQgetvalue(res, 0, i_opcintype));
12667         opckeytype = PQgetvalue(res, 0, i_opckeytype);
12668         opcdefault = PQgetvalue(res, 0, i_opcdefault);
12669         /* opcfamily will still be needed after we PQclear res */
12670         opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
12671         opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
12672         opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
12673         /* amname will still be needed after we PQclear res */
12674         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
12675
12676         appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
12677                                           fmtQualifiedDumpable(opcinfo));
12678         appendPQExpBuffer(delq, " USING %s;\n",
12679                                           fmtId(amname));
12680
12681         /* Build the fixed portion of the CREATE command */
12682         appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n    ",
12683                                           fmtQualifiedDumpable(opcinfo));
12684         if (strcmp(opcdefault, "t") == 0)
12685                 appendPQExpBufferStr(q, "DEFAULT ");
12686         appendPQExpBuffer(q, "FOR TYPE %s USING %s",
12687                                           opcintype,
12688                                           fmtId(amname));
12689         if (strlen(opcfamilyname) > 0)
12690         {
12691                 appendPQExpBufferStr(q, " FAMILY ");
12692                 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
12693                 appendPQExpBufferStr(q, fmtId(opcfamilyname));
12694         }
12695         appendPQExpBufferStr(q, " AS\n    ");
12696
12697         needComma = false;
12698
12699         if (strcmp(opckeytype, "-") != 0)
12700         {
12701                 appendPQExpBuffer(q, "STORAGE %s",
12702                                                   opckeytype);
12703                 needComma = true;
12704         }
12705
12706         PQclear(res);
12707
12708         /*
12709          * Now fetch and print the OPERATOR entries (pg_amop rows).
12710          *
12711          * Print only those opfamily members that are tied to the opclass by
12712          * pg_depend entries.
12713          *
12714          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
12715          * older server's opclass in which it is used.  This is to avoid
12716          * hard-to-detect breakage if a newer pg_dump is used to dump from an
12717          * older server and then reload into that old version.  This can go away
12718          * once 8.3 is so old as to not be of interest to anyone.
12719          */
12720         resetPQExpBuffer(query);
12721
12722         if (fout->remoteVersion >= 90100)
12723         {
12724                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12725                                                   "amopopr::pg_catalog.regoperator, "
12726                                                   "opfname AS sortfamily, "
12727                                                   "nspname AS sortfamilynsp "
12728                                                   "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
12729                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
12730                                                   "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
12731                                                   "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12732                                                   "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12733                                                   "AND refobjid = '%u'::pg_catalog.oid "
12734                                                   "AND amopfamily = '%s'::pg_catalog.oid "
12735                                                   "ORDER BY amopstrategy",
12736                                                   opcinfo->dobj.catId.oid,
12737                                                   opcfamily);
12738         }
12739         else if (fout->remoteVersion >= 80400)
12740         {
12741                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12742                                                   "amopopr::pg_catalog.regoperator, "
12743                                                   "NULL AS sortfamily, "
12744                                                   "NULL AS sortfamilynsp "
12745                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12746                                                   "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12747                                                   "AND refobjid = '%u'::pg_catalog.oid "
12748                                                   "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12749                                                   "AND objid = ao.oid "
12750                                                   "ORDER BY amopstrategy",
12751                                                   opcinfo->dobj.catId.oid);
12752         }
12753         else if (fout->remoteVersion >= 80300)
12754         {
12755                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12756                                                   "amopopr::pg_catalog.regoperator, "
12757                                                   "NULL AS sortfamily, "
12758                                                   "NULL AS sortfamilynsp "
12759                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12760                                                   "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12761                                                   "AND refobjid = '%u'::pg_catalog.oid "
12762                                                   "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12763                                                   "AND objid = ao.oid "
12764                                                   "ORDER BY amopstrategy",
12765                                                   opcinfo->dobj.catId.oid);
12766         }
12767         else
12768         {
12769                 /*
12770                  * Here, we print all entries since there are no opfamilies and hence
12771                  * no loose operators to worry about.
12772                  */
12773                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12774                                                   "amopopr::pg_catalog.regoperator, "
12775                                                   "NULL AS sortfamily, "
12776                                                   "NULL AS sortfamilynsp "
12777                                                   "FROM pg_catalog.pg_amop "
12778                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
12779                                                   "ORDER BY amopstrategy",
12780                                                   opcinfo->dobj.catId.oid);
12781         }
12782
12783         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12784
12785         ntups = PQntuples(res);
12786
12787         i_amopstrategy = PQfnumber(res, "amopstrategy");
12788         i_amopreqcheck = PQfnumber(res, "amopreqcheck");
12789         i_amopopr = PQfnumber(res, "amopopr");
12790         i_sortfamily = PQfnumber(res, "sortfamily");
12791         i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
12792
12793         for (i = 0; i < ntups; i++)
12794         {
12795                 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
12796                 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
12797                 amopopr = PQgetvalue(res, i, i_amopopr);
12798                 sortfamily = PQgetvalue(res, i, i_sortfamily);
12799                 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
12800
12801                 if (needComma)
12802                         appendPQExpBufferStr(q, " ,\n    ");
12803
12804                 appendPQExpBuffer(q, "OPERATOR %s %s",
12805                                                   amopstrategy, amopopr);
12806
12807                 if (strlen(sortfamily) > 0)
12808                 {
12809                         appendPQExpBufferStr(q, " FOR ORDER BY ");
12810                         appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
12811                         appendPQExpBufferStr(q, fmtId(sortfamily));
12812                 }
12813
12814                 if (strcmp(amopreqcheck, "t") == 0)
12815                         appendPQExpBufferStr(q, " RECHECK");
12816
12817                 needComma = true;
12818         }
12819
12820         PQclear(res);
12821
12822         /*
12823          * Now fetch and print the FUNCTION entries (pg_amproc rows).
12824          *
12825          * Print only those opfamily members that are tied to the opclass by
12826          * pg_depend entries.
12827          *
12828          * We print the amproclefttype/amprocrighttype even though in most cases
12829          * the backend could deduce the right values, because of the corner case
12830          * of a btree sort support function for a cross-type comparison.  That's
12831          * only allowed in 9.2 and later, but for simplicity print them in all
12832          * versions that have the columns.
12833          */
12834         resetPQExpBuffer(query);
12835
12836         if (fout->remoteVersion >= 80300)
12837         {
12838                 appendPQExpBuffer(query, "SELECT amprocnum, "
12839                                                   "amproc::pg_catalog.regprocedure, "
12840                                                   "amproclefttype::pg_catalog.regtype, "
12841                                                   "amprocrighttype::pg_catalog.regtype "
12842                                                   "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
12843                                                   "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12844                                                   "AND refobjid = '%u'::pg_catalog.oid "
12845                                                   "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
12846                                                   "AND objid = ap.oid "
12847                                                   "ORDER BY amprocnum",
12848                                                   opcinfo->dobj.catId.oid);
12849         }
12850         else
12851         {
12852                 appendPQExpBuffer(query, "SELECT amprocnum, "
12853                                                   "amproc::pg_catalog.regprocedure, "
12854                                                   "'' AS amproclefttype, "
12855                                                   "'' AS amprocrighttype "
12856                                                   "FROM pg_catalog.pg_amproc "
12857                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
12858                                                   "ORDER BY amprocnum",
12859                                                   opcinfo->dobj.catId.oid);
12860         }
12861
12862         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12863
12864         ntups = PQntuples(res);
12865
12866         i_amprocnum = PQfnumber(res, "amprocnum");
12867         i_amproc = PQfnumber(res, "amproc");
12868         i_amproclefttype = PQfnumber(res, "amproclefttype");
12869         i_amprocrighttype = PQfnumber(res, "amprocrighttype");
12870
12871         for (i = 0; i < ntups; i++)
12872         {
12873                 amprocnum = PQgetvalue(res, i, i_amprocnum);
12874                 amproc = PQgetvalue(res, i, i_amproc);
12875                 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
12876                 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
12877
12878                 if (needComma)
12879                         appendPQExpBufferStr(q, " ,\n    ");
12880
12881                 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
12882
12883                 if (*amproclefttype && *amprocrighttype)
12884                         appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
12885
12886                 appendPQExpBuffer(q, " %s", amproc);
12887
12888                 needComma = true;
12889         }
12890
12891         PQclear(res);
12892
12893         /*
12894          * If needComma is still false it means we haven't added anything after
12895          * the AS keyword.  To avoid printing broken SQL, append a dummy STORAGE
12896          * clause with the same datatype.  This isn't sanctioned by the
12897          * documentation, but actually DefineOpClass will treat it as a no-op.
12898          */
12899         if (!needComma)
12900                 appendPQExpBuffer(q, "STORAGE %s", opcintype);
12901
12902         appendPQExpBufferStr(q, ";\n");
12903
12904         appendPQExpBufferStr(nameusing, fmtId(opcinfo->dobj.name));
12905         appendPQExpBuffer(nameusing, " USING %s",
12906                                           fmtId(amname));
12907
12908         if (dopt->binary_upgrade)
12909                 binary_upgrade_extension_member(q, &opcinfo->dobj,
12910                                                                                 "OPERATOR CLASS", nameusing->data,
12911                                                                                 opcinfo->dobj.namespace->dobj.name);
12912
12913         if (opcinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12914                 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
12915                                          opcinfo->dobj.name,
12916                                          opcinfo->dobj.namespace->dobj.name,
12917                                          NULL,
12918                                          opcinfo->rolname,
12919                                          false, "OPERATOR CLASS", SECTION_PRE_DATA,
12920                                          q->data, delq->data, NULL,
12921                                          NULL, 0,
12922                                          NULL, NULL);
12923
12924         /* Dump Operator Class Comments */
12925         if (opcinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12926                 dumpComment(fout, "OPERATOR CLASS", nameusing->data,
12927                                         opcinfo->dobj.namespace->dobj.name, opcinfo->rolname,
12928                                         opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
12929
12930         free(opcintype);
12931         free(opcfamily);
12932         free(amname);
12933         destroyPQExpBuffer(query);
12934         destroyPQExpBuffer(q);
12935         destroyPQExpBuffer(delq);
12936         destroyPQExpBuffer(nameusing);
12937 }
12938
12939 /*
12940  * dumpOpfamily
12941  *        write out a single operator family definition
12942  *
12943  * Note: this also dumps any "loose" operator members that aren't bound to a
12944  * specific opclass within the opfamily.
12945  */
12946 static void
12947 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
12948 {
12949         DumpOptions *dopt = fout->dopt;
12950         PQExpBuffer query;
12951         PQExpBuffer q;
12952         PQExpBuffer delq;
12953         PQExpBuffer nameusing;
12954         PGresult   *res;
12955         PGresult   *res_ops;
12956         PGresult   *res_procs;
12957         int                     ntups;
12958         int                     i_amname;
12959         int                     i_amopstrategy;
12960         int                     i_amopreqcheck;
12961         int                     i_amopopr;
12962         int                     i_sortfamily;
12963         int                     i_sortfamilynsp;
12964         int                     i_amprocnum;
12965         int                     i_amproc;
12966         int                     i_amproclefttype;
12967         int                     i_amprocrighttype;
12968         char       *amname;
12969         char       *amopstrategy;
12970         char       *amopreqcheck;
12971         char       *amopopr;
12972         char       *sortfamily;
12973         char       *sortfamilynsp;
12974         char       *amprocnum;
12975         char       *amproc;
12976         char       *amproclefttype;
12977         char       *amprocrighttype;
12978         bool            needComma;
12979         int                     i;
12980
12981         /* Skip if not to be dumped */
12982         if (!opfinfo->dobj.dump || dopt->dataOnly)
12983                 return;
12984
12985         query = createPQExpBuffer();
12986         q = createPQExpBuffer();
12987         delq = createPQExpBuffer();
12988         nameusing = createPQExpBuffer();
12989
12990         /*
12991          * Fetch only those opfamily members that are tied directly to the
12992          * opfamily by pg_depend entries.
12993          *
12994          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
12995          * older server's opclass in which it is used.  This is to avoid
12996          * hard-to-detect breakage if a newer pg_dump is used to dump from an
12997          * older server and then reload into that old version.  This can go away
12998          * once 8.3 is so old as to not be of interest to anyone.
12999          */
13000         if (fout->remoteVersion >= 90100)
13001         {
13002                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13003                                                   "amopopr::pg_catalog.regoperator, "
13004                                                   "opfname AS sortfamily, "
13005                                                   "nspname AS sortfamilynsp "
13006                                                   "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
13007                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
13008                                                   "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
13009                                                   "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13010                                                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13011                                                   "AND refobjid = '%u'::pg_catalog.oid "
13012                                                   "AND amopfamily = '%u'::pg_catalog.oid "
13013                                                   "ORDER BY amopstrategy",
13014                                                   opfinfo->dobj.catId.oid,
13015                                                   opfinfo->dobj.catId.oid);
13016         }
13017         else if (fout->remoteVersion >= 80400)
13018         {
13019                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13020                                                   "amopopr::pg_catalog.regoperator, "
13021                                                   "NULL AS sortfamily, "
13022                                                   "NULL AS sortfamilynsp "
13023                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13024                                                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13025                                                   "AND refobjid = '%u'::pg_catalog.oid "
13026                                                   "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13027                                                   "AND objid = ao.oid "
13028                                                   "ORDER BY amopstrategy",
13029                                                   opfinfo->dobj.catId.oid);
13030         }
13031         else
13032         {
13033                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
13034                                                   "amopopr::pg_catalog.regoperator, "
13035                                                   "NULL AS sortfamily, "
13036                                                   "NULL AS sortfamilynsp "
13037                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13038                                                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13039                                                   "AND refobjid = '%u'::pg_catalog.oid "
13040                                                   "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13041                                                   "AND objid = ao.oid "
13042                                                   "ORDER BY amopstrategy",
13043                                                   opfinfo->dobj.catId.oid);
13044         }
13045
13046         res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13047
13048         resetPQExpBuffer(query);
13049
13050         appendPQExpBuffer(query, "SELECT amprocnum, "
13051                                           "amproc::pg_catalog.regprocedure, "
13052                                           "amproclefttype::pg_catalog.regtype, "
13053                                           "amprocrighttype::pg_catalog.regtype "
13054                                           "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
13055                                           "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13056                                           "AND refobjid = '%u'::pg_catalog.oid "
13057                                           "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
13058                                           "AND objid = ap.oid "
13059                                           "ORDER BY amprocnum",
13060                                           opfinfo->dobj.catId.oid);
13061
13062         res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13063
13064         /* Get additional fields from the pg_opfamily row */
13065         resetPQExpBuffer(query);
13066
13067         appendPQExpBuffer(query, "SELECT "
13068                                           "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
13069                                           "FROM pg_catalog.pg_opfamily "
13070                                           "WHERE oid = '%u'::pg_catalog.oid",
13071                                           opfinfo->dobj.catId.oid);
13072
13073         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13074
13075         i_amname = PQfnumber(res, "amname");
13076
13077         /* amname will still be needed after we PQclear res */
13078         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
13079
13080         appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
13081                                           fmtQualifiedDumpable(opfinfo));
13082         appendPQExpBuffer(delq, " USING %s;\n",
13083                                           fmtId(amname));
13084
13085         /* Build the fixed portion of the CREATE command */
13086         appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
13087                                           fmtQualifiedDumpable(opfinfo));
13088         appendPQExpBuffer(q, " USING %s;\n",
13089                                           fmtId(amname));
13090
13091         PQclear(res);
13092
13093         /* Do we need an ALTER to add loose members? */
13094         if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
13095         {
13096                 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
13097                                                   fmtQualifiedDumpable(opfinfo));
13098                 appendPQExpBuffer(q, " USING %s ADD\n    ",
13099                                                   fmtId(amname));
13100
13101                 needComma = false;
13102
13103                 /*
13104                  * Now fetch and print the OPERATOR entries (pg_amop rows).
13105                  */
13106                 ntups = PQntuples(res_ops);
13107
13108                 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
13109                 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
13110                 i_amopopr = PQfnumber(res_ops, "amopopr");
13111                 i_sortfamily = PQfnumber(res_ops, "sortfamily");
13112                 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
13113
13114                 for (i = 0; i < ntups; i++)
13115                 {
13116                         amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
13117                         amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
13118                         amopopr = PQgetvalue(res_ops, i, i_amopopr);
13119                         sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
13120                         sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
13121
13122                         if (needComma)
13123                                 appendPQExpBufferStr(q, " ,\n    ");
13124
13125                         appendPQExpBuffer(q, "OPERATOR %s %s",
13126                                                           amopstrategy, amopopr);
13127
13128                         if (strlen(sortfamily) > 0)
13129                         {
13130                                 appendPQExpBufferStr(q, " FOR ORDER BY ");
13131                                 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
13132                                 appendPQExpBufferStr(q, fmtId(sortfamily));
13133                         }
13134
13135                         if (strcmp(amopreqcheck, "t") == 0)
13136                                 appendPQExpBufferStr(q, " RECHECK");
13137
13138                         needComma = true;
13139                 }
13140
13141                 /*
13142                  * Now fetch and print the FUNCTION entries (pg_amproc rows).
13143                  */
13144                 ntups = PQntuples(res_procs);
13145
13146                 i_amprocnum = PQfnumber(res_procs, "amprocnum");
13147                 i_amproc = PQfnumber(res_procs, "amproc");
13148                 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
13149                 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
13150
13151                 for (i = 0; i < ntups; i++)
13152                 {
13153                         amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
13154                         amproc = PQgetvalue(res_procs, i, i_amproc);
13155                         amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
13156                         amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
13157
13158                         if (needComma)
13159                                 appendPQExpBufferStr(q, " ,\n    ");
13160
13161                         appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
13162                                                           amprocnum, amproclefttype, amprocrighttype,
13163                                                           amproc);
13164
13165                         needComma = true;
13166                 }
13167
13168                 appendPQExpBufferStr(q, ";\n");
13169         }
13170
13171         appendPQExpBufferStr(nameusing, fmtId(opfinfo->dobj.name));
13172         appendPQExpBuffer(nameusing, " USING %s",
13173                                           fmtId(amname));
13174
13175         if (dopt->binary_upgrade)
13176                 binary_upgrade_extension_member(q, &opfinfo->dobj,
13177                                                                                 "OPERATOR FAMILY", nameusing->data,
13178                                                                                 opfinfo->dobj.namespace->dobj.name);
13179
13180         if (opfinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13181                 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
13182                                          opfinfo->dobj.name,
13183                                          opfinfo->dobj.namespace->dobj.name,
13184                                          NULL,
13185                                          opfinfo->rolname,
13186                                          false, "OPERATOR FAMILY", SECTION_PRE_DATA,
13187                                          q->data, delq->data, NULL,
13188                                          NULL, 0,
13189                                          NULL, NULL);
13190
13191         /* Dump Operator Family Comments */
13192         if (opfinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13193                 dumpComment(fout, "OPERATOR FAMILY", nameusing->data,
13194                                         opfinfo->dobj.namespace->dobj.name, opfinfo->rolname,
13195                                         opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
13196
13197         free(amname);
13198         PQclear(res_ops);
13199         PQclear(res_procs);
13200         destroyPQExpBuffer(query);
13201         destroyPQExpBuffer(q);
13202         destroyPQExpBuffer(delq);
13203         destroyPQExpBuffer(nameusing);
13204 }
13205
13206 /*
13207  * dumpCollation
13208  *        write out a single collation definition
13209  */
13210 static void
13211 dumpCollation(Archive *fout, CollInfo *collinfo)
13212 {
13213         DumpOptions *dopt = fout->dopt;
13214         PQExpBuffer query;
13215         PQExpBuffer q;
13216         PQExpBuffer delq;
13217         char       *qcollname;
13218         PGresult   *res;
13219         int                     i_collprovider;
13220         int                     i_collcollate;
13221         int                     i_collctype;
13222         const char *collprovider;
13223         const char *collcollate;
13224         const char *collctype;
13225
13226         /* Skip if not to be dumped */
13227         if (!collinfo->dobj.dump || dopt->dataOnly)
13228                 return;
13229
13230         query = createPQExpBuffer();
13231         q = createPQExpBuffer();
13232         delq = createPQExpBuffer();
13233
13234         qcollname = pg_strdup(fmtId(collinfo->dobj.name));
13235
13236         /* Get collation-specific details */
13237         if (fout->remoteVersion >= 100000)
13238                 appendPQExpBuffer(query, "SELECT "
13239                                                   "collprovider, "
13240                                                   "collcollate, "
13241                                                   "collctype, "
13242                                                   "collversion "
13243                                                   "FROM pg_catalog.pg_collation c "
13244                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
13245                                                   collinfo->dobj.catId.oid);
13246         else
13247                 appendPQExpBuffer(query, "SELECT "
13248                                                   "'c' AS collprovider, "
13249                                                   "collcollate, "
13250                                                   "collctype, "
13251                                                   "NULL AS collversion "
13252                                                   "FROM pg_catalog.pg_collation c "
13253                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
13254                                                   collinfo->dobj.catId.oid);
13255
13256         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13257
13258         i_collprovider = PQfnumber(res, "collprovider");
13259         i_collcollate = PQfnumber(res, "collcollate");
13260         i_collctype = PQfnumber(res, "collctype");
13261
13262         collprovider = PQgetvalue(res, 0, i_collprovider);
13263         collcollate = PQgetvalue(res, 0, i_collcollate);
13264         collctype = PQgetvalue(res, 0, i_collctype);
13265
13266         appendPQExpBuffer(delq, "DROP COLLATION %s;\n",
13267                                           fmtQualifiedDumpable(collinfo));
13268
13269         appendPQExpBuffer(q, "CREATE COLLATION %s (",
13270                                           fmtQualifiedDumpable(collinfo));
13271
13272         appendPQExpBufferStr(q, "provider = ");
13273         if (collprovider[0] == 'c')
13274                 appendPQExpBufferStr(q, "libc");
13275         else if (collprovider[0] == 'i')
13276                 appendPQExpBufferStr(q, "icu");
13277         else if (collprovider[0] == 'd')
13278                 /* to allow dumping pg_catalog; not accepted on input */
13279                 appendPQExpBufferStr(q, "default");
13280         else
13281                 exit_horribly(NULL,
13282                                           "unrecognized collation provider: %s\n",
13283                                           collprovider);
13284
13285         if (strcmp(collcollate, collctype) == 0)
13286         {
13287                 appendPQExpBufferStr(q, ", locale = ");
13288                 appendStringLiteralAH(q, collcollate, fout);
13289         }
13290         else
13291         {
13292                 appendPQExpBufferStr(q, ", lc_collate = ");
13293                 appendStringLiteralAH(q, collcollate, fout);
13294                 appendPQExpBufferStr(q, ", lc_ctype = ");
13295                 appendStringLiteralAH(q, collctype, fout);
13296         }
13297
13298         /*
13299          * For binary upgrade, carry over the collation version.  For normal
13300          * dump/restore, omit the version, so that it is computed upon restore.
13301          */
13302         if (dopt->binary_upgrade)
13303         {
13304                 int                     i_collversion;
13305
13306                 i_collversion = PQfnumber(res, "collversion");
13307                 if (!PQgetisnull(res, 0, i_collversion))
13308                 {
13309                         appendPQExpBufferStr(q, ", version = ");
13310                         appendStringLiteralAH(q,
13311                                                                   PQgetvalue(res, 0, i_collversion),
13312                                                                   fout);
13313                 }
13314         }
13315
13316         appendPQExpBufferStr(q, ");\n");
13317
13318         if (dopt->binary_upgrade)
13319                 binary_upgrade_extension_member(q, &collinfo->dobj,
13320                                                                                 "COLLATION", qcollname,
13321                                                                                 collinfo->dobj.namespace->dobj.name);
13322
13323         if (collinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13324                 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
13325                                          collinfo->dobj.name,
13326                                          collinfo->dobj.namespace->dobj.name,
13327                                          NULL,
13328                                          collinfo->rolname,
13329                                          false, "COLLATION", SECTION_PRE_DATA,
13330                                          q->data, delq->data, NULL,
13331                                          NULL, 0,
13332                                          NULL, NULL);
13333
13334         /* Dump Collation Comments */
13335         if (collinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13336                 dumpComment(fout, "COLLATION", qcollname,
13337                                         collinfo->dobj.namespace->dobj.name, collinfo->rolname,
13338                                         collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
13339
13340         PQclear(res);
13341
13342         destroyPQExpBuffer(query);
13343         destroyPQExpBuffer(q);
13344         destroyPQExpBuffer(delq);
13345         free(qcollname);
13346 }
13347
13348 /*
13349  * dumpConversion
13350  *        write out a single conversion definition
13351  */
13352 static void
13353 dumpConversion(Archive *fout, ConvInfo *convinfo)
13354 {
13355         DumpOptions *dopt = fout->dopt;
13356         PQExpBuffer query;
13357         PQExpBuffer q;
13358         PQExpBuffer delq;
13359         char       *qconvname;
13360         PGresult   *res;
13361         int                     i_conforencoding;
13362         int                     i_contoencoding;
13363         int                     i_conproc;
13364         int                     i_condefault;
13365         const char *conforencoding;
13366         const char *contoencoding;
13367         const char *conproc;
13368         bool            condefault;
13369
13370         /* Skip if not to be dumped */
13371         if (!convinfo->dobj.dump || dopt->dataOnly)
13372                 return;
13373
13374         query = createPQExpBuffer();
13375         q = createPQExpBuffer();
13376         delq = createPQExpBuffer();
13377
13378         qconvname = pg_strdup(fmtId(convinfo->dobj.name));
13379
13380         /* Get conversion-specific details */
13381         appendPQExpBuffer(query, "SELECT "
13382                                           "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
13383                                           "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
13384                                           "conproc, condefault "
13385                                           "FROM pg_catalog.pg_conversion c "
13386                                           "WHERE c.oid = '%u'::pg_catalog.oid",
13387                                           convinfo->dobj.catId.oid);
13388
13389         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13390
13391         i_conforencoding = PQfnumber(res, "conforencoding");
13392         i_contoencoding = PQfnumber(res, "contoencoding");
13393         i_conproc = PQfnumber(res, "conproc");
13394         i_condefault = PQfnumber(res, "condefault");
13395
13396         conforencoding = PQgetvalue(res, 0, i_conforencoding);
13397         contoencoding = PQgetvalue(res, 0, i_contoencoding);
13398         conproc = PQgetvalue(res, 0, i_conproc);
13399         condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
13400
13401         appendPQExpBuffer(delq, "DROP CONVERSION %s;\n",
13402                                           fmtQualifiedDumpable(convinfo));
13403
13404         appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
13405                                           (condefault) ? "DEFAULT " : "",
13406                                           fmtQualifiedDumpable(convinfo));
13407         appendStringLiteralAH(q, conforencoding, fout);
13408         appendPQExpBufferStr(q, " TO ");
13409         appendStringLiteralAH(q, contoencoding, fout);
13410         /* regproc output is already sufficiently quoted */
13411         appendPQExpBuffer(q, " FROM %s;\n", conproc);
13412
13413         if (dopt->binary_upgrade)
13414                 binary_upgrade_extension_member(q, &convinfo->dobj,
13415                                                                                 "CONVERSION", qconvname,
13416                                                                                 convinfo->dobj.namespace->dobj.name);
13417
13418         if (convinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13419                 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
13420                                          convinfo->dobj.name,
13421                                          convinfo->dobj.namespace->dobj.name,
13422                                          NULL,
13423                                          convinfo->rolname,
13424                                          false, "CONVERSION", SECTION_PRE_DATA,
13425                                          q->data, delq->data, NULL,
13426                                          NULL, 0,
13427                                          NULL, NULL);
13428
13429         /* Dump Conversion Comments */
13430         if (convinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13431                 dumpComment(fout, "CONVERSION", qconvname,
13432                                         convinfo->dobj.namespace->dobj.name, convinfo->rolname,
13433                                         convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
13434
13435         PQclear(res);
13436
13437         destroyPQExpBuffer(query);
13438         destroyPQExpBuffer(q);
13439         destroyPQExpBuffer(delq);
13440         free(qconvname);
13441 }
13442
13443 /*
13444  * format_aggregate_signature: generate aggregate name and argument list
13445  *
13446  * The argument type names are qualified if needed.  The aggregate name
13447  * is never qualified.
13448  */
13449 static char *
13450 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
13451 {
13452         PQExpBufferData buf;
13453         int                     j;
13454
13455         initPQExpBuffer(&buf);
13456         if (honor_quotes)
13457                 appendPQExpBufferStr(&buf, fmtId(agginfo->aggfn.dobj.name));
13458         else
13459                 appendPQExpBufferStr(&buf, agginfo->aggfn.dobj.name);
13460
13461         if (agginfo->aggfn.nargs == 0)
13462                 appendPQExpBuffer(&buf, "(*)");
13463         else
13464         {
13465                 appendPQExpBufferChar(&buf, '(');
13466                 for (j = 0; j < agginfo->aggfn.nargs; j++)
13467                 {
13468                         char       *typname;
13469
13470                         typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
13471                                                                                    zeroAsOpaque);
13472
13473                         appendPQExpBuffer(&buf, "%s%s",
13474                                                           (j > 0) ? ", " : "",
13475                                                           typname);
13476                         free(typname);
13477                 }
13478                 appendPQExpBufferChar(&buf, ')');
13479         }
13480         return buf.data;
13481 }
13482
13483 /*
13484  * dumpAgg
13485  *        write out a single aggregate definition
13486  */
13487 static void
13488 dumpAgg(Archive *fout, AggInfo *agginfo)
13489 {
13490         DumpOptions *dopt = fout->dopt;
13491         PQExpBuffer query;
13492         PQExpBuffer q;
13493         PQExpBuffer delq;
13494         PQExpBuffer details;
13495         char       *aggsig;                     /* identity signature */
13496         char       *aggfullsig = NULL;  /* full signature */
13497         char       *aggsig_tag;
13498         PGresult   *res;
13499         int                     i_aggtransfn;
13500         int                     i_aggfinalfn;
13501         int                     i_aggcombinefn;
13502         int                     i_aggserialfn;
13503         int                     i_aggdeserialfn;
13504         int                     i_aggmtransfn;
13505         int                     i_aggminvtransfn;
13506         int                     i_aggmfinalfn;
13507         int                     i_aggfinalextra;
13508         int                     i_aggmfinalextra;
13509         int                     i_aggfinalmodify;
13510         int                     i_aggmfinalmodify;
13511         int                     i_aggsortop;
13512         int                     i_aggkind;
13513         int                     i_aggtranstype;
13514         int                     i_aggtransspace;
13515         int                     i_aggmtranstype;
13516         int                     i_aggmtransspace;
13517         int                     i_agginitval;
13518         int                     i_aggminitval;
13519         int                     i_convertok;
13520         int                     i_proparallel;
13521         const char *aggtransfn;
13522         const char *aggfinalfn;
13523         const char *aggcombinefn;
13524         const char *aggserialfn;
13525         const char *aggdeserialfn;
13526         const char *aggmtransfn;
13527         const char *aggminvtransfn;
13528         const char *aggmfinalfn;
13529         bool            aggfinalextra;
13530         bool            aggmfinalextra;
13531         char            aggfinalmodify;
13532         char            aggmfinalmodify;
13533         const char *aggsortop;
13534         char       *aggsortconvop;
13535         char            aggkind;
13536         const char *aggtranstype;
13537         const char *aggtransspace;
13538         const char *aggmtranstype;
13539         const char *aggmtransspace;
13540         const char *agginitval;
13541         const char *aggminitval;
13542         bool            convertok;
13543         const char *proparallel;
13544         char            defaultfinalmodify;
13545
13546         /* Skip if not to be dumped */
13547         if (!agginfo->aggfn.dobj.dump || dopt->dataOnly)
13548                 return;
13549
13550         query = createPQExpBuffer();
13551         q = createPQExpBuffer();
13552         delq = createPQExpBuffer();
13553         details = createPQExpBuffer();
13554
13555         /* Get aggregate-specific details */
13556         if (fout->remoteVersion >= 110000)
13557         {
13558                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13559                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13560                                                   "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13561                                                   "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13562                                                   "aggfinalextra, aggmfinalextra, "
13563                                                   "aggfinalmodify, aggmfinalmodify, "
13564                                                   "aggsortop, "
13565                                                   "aggkind, "
13566                                                   "aggtransspace, agginitval, "
13567                                                   "aggmtransspace, aggminitval, "
13568                                                   "true AS convertok, "
13569                                                   "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13570                                                   "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13571                                                   "p.proparallel "
13572                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13573                                                   "WHERE a.aggfnoid = p.oid "
13574                                                   "AND p.oid = '%u'::pg_catalog.oid",
13575                                                   agginfo->aggfn.dobj.catId.oid);
13576         }
13577         else if (fout->remoteVersion >= 90600)
13578         {
13579                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13580                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13581                                                   "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13582                                                   "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13583                                                   "aggfinalextra, aggmfinalextra, "
13584                                                   "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13585                                                   "aggsortop, "
13586                                                   "aggkind, "
13587                                                   "aggtransspace, agginitval, "
13588                                                   "aggmtransspace, aggminitval, "
13589                                                   "true AS convertok, "
13590                                                   "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13591                                                   "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13592                                                   "p.proparallel "
13593                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13594                                                   "WHERE a.aggfnoid = p.oid "
13595                                                   "AND p.oid = '%u'::pg_catalog.oid",
13596                                                   agginfo->aggfn.dobj.catId.oid);
13597         }
13598         else if (fout->remoteVersion >= 90400)
13599         {
13600                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13601                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13602                                                   "'-' AS aggcombinefn, '-' AS aggserialfn, "
13603                                                   "'-' AS aggdeserialfn, aggmtransfn, aggminvtransfn, "
13604                                                   "aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13605                                                   "aggfinalextra, aggmfinalextra, "
13606                                                   "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13607                                                   "aggsortop, "
13608                                                   "aggkind, "
13609                                                   "aggtransspace, agginitval, "
13610                                                   "aggmtransspace, aggminitval, "
13611                                                   "true AS convertok, "
13612                                                   "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13613                                                   "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13614                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13615                                                   "WHERE a.aggfnoid = p.oid "
13616                                                   "AND p.oid = '%u'::pg_catalog.oid",
13617                                                   agginfo->aggfn.dobj.catId.oid);
13618         }
13619         else if (fout->remoteVersion >= 80400)
13620         {
13621                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13622                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13623                                                   "'-' AS aggcombinefn, '-' AS aggserialfn, "
13624                                                   "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13625                                                   "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13626                                                   "0 AS aggmtranstype, false AS aggfinalextra, "
13627                                                   "false AS aggmfinalextra, "
13628                                                   "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13629                                                   "aggsortop, "
13630                                                   "'n' AS aggkind, "
13631                                                   "0 AS aggtransspace, agginitval, "
13632                                                   "0 AS aggmtransspace, NULL AS aggminitval, "
13633                                                   "true AS convertok, "
13634                                                   "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13635                                                   "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13636                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13637                                                   "WHERE a.aggfnoid = p.oid "
13638                                                   "AND p.oid = '%u'::pg_catalog.oid",
13639                                                   agginfo->aggfn.dobj.catId.oid);
13640         }
13641         else if (fout->remoteVersion >= 80100)
13642         {
13643                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13644                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13645                                                   "'-' AS aggcombinefn, '-' AS aggserialfn, "
13646                                                   "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13647                                                   "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13648                                                   "0 AS aggmtranstype, false AS aggfinalextra, "
13649                                                   "false AS aggmfinalextra, "
13650                                                   "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13651                                                   "aggsortop, "
13652                                                   "'n' AS aggkind, "
13653                                                   "0 AS aggtransspace, agginitval, "
13654                                                   "0 AS aggmtransspace, NULL AS aggminitval, "
13655                                                   "true AS convertok "
13656                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13657                                                   "WHERE a.aggfnoid = p.oid "
13658                                                   "AND p.oid = '%u'::pg_catalog.oid",
13659                                                   agginfo->aggfn.dobj.catId.oid);
13660         }
13661         else
13662         {
13663                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13664                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13665                                                   "'-' AS aggcombinefn, '-' AS aggserialfn, "
13666                                                   "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13667                                                   "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13668                                                   "0 AS aggmtranstype, false AS aggfinalextra, "
13669                                                   "false AS aggmfinalextra, "
13670                                                   "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13671                                                   "0 AS aggsortop, "
13672                                                   "'n' AS aggkind, "
13673                                                   "0 AS aggtransspace, agginitval, "
13674                                                   "0 AS aggmtransspace, NULL AS aggminitval, "
13675                                                   "true AS convertok "
13676                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13677                                                   "WHERE a.aggfnoid = p.oid "
13678                                                   "AND p.oid = '%u'::pg_catalog.oid",
13679                                                   agginfo->aggfn.dobj.catId.oid);
13680         }
13681
13682         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13683
13684         i_aggtransfn = PQfnumber(res, "aggtransfn");
13685         i_aggfinalfn = PQfnumber(res, "aggfinalfn");
13686         i_aggcombinefn = PQfnumber(res, "aggcombinefn");
13687         i_aggserialfn = PQfnumber(res, "aggserialfn");
13688         i_aggdeserialfn = PQfnumber(res, "aggdeserialfn");
13689         i_aggmtransfn = PQfnumber(res, "aggmtransfn");
13690         i_aggminvtransfn = PQfnumber(res, "aggminvtransfn");
13691         i_aggmfinalfn = PQfnumber(res, "aggmfinalfn");
13692         i_aggfinalextra = PQfnumber(res, "aggfinalextra");
13693         i_aggmfinalextra = PQfnumber(res, "aggmfinalextra");
13694         i_aggfinalmodify = PQfnumber(res, "aggfinalmodify");
13695         i_aggmfinalmodify = PQfnumber(res, "aggmfinalmodify");
13696         i_aggsortop = PQfnumber(res, "aggsortop");
13697         i_aggkind = PQfnumber(res, "aggkind");
13698         i_aggtranstype = PQfnumber(res, "aggtranstype");
13699         i_aggtransspace = PQfnumber(res, "aggtransspace");
13700         i_aggmtranstype = PQfnumber(res, "aggmtranstype");
13701         i_aggmtransspace = PQfnumber(res, "aggmtransspace");
13702         i_agginitval = PQfnumber(res, "agginitval");
13703         i_aggminitval = PQfnumber(res, "aggminitval");
13704         i_convertok = PQfnumber(res, "convertok");
13705         i_proparallel = PQfnumber(res, "proparallel");
13706
13707         aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
13708         aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
13709         aggcombinefn = PQgetvalue(res, 0, i_aggcombinefn);
13710         aggserialfn = PQgetvalue(res, 0, i_aggserialfn);
13711         aggdeserialfn = PQgetvalue(res, 0, i_aggdeserialfn);
13712         aggmtransfn = PQgetvalue(res, 0, i_aggmtransfn);
13713         aggminvtransfn = PQgetvalue(res, 0, i_aggminvtransfn);
13714         aggmfinalfn = PQgetvalue(res, 0, i_aggmfinalfn);
13715         aggfinalextra = (PQgetvalue(res, 0, i_aggfinalextra)[0] == 't');
13716         aggmfinalextra = (PQgetvalue(res, 0, i_aggmfinalextra)[0] == 't');
13717         aggfinalmodify = PQgetvalue(res, 0, i_aggfinalmodify)[0];
13718         aggmfinalmodify = PQgetvalue(res, 0, i_aggmfinalmodify)[0];
13719         aggsortop = PQgetvalue(res, 0, i_aggsortop);
13720         aggkind = PQgetvalue(res, 0, i_aggkind)[0];
13721         aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
13722         aggtransspace = PQgetvalue(res, 0, i_aggtransspace);
13723         aggmtranstype = PQgetvalue(res, 0, i_aggmtranstype);
13724         aggmtransspace = PQgetvalue(res, 0, i_aggmtransspace);
13725         agginitval = PQgetvalue(res, 0, i_agginitval);
13726         aggminitval = PQgetvalue(res, 0, i_aggminitval);
13727         convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
13728
13729         if (fout->remoteVersion >= 80400)
13730         {
13731                 /* 8.4 or later; we rely on server-side code for most of the work */
13732                 char       *funcargs;
13733                 char       *funciargs;
13734
13735                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
13736                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
13737                 aggfullsig = format_function_arguments(&agginfo->aggfn, funcargs, true);
13738                 aggsig = format_function_arguments(&agginfo->aggfn, funciargs, true);
13739         }
13740         else
13741                 /* pre-8.4, do it ourselves */
13742                 aggsig = format_aggregate_signature(agginfo, fout, true);
13743
13744         aggsig_tag = format_aggregate_signature(agginfo, fout, false);
13745
13746         if (i_proparallel != -1)
13747                 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
13748         else
13749                 proparallel = NULL;
13750
13751         if (!convertok)
13752         {
13753                 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
13754                                   aggsig);
13755
13756                 if (aggfullsig)
13757                         free(aggfullsig);
13758
13759                 free(aggsig);
13760
13761                 return;
13762         }
13763
13764         /* identify default modify flag for aggkind (must match DefineAggregate) */
13765         defaultfinalmodify = (aggkind == AGGKIND_NORMAL) ? AGGMODIFY_READ_ONLY : AGGMODIFY_READ_WRITE;
13766         /* replace omitted flags for old versions */
13767         if (aggfinalmodify == '0')
13768                 aggfinalmodify = defaultfinalmodify;
13769         if (aggmfinalmodify == '0')
13770                 aggmfinalmodify = defaultfinalmodify;
13771
13772         /* regproc and regtype output is already sufficiently quoted */
13773         appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
13774                                           aggtransfn, aggtranstype);
13775
13776         if (strcmp(aggtransspace, "0") != 0)
13777         {
13778                 appendPQExpBuffer(details, ",\n    SSPACE = %s",
13779                                                   aggtransspace);
13780         }
13781
13782         if (!PQgetisnull(res, 0, i_agginitval))
13783         {
13784                 appendPQExpBufferStr(details, ",\n    INITCOND = ");
13785                 appendStringLiteralAH(details, agginitval, fout);
13786         }
13787
13788         if (strcmp(aggfinalfn, "-") != 0)
13789         {
13790                 appendPQExpBuffer(details, ",\n    FINALFUNC = %s",
13791                                                   aggfinalfn);
13792                 if (aggfinalextra)
13793                         appendPQExpBufferStr(details, ",\n    FINALFUNC_EXTRA");
13794                 if (aggfinalmodify != defaultfinalmodify)
13795                 {
13796                         switch (aggfinalmodify)
13797                         {
13798                                 case AGGMODIFY_READ_ONLY:
13799                                         appendPQExpBufferStr(details, ",\n    FINALFUNC_MODIFY = READ_ONLY");
13800                                         break;
13801                                 case AGGMODIFY_SHARABLE:
13802                                         appendPQExpBufferStr(details, ",\n    FINALFUNC_MODIFY = SHARABLE");
13803                                         break;
13804                                 case AGGMODIFY_READ_WRITE:
13805                                         appendPQExpBufferStr(details, ",\n    FINALFUNC_MODIFY = READ_WRITE");
13806                                         break;
13807                                 default:
13808                                         exit_horribly(NULL, "unrecognized aggfinalmodify value for aggregate \"%s\"\n",
13809                                                                   agginfo->aggfn.dobj.name);
13810                                         break;
13811                         }
13812                 }
13813         }
13814
13815         if (strcmp(aggcombinefn, "-") != 0)
13816                 appendPQExpBuffer(details, ",\n    COMBINEFUNC = %s", aggcombinefn);
13817
13818         if (strcmp(aggserialfn, "-") != 0)
13819                 appendPQExpBuffer(details, ",\n    SERIALFUNC = %s", aggserialfn);
13820
13821         if (strcmp(aggdeserialfn, "-") != 0)
13822                 appendPQExpBuffer(details, ",\n    DESERIALFUNC = %s", aggdeserialfn);
13823
13824         if (strcmp(aggmtransfn, "-") != 0)
13825         {
13826                 appendPQExpBuffer(details, ",\n    MSFUNC = %s,\n    MINVFUNC = %s,\n    MSTYPE = %s",
13827                                                   aggmtransfn,
13828                                                   aggminvtransfn,
13829                                                   aggmtranstype);
13830         }
13831
13832         if (strcmp(aggmtransspace, "0") != 0)
13833         {
13834                 appendPQExpBuffer(details, ",\n    MSSPACE = %s",
13835                                                   aggmtransspace);
13836         }
13837
13838         if (!PQgetisnull(res, 0, i_aggminitval))
13839         {
13840                 appendPQExpBufferStr(details, ",\n    MINITCOND = ");
13841                 appendStringLiteralAH(details, aggminitval, fout);
13842         }
13843
13844         if (strcmp(aggmfinalfn, "-") != 0)
13845         {
13846                 appendPQExpBuffer(details, ",\n    MFINALFUNC = %s",
13847                                                   aggmfinalfn);
13848                 if (aggmfinalextra)
13849                         appendPQExpBufferStr(details, ",\n    MFINALFUNC_EXTRA");
13850                 if (aggmfinalmodify != defaultfinalmodify)
13851                 {
13852                         switch (aggmfinalmodify)
13853                         {
13854                                 case AGGMODIFY_READ_ONLY:
13855                                         appendPQExpBufferStr(details, ",\n    MFINALFUNC_MODIFY = READ_ONLY");
13856                                         break;
13857                                 case AGGMODIFY_SHARABLE:
13858                                         appendPQExpBufferStr(details, ",\n    MFINALFUNC_MODIFY = SHARABLE");
13859                                         break;
13860                                 case AGGMODIFY_READ_WRITE:
13861                                         appendPQExpBufferStr(details, ",\n    MFINALFUNC_MODIFY = READ_WRITE");
13862                                         break;
13863                                 default:
13864                                         exit_horribly(NULL, "unrecognized aggmfinalmodify value for aggregate \"%s\"\n",
13865                                                                   agginfo->aggfn.dobj.name);
13866                                         break;
13867                         }
13868                 }
13869         }
13870
13871         aggsortconvop = getFormattedOperatorName(fout, aggsortop);
13872         if (aggsortconvop)
13873         {
13874                 appendPQExpBuffer(details, ",\n    SORTOP = %s",
13875                                                   aggsortconvop);
13876                 free(aggsortconvop);
13877         }
13878
13879         if (aggkind == AGGKIND_HYPOTHETICAL)
13880                 appendPQExpBufferStr(details, ",\n    HYPOTHETICAL");
13881
13882         if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
13883         {
13884                 if (proparallel[0] == PROPARALLEL_SAFE)
13885                         appendPQExpBufferStr(details, ",\n    PARALLEL = safe");
13886                 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
13887                         appendPQExpBufferStr(details, ",\n    PARALLEL = restricted");
13888                 else if (proparallel[0] != PROPARALLEL_UNSAFE)
13889                         exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
13890                                                   agginfo->aggfn.dobj.name);
13891         }
13892
13893         appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
13894                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
13895                                           aggsig);
13896
13897         appendPQExpBuffer(q, "CREATE AGGREGATE %s.%s (\n%s\n);\n",
13898                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
13899                                           aggfullsig ? aggfullsig : aggsig, details->data);
13900
13901         if (dopt->binary_upgrade)
13902                 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj,
13903                                                                                 "AGGREGATE", aggsig,
13904                                                                                 agginfo->aggfn.dobj.namespace->dobj.name);
13905
13906         if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_DEFINITION)
13907                 ArchiveEntry(fout, agginfo->aggfn.dobj.catId,
13908                                          agginfo->aggfn.dobj.dumpId,
13909                                          aggsig_tag,
13910                                          agginfo->aggfn.dobj.namespace->dobj.name,
13911                                          NULL,
13912                                          agginfo->aggfn.rolname,
13913                                          false, "AGGREGATE", SECTION_PRE_DATA,
13914                                          q->data, delq->data, NULL,
13915                                          NULL, 0,
13916                                          NULL, NULL);
13917
13918         /* Dump Aggregate Comments */
13919         if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_COMMENT)
13920                 dumpComment(fout, "AGGREGATE", aggsig,
13921                                         agginfo->aggfn.dobj.namespace->dobj.name,
13922                                         agginfo->aggfn.rolname,
13923                                         agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
13924
13925         if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_SECLABEL)
13926                 dumpSecLabel(fout, "AGGREGATE", aggsig,
13927                                          agginfo->aggfn.dobj.namespace->dobj.name,
13928                                          agginfo->aggfn.rolname,
13929                                          agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
13930
13931         /*
13932          * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
13933          * command look like a function's GRANT; in particular this affects the
13934          * syntax for zero-argument aggregates and ordered-set aggregates.
13935          */
13936         free(aggsig);
13937
13938         aggsig = format_function_signature(fout, &agginfo->aggfn, true);
13939
13940         if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_ACL)
13941                 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
13942                                 "FUNCTION", aggsig, NULL,
13943                                 agginfo->aggfn.dobj.namespace->dobj.name,
13944                                 agginfo->aggfn.rolname, agginfo->aggfn.proacl,
13945                                 agginfo->aggfn.rproacl,
13946                                 agginfo->aggfn.initproacl, agginfo->aggfn.initrproacl);
13947
13948         free(aggsig);
13949         if (aggfullsig)
13950                 free(aggfullsig);
13951         free(aggsig_tag);
13952
13953         PQclear(res);
13954
13955         destroyPQExpBuffer(query);
13956         destroyPQExpBuffer(q);
13957         destroyPQExpBuffer(delq);
13958         destroyPQExpBuffer(details);
13959 }
13960
13961 /*
13962  * dumpTSParser
13963  *        write out a single text search parser
13964  */
13965 static void
13966 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
13967 {
13968         DumpOptions *dopt = fout->dopt;
13969         PQExpBuffer q;
13970         PQExpBuffer delq;
13971         char       *qprsname;
13972
13973         /* Skip if not to be dumped */
13974         if (!prsinfo->dobj.dump || dopt->dataOnly)
13975                 return;
13976
13977         q = createPQExpBuffer();
13978         delq = createPQExpBuffer();
13979
13980         qprsname = pg_strdup(fmtId(prsinfo->dobj.name));
13981
13982         appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
13983                                           fmtQualifiedDumpable(prsinfo));
13984
13985         appendPQExpBuffer(q, "    START = %s,\n",
13986                                           convertTSFunction(fout, prsinfo->prsstart));
13987         appendPQExpBuffer(q, "    GETTOKEN = %s,\n",
13988                                           convertTSFunction(fout, prsinfo->prstoken));
13989         appendPQExpBuffer(q, "    END = %s,\n",
13990                                           convertTSFunction(fout, prsinfo->prsend));
13991         if (prsinfo->prsheadline != InvalidOid)
13992                 appendPQExpBuffer(q, "    HEADLINE = %s,\n",
13993                                                   convertTSFunction(fout, prsinfo->prsheadline));
13994         appendPQExpBuffer(q, "    LEXTYPES = %s );\n",
13995                                           convertTSFunction(fout, prsinfo->prslextype));
13996
13997         appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s;\n",
13998                                           fmtQualifiedDumpable(prsinfo));
13999
14000         if (dopt->binary_upgrade)
14001                 binary_upgrade_extension_member(q, &prsinfo->dobj,
14002                                                                                 "TEXT SEARCH PARSER", qprsname,
14003                                                                                 prsinfo->dobj.namespace->dobj.name);
14004
14005         if (prsinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14006                 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
14007                                          prsinfo->dobj.name,
14008                                          prsinfo->dobj.namespace->dobj.name,
14009                                          NULL,
14010                                          "",
14011                                          false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
14012                                          q->data, delq->data, NULL,
14013                                          NULL, 0,
14014                                          NULL, NULL);
14015
14016         /* Dump Parser Comments */
14017         if (prsinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14018                 dumpComment(fout, "TEXT SEARCH PARSER", qprsname,
14019                                         prsinfo->dobj.namespace->dobj.name, "",
14020                                         prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
14021
14022         destroyPQExpBuffer(q);
14023         destroyPQExpBuffer(delq);
14024         free(qprsname);
14025 }
14026
14027 /*
14028  * dumpTSDictionary
14029  *        write out a single text search dictionary
14030  */
14031 static void
14032 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
14033 {
14034         DumpOptions *dopt = fout->dopt;
14035         PQExpBuffer q;
14036         PQExpBuffer delq;
14037         PQExpBuffer query;
14038         char       *qdictname;
14039         PGresult   *res;
14040         char       *nspname;
14041         char       *tmplname;
14042
14043         /* Skip if not to be dumped */
14044         if (!dictinfo->dobj.dump || dopt->dataOnly)
14045                 return;
14046
14047         q = createPQExpBuffer();
14048         delq = createPQExpBuffer();
14049         query = createPQExpBuffer();
14050
14051         qdictname = pg_strdup(fmtId(dictinfo->dobj.name));
14052
14053         /* Fetch name and namespace of the dictionary's template */
14054         appendPQExpBuffer(query, "SELECT nspname, tmplname "
14055                                           "FROM pg_ts_template p, pg_namespace n "
14056                                           "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
14057                                           dictinfo->dicttemplate);
14058         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14059         nspname = PQgetvalue(res, 0, 0);
14060         tmplname = PQgetvalue(res, 0, 1);
14061
14062         appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
14063                                           fmtQualifiedDumpable(dictinfo));
14064
14065         appendPQExpBufferStr(q, "    TEMPLATE = ");
14066         appendPQExpBuffer(q, "%s.", fmtId(nspname));
14067         appendPQExpBufferStr(q, fmtId(tmplname));
14068
14069         PQclear(res);
14070
14071         /* the dictinitoption can be dumped straight into the command */
14072         if (dictinfo->dictinitoption)
14073                 appendPQExpBuffer(q, ",\n    %s", dictinfo->dictinitoption);
14074
14075         appendPQExpBufferStr(q, " );\n");
14076
14077         appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s;\n",
14078                                           fmtQualifiedDumpable(dictinfo));
14079
14080         if (dopt->binary_upgrade)
14081                 binary_upgrade_extension_member(q, &dictinfo->dobj,
14082                                                                                 "TEXT SEARCH DICTIONARY", qdictname,
14083                                                                                 dictinfo->dobj.namespace->dobj.name);
14084
14085         if (dictinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14086                 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
14087                                          dictinfo->dobj.name,
14088                                          dictinfo->dobj.namespace->dobj.name,
14089                                          NULL,
14090                                          dictinfo->rolname,
14091                                          false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
14092                                          q->data, delq->data, NULL,
14093                                          NULL, 0,
14094                                          NULL, NULL);
14095
14096         /* Dump Dictionary Comments */
14097         if (dictinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14098                 dumpComment(fout, "TEXT SEARCH DICTIONARY", qdictname,
14099                                         dictinfo->dobj.namespace->dobj.name, dictinfo->rolname,
14100                                         dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
14101
14102         destroyPQExpBuffer(q);
14103         destroyPQExpBuffer(delq);
14104         destroyPQExpBuffer(query);
14105         free(qdictname);
14106 }
14107
14108 /*
14109  * dumpTSTemplate
14110  *        write out a single text search template
14111  */
14112 static void
14113 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
14114 {
14115         DumpOptions *dopt = fout->dopt;
14116         PQExpBuffer q;
14117         PQExpBuffer delq;
14118         char       *qtmplname;
14119
14120         /* Skip if not to be dumped */
14121         if (!tmplinfo->dobj.dump || dopt->dataOnly)
14122                 return;
14123
14124         q = createPQExpBuffer();
14125         delq = createPQExpBuffer();
14126
14127         qtmplname = pg_strdup(fmtId(tmplinfo->dobj.name));
14128
14129         appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
14130                                           fmtQualifiedDumpable(tmplinfo));
14131
14132         if (tmplinfo->tmplinit != InvalidOid)
14133                 appendPQExpBuffer(q, "    INIT = %s,\n",
14134                                                   convertTSFunction(fout, tmplinfo->tmplinit));
14135         appendPQExpBuffer(q, "    LEXIZE = %s );\n",
14136                                           convertTSFunction(fout, tmplinfo->tmpllexize));
14137
14138         appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s;\n",
14139                                           fmtQualifiedDumpable(tmplinfo));
14140
14141         if (dopt->binary_upgrade)
14142                 binary_upgrade_extension_member(q, &tmplinfo->dobj,
14143                                                                                 "TEXT SEARCH TEMPLATE", qtmplname,
14144                                                                                 tmplinfo->dobj.namespace->dobj.name);
14145
14146         if (tmplinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14147                 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
14148                                          tmplinfo->dobj.name,
14149                                          tmplinfo->dobj.namespace->dobj.name,
14150                                          NULL,
14151                                          "",
14152                                          false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
14153                                          q->data, delq->data, NULL,
14154                                          NULL, 0,
14155                                          NULL, NULL);
14156
14157         /* Dump Template Comments */
14158         if (tmplinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14159                 dumpComment(fout, "TEXT SEARCH TEMPLATE", qtmplname,
14160                                         tmplinfo->dobj.namespace->dobj.name, "",
14161                                         tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
14162
14163         destroyPQExpBuffer(q);
14164         destroyPQExpBuffer(delq);
14165         free(qtmplname);
14166 }
14167
14168 /*
14169  * dumpTSConfig
14170  *        write out a single text search configuration
14171  */
14172 static void
14173 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
14174 {
14175         DumpOptions *dopt = fout->dopt;
14176         PQExpBuffer q;
14177         PQExpBuffer delq;
14178         PQExpBuffer query;
14179         char       *qcfgname;
14180         PGresult   *res;
14181         char       *nspname;
14182         char       *prsname;
14183         int                     ntups,
14184                                 i;
14185         int                     i_tokenname;
14186         int                     i_dictname;
14187
14188         /* Skip if not to be dumped */
14189         if (!cfginfo->dobj.dump || dopt->dataOnly)
14190                 return;
14191
14192         q = createPQExpBuffer();
14193         delq = createPQExpBuffer();
14194         query = createPQExpBuffer();
14195
14196         qcfgname = pg_strdup(fmtId(cfginfo->dobj.name));
14197
14198         /* Fetch name and namespace of the config's parser */
14199         appendPQExpBuffer(query, "SELECT nspname, prsname "
14200                                           "FROM pg_ts_parser p, pg_namespace n "
14201                                           "WHERE p.oid = '%u' AND n.oid = prsnamespace",
14202                                           cfginfo->cfgparser);
14203         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14204         nspname = PQgetvalue(res, 0, 0);
14205         prsname = PQgetvalue(res, 0, 1);
14206
14207         appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
14208                                           fmtQualifiedDumpable(cfginfo));
14209
14210         appendPQExpBuffer(q, "    PARSER = %s.", fmtId(nspname));
14211         appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
14212
14213         PQclear(res);
14214
14215         resetPQExpBuffer(query);
14216         appendPQExpBuffer(query,
14217                                           "SELECT\n"
14218                                           "  ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t\n"
14219                                           "    WHERE t.tokid = m.maptokentype ) AS tokenname,\n"
14220                                           "  m.mapdict::pg_catalog.regdictionary AS dictname\n"
14221                                           "FROM pg_catalog.pg_ts_config_map AS m\n"
14222                                           "WHERE m.mapcfg = '%u'\n"
14223                                           "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
14224                                           cfginfo->cfgparser, cfginfo->dobj.catId.oid);
14225
14226         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14227         ntups = PQntuples(res);
14228
14229         i_tokenname = PQfnumber(res, "tokenname");
14230         i_dictname = PQfnumber(res, "dictname");
14231
14232         for (i = 0; i < ntups; i++)
14233         {
14234                 char       *tokenname = PQgetvalue(res, i, i_tokenname);
14235                 char       *dictname = PQgetvalue(res, i, i_dictname);
14236
14237                 if (i == 0 ||
14238                         strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
14239                 {
14240                         /* starting a new token type, so start a new command */
14241                         if (i > 0)
14242                                 appendPQExpBufferStr(q, ";\n");
14243                         appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
14244                                                           fmtQualifiedDumpable(cfginfo));
14245                         /* tokenname needs quoting, dictname does NOT */
14246                         appendPQExpBuffer(q, "    ADD MAPPING FOR %s WITH %s",
14247                                                           fmtId(tokenname), dictname);
14248                 }
14249                 else
14250                         appendPQExpBuffer(q, ", %s", dictname);
14251         }
14252
14253         if (ntups > 0)
14254                 appendPQExpBufferStr(q, ";\n");
14255
14256         PQclear(res);
14257
14258         appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s;\n",
14259                                           fmtQualifiedDumpable(cfginfo));
14260
14261         if (dopt->binary_upgrade)
14262                 binary_upgrade_extension_member(q, &cfginfo->dobj,
14263                                                                                 "TEXT SEARCH CONFIGURATION", qcfgname,
14264                                                                                 cfginfo->dobj.namespace->dobj.name);
14265
14266         if (cfginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14267                 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
14268                                          cfginfo->dobj.name,
14269                                          cfginfo->dobj.namespace->dobj.name,
14270                                          NULL,
14271                                          cfginfo->rolname,
14272                                          false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
14273                                          q->data, delq->data, NULL,
14274                                          NULL, 0,
14275                                          NULL, NULL);
14276
14277         /* Dump Configuration Comments */
14278         if (cfginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14279                 dumpComment(fout, "TEXT SEARCH CONFIGURATION", qcfgname,
14280                                         cfginfo->dobj.namespace->dobj.name, cfginfo->rolname,
14281                                         cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
14282
14283         destroyPQExpBuffer(q);
14284         destroyPQExpBuffer(delq);
14285         destroyPQExpBuffer(query);
14286         free(qcfgname);
14287 }
14288
14289 /*
14290  * dumpForeignDataWrapper
14291  *        write out a single foreign-data wrapper definition
14292  */
14293 static void
14294 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
14295 {
14296         DumpOptions *dopt = fout->dopt;
14297         PQExpBuffer q;
14298         PQExpBuffer delq;
14299         char       *qfdwname;
14300
14301         /* Skip if not to be dumped */
14302         if (!fdwinfo->dobj.dump || dopt->dataOnly)
14303                 return;
14304
14305         q = createPQExpBuffer();
14306         delq = createPQExpBuffer();
14307
14308         qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
14309
14310         appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
14311                                           qfdwname);
14312
14313         if (strcmp(fdwinfo->fdwhandler, "-") != 0)
14314                 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
14315
14316         if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
14317                 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
14318
14319         if (strlen(fdwinfo->fdwoptions) > 0)
14320                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", fdwinfo->fdwoptions);
14321
14322         appendPQExpBufferStr(q, ";\n");
14323
14324         appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
14325                                           qfdwname);
14326
14327         if (dopt->binary_upgrade)
14328                 binary_upgrade_extension_member(q, &fdwinfo->dobj,
14329                                                                                 "FOREIGN DATA WRAPPER", qfdwname,
14330                                                                                 NULL);
14331
14332         if (fdwinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14333                 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14334                                          fdwinfo->dobj.name,
14335                                          NULL,
14336                                          NULL,
14337                                          fdwinfo->rolname,
14338                                          false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
14339                                          q->data, delq->data, NULL,
14340                                          NULL, 0,
14341                                          NULL, NULL);
14342
14343         /* Dump Foreign Data Wrapper Comments */
14344         if (fdwinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14345                 dumpComment(fout, "FOREIGN DATA WRAPPER", qfdwname,
14346                                         NULL, fdwinfo->rolname,
14347                                         fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
14348
14349         /* Handle the ACL */
14350         if (fdwinfo->dobj.dump & DUMP_COMPONENT_ACL)
14351                 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14352                                 "FOREIGN DATA WRAPPER", qfdwname, NULL,
14353                                 NULL, fdwinfo->rolname,
14354                                 fdwinfo->fdwacl, fdwinfo->rfdwacl,
14355                                 fdwinfo->initfdwacl, fdwinfo->initrfdwacl);
14356
14357         free(qfdwname);
14358
14359         destroyPQExpBuffer(q);
14360         destroyPQExpBuffer(delq);
14361 }
14362
14363 /*
14364  * dumpForeignServer
14365  *        write out a foreign server definition
14366  */
14367 static void
14368 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
14369 {
14370         DumpOptions *dopt = fout->dopt;
14371         PQExpBuffer q;
14372         PQExpBuffer delq;
14373         PQExpBuffer query;
14374         PGresult   *res;
14375         char       *qsrvname;
14376         char       *fdwname;
14377
14378         /* Skip if not to be dumped */
14379         if (!srvinfo->dobj.dump || dopt->dataOnly)
14380                 return;
14381
14382         q = createPQExpBuffer();
14383         delq = createPQExpBuffer();
14384         query = createPQExpBuffer();
14385
14386         qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
14387
14388         /* look up the foreign-data wrapper */
14389         appendPQExpBuffer(query, "SELECT fdwname "
14390                                           "FROM pg_foreign_data_wrapper w "
14391                                           "WHERE w.oid = '%u'",
14392                                           srvinfo->srvfdw);
14393         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14394         fdwname = PQgetvalue(res, 0, 0);
14395
14396         appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
14397         if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
14398         {
14399                 appendPQExpBufferStr(q, " TYPE ");
14400                 appendStringLiteralAH(q, srvinfo->srvtype, fout);
14401         }
14402         if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
14403         {
14404                 appendPQExpBufferStr(q, " VERSION ");
14405                 appendStringLiteralAH(q, srvinfo->srvversion, fout);
14406         }
14407
14408         appendPQExpBufferStr(q, " FOREIGN DATA WRAPPER ");
14409         appendPQExpBufferStr(q, fmtId(fdwname));
14410
14411         if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
14412                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", srvinfo->srvoptions);
14413
14414         appendPQExpBufferStr(q, ";\n");
14415
14416         appendPQExpBuffer(delq, "DROP SERVER %s;\n",
14417                                           qsrvname);
14418
14419         if (dopt->binary_upgrade)
14420                 binary_upgrade_extension_member(q, &srvinfo->dobj,
14421                                                                                 "SERVER", qsrvname, NULL);
14422
14423         if (srvinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14424                 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14425                                          srvinfo->dobj.name,
14426                                          NULL,
14427                                          NULL,
14428                                          srvinfo->rolname,
14429                                          false, "SERVER", SECTION_PRE_DATA,
14430                                          q->data, delq->data, NULL,
14431                                          NULL, 0,
14432                                          NULL, NULL);
14433
14434         /* Dump Foreign Server Comments */
14435         if (srvinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14436                 dumpComment(fout, "SERVER", qsrvname,
14437                                         NULL, srvinfo->rolname,
14438                                         srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
14439
14440         /* Handle the ACL */
14441         if (srvinfo->dobj.dump & DUMP_COMPONENT_ACL)
14442                 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14443                                 "FOREIGN SERVER", qsrvname, NULL,
14444                                 NULL, srvinfo->rolname,
14445                                 srvinfo->srvacl, srvinfo->rsrvacl,
14446                                 srvinfo->initsrvacl, srvinfo->initrsrvacl);
14447
14448         /* Dump user mappings */
14449         if (srvinfo->dobj.dump & DUMP_COMPONENT_USERMAP)
14450                 dumpUserMappings(fout,
14451                                                  srvinfo->dobj.name, NULL,
14452                                                  srvinfo->rolname,
14453                                                  srvinfo->dobj.catId, srvinfo->dobj.dumpId);
14454
14455         free(qsrvname);
14456
14457         destroyPQExpBuffer(q);
14458         destroyPQExpBuffer(delq);
14459         destroyPQExpBuffer(query);
14460 }
14461
14462 /*
14463  * dumpUserMappings
14464  *
14465  * This routine is used to dump any user mappings associated with the
14466  * server handed to this routine. Should be called after ArchiveEntry()
14467  * for the server.
14468  */
14469 static void
14470 dumpUserMappings(Archive *fout,
14471                                  const char *servername, const char *namespace,
14472                                  const char *owner,
14473                                  CatalogId catalogId, DumpId dumpId)
14474 {
14475         PQExpBuffer q;
14476         PQExpBuffer delq;
14477         PQExpBuffer query;
14478         PQExpBuffer tag;
14479         PGresult   *res;
14480         int                     ntups;
14481         int                     i_usename;
14482         int                     i_umoptions;
14483         int                     i;
14484
14485         q = createPQExpBuffer();
14486         tag = createPQExpBuffer();
14487         delq = createPQExpBuffer();
14488         query = createPQExpBuffer();
14489
14490         /*
14491          * We read from the publicly accessible view pg_user_mappings, so as not
14492          * to fail if run by a non-superuser.  Note that the view will show
14493          * umoptions as null if the user hasn't got privileges for the associated
14494          * server; this means that pg_dump will dump such a mapping, but with no
14495          * OPTIONS clause.  A possible alternative is to skip such mappings
14496          * altogether, but it's not clear that that's an improvement.
14497          */
14498         appendPQExpBuffer(query,
14499                                           "SELECT usename, "
14500                                           "array_to_string(ARRAY("
14501                                           "SELECT quote_ident(option_name) || ' ' || "
14502                                           "quote_literal(option_value) "
14503                                           "FROM pg_options_to_table(umoptions) "
14504                                           "ORDER BY option_name"
14505                                           "), E',\n    ') AS umoptions "
14506                                           "FROM pg_user_mappings "
14507                                           "WHERE srvid = '%u' "
14508                                           "ORDER BY usename",
14509                                           catalogId.oid);
14510
14511         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14512
14513         ntups = PQntuples(res);
14514         i_usename = PQfnumber(res, "usename");
14515         i_umoptions = PQfnumber(res, "umoptions");
14516
14517         for (i = 0; i < ntups; i++)
14518         {
14519                 char       *usename;
14520                 char       *umoptions;
14521
14522                 usename = PQgetvalue(res, i, i_usename);
14523                 umoptions = PQgetvalue(res, i, i_umoptions);
14524
14525                 resetPQExpBuffer(q);
14526                 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
14527                 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
14528
14529                 if (umoptions && strlen(umoptions) > 0)
14530                         appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", umoptions);
14531
14532                 appendPQExpBufferStr(q, ";\n");
14533
14534                 resetPQExpBuffer(delq);
14535                 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
14536                 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
14537
14538                 resetPQExpBuffer(tag);
14539                 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
14540                                                   usename, servername);
14541
14542                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14543                                          tag->data,
14544                                          namespace,
14545                                          NULL,
14546                                          owner, false,
14547                                          "USER MAPPING", SECTION_PRE_DATA,
14548                                          q->data, delq->data, NULL,
14549                                          &dumpId, 1,
14550                                          NULL, NULL);
14551         }
14552
14553         PQclear(res);
14554
14555         destroyPQExpBuffer(query);
14556         destroyPQExpBuffer(delq);
14557         destroyPQExpBuffer(tag);
14558         destroyPQExpBuffer(q);
14559 }
14560
14561 /*
14562  * Write out default privileges information
14563  */
14564 static void
14565 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
14566 {
14567         DumpOptions *dopt = fout->dopt;
14568         PQExpBuffer q;
14569         PQExpBuffer tag;
14570         const char *type;
14571
14572         /* Skip if not to be dumped */
14573         if (!daclinfo->dobj.dump || dopt->dataOnly || dopt->aclsSkip)
14574                 return;
14575
14576         q = createPQExpBuffer();
14577         tag = createPQExpBuffer();
14578
14579         switch (daclinfo->defaclobjtype)
14580         {
14581                 case DEFACLOBJ_RELATION:
14582                         type = "TABLES";
14583                         break;
14584                 case DEFACLOBJ_SEQUENCE:
14585                         type = "SEQUENCES";
14586                         break;
14587                 case DEFACLOBJ_FUNCTION:
14588                         type = "FUNCTIONS";
14589                         break;
14590                 case DEFACLOBJ_TYPE:
14591                         type = "TYPES";
14592                         break;
14593                 case DEFACLOBJ_NAMESPACE:
14594                         type = "SCHEMAS";
14595                         break;
14596                 default:
14597                         /* shouldn't get here */
14598                         exit_horribly(NULL,
14599                                                   "unrecognized object type in default privileges: %d\n",
14600                                                   (int) daclinfo->defaclobjtype);
14601                         type = "";                      /* keep compiler quiet */
14602         }
14603
14604         appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
14605
14606         /* build the actual command(s) for this tuple */
14607         if (!buildDefaultACLCommands(type,
14608                                                                  daclinfo->dobj.namespace != NULL ?
14609                                                                  daclinfo->dobj.namespace->dobj.name : NULL,
14610                                                                  daclinfo->defaclacl,
14611                                                                  daclinfo->rdefaclacl,
14612                                                                  daclinfo->initdefaclacl,
14613                                                                  daclinfo->initrdefaclacl,
14614                                                                  daclinfo->defaclrole,
14615                                                                  fout->remoteVersion,
14616                                                                  q))
14617                 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
14618                                           daclinfo->defaclacl);
14619
14620         if (daclinfo->dobj.dump & DUMP_COMPONENT_ACL)
14621                 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
14622                                          tag->data,
14623                                          daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
14624                                          NULL,
14625                                          daclinfo->defaclrole,
14626                                          false, "DEFAULT ACL", SECTION_POST_DATA,
14627                                          q->data, "", NULL,
14628                                          NULL, 0,
14629                                          NULL, NULL);
14630
14631         destroyPQExpBuffer(tag);
14632         destroyPQExpBuffer(q);
14633 }
14634
14635 /*----------
14636  * Write out grant/revoke information
14637  *
14638  * 'objCatId' is the catalog ID of the underlying object.
14639  * 'objDumpId' is the dump ID of the underlying object.
14640  * 'type' must be one of
14641  *              TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
14642  *              FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
14643  * 'name' is the formatted name of the object.  Must be quoted etc. already.
14644  * 'subname' is the formatted name of the sub-object, if any.  Must be quoted.
14645  *              (Currently we assume that subname is only provided for table columns.)
14646  * 'nspname' is the namespace the object is in (NULL if none).
14647  * 'owner' is the owner, NULL if there is no owner (for languages).
14648  * 'acls' contains the ACL string of the object from the appropriate system
14649  *              catalog field; it will be passed to buildACLCommands for building the
14650  *              appropriate GRANT commands.
14651  * 'racls' contains the ACL string of any initial-but-now-revoked ACLs of the
14652  *              object; it will be passed to buildACLCommands for building the
14653  *              appropriate REVOKE commands.
14654  * 'initacls' In binary-upgrade mode, ACL string of the object's initial
14655  *              privileges, to be recorded into pg_init_privs
14656  * 'initracls' In binary-upgrade mode, ACL string of the object's
14657  *              revoked-from-default privileges, to be recorded into pg_init_privs
14658  *
14659  * NB: initacls/initracls are needed because extensions can set privileges on
14660  * an object during the extension's script file and we record those into
14661  * pg_init_privs as that object's initial privileges.
14662  *----------
14663  */
14664 static void
14665 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
14666                 const char *type, const char *name, const char *subname,
14667                 const char *nspname, const char *owner,
14668                 const char *acls, const char *racls,
14669                 const char *initacls, const char *initracls)
14670 {
14671         DumpOptions *dopt = fout->dopt;
14672         PQExpBuffer sql;
14673
14674         /* Do nothing if ACL dump is not enabled */
14675         if (dopt->aclsSkip)
14676                 return;
14677
14678         /* --data-only skips ACLs *except* BLOB ACLs */
14679         if (dopt->dataOnly && strcmp(type, "LARGE OBJECT") != 0)
14680                 return;
14681
14682         sql = createPQExpBuffer();
14683
14684         /*
14685          * Check to see if this object has had any initial ACLs included for it.
14686          * If so, we are in binary upgrade mode and these are the ACLs to turn
14687          * into GRANT and REVOKE statements to set and record the initial
14688          * privileges for an extension object.  Let the backend know that these
14689          * are to be recorded by calling binary_upgrade_set_record_init_privs()
14690          * before and after.
14691          */
14692         if (strlen(initacls) != 0 || strlen(initracls) != 0)
14693         {
14694                 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(true);\n");
14695                 if (!buildACLCommands(name, subname, nspname, type,
14696                                                           initacls, initracls, owner,
14697                                                           "", fout->remoteVersion, sql))
14698                         exit_horribly(NULL,
14699                                                   "could not parse initial GRANT ACL list (%s) or initial REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14700                                                   initacls, initracls, name, type);
14701                 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(false);\n");
14702         }
14703
14704         if (!buildACLCommands(name, subname, nspname, type,
14705                                                   acls, racls, owner,
14706                                                   "", fout->remoteVersion, sql))
14707                 exit_horribly(NULL,
14708                                           "could not parse GRANT ACL list (%s) or REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14709                                           acls, racls, name, type);
14710
14711         if (sql->len > 0)
14712         {
14713                 PQExpBuffer tag = createPQExpBuffer();
14714
14715                 if (subname)
14716                         appendPQExpBuffer(tag, "COLUMN %s.%s", name, subname);
14717                 else
14718                         appendPQExpBuffer(tag, "%s %s", type, name);
14719
14720                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14721                                          tag->data, nspname,
14722                                          NULL,
14723                                          owner ? owner : "",
14724                                          false, "ACL", SECTION_NONE,
14725                                          sql->data, "", NULL,
14726                                          &(objDumpId), 1,
14727                                          NULL, NULL);
14728                 destroyPQExpBuffer(tag);
14729         }
14730
14731         destroyPQExpBuffer(sql);
14732 }
14733
14734 /*
14735  * dumpSecLabel
14736  *
14737  * This routine is used to dump any security labels associated with the
14738  * object handed to this routine. The routine takes the object type
14739  * and object name (ready to print, except for schema decoration), plus
14740  * the namespace and owner of the object (for labeling the ArchiveEntry),
14741  * plus catalog ID and subid which are the lookup key for pg_seclabel,
14742  * plus the dump ID for the object (for setting a dependency).
14743  * If a matching pg_seclabel entry is found, it is dumped.
14744  *
14745  * Note: although this routine takes a dumpId for dependency purposes,
14746  * that purpose is just to mark the dependency in the emitted dump file
14747  * for possible future use by pg_restore.  We do NOT use it for determining
14748  * ordering of the label in the dump file, because this routine is called
14749  * after dependency sorting occurs.  This routine should be called just after
14750  * calling ArchiveEntry() for the specified object.
14751  */
14752 static void
14753 dumpSecLabel(Archive *fout, const char *type, const char *name,
14754                          const char *namespace, const char *owner,
14755                          CatalogId catalogId, int subid, DumpId dumpId)
14756 {
14757         DumpOptions *dopt = fout->dopt;
14758         SecLabelItem *labels;
14759         int                     nlabels;
14760         int                     i;
14761         PQExpBuffer query;
14762
14763         /* do nothing, if --no-security-labels is supplied */
14764         if (dopt->no_security_labels)
14765                 return;
14766
14767         /* Security labels are schema not data ... except blob labels are data */
14768         if (strcmp(type, "LARGE OBJECT") != 0)
14769         {
14770                 if (dopt->dataOnly)
14771                         return;
14772         }
14773         else
14774         {
14775                 /* We do dump blob security labels in binary-upgrade mode */
14776                 if (dopt->schemaOnly && !dopt->binary_upgrade)
14777                         return;
14778         }
14779
14780         /* Search for security labels associated with catalogId, using table */
14781         nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
14782
14783         query = createPQExpBuffer();
14784
14785         for (i = 0; i < nlabels; i++)
14786         {
14787                 /*
14788                  * Ignore label entries for which the subid doesn't match.
14789                  */
14790                 if (labels[i].objsubid != subid)
14791                         continue;
14792
14793                 appendPQExpBuffer(query,
14794                                                   "SECURITY LABEL FOR %s ON %s ",
14795                                                   fmtId(labels[i].provider), type);
14796                 if (namespace && *namespace)
14797                         appendPQExpBuffer(query, "%s.", fmtId(namespace));
14798                 appendPQExpBuffer(query, "%s IS ", name);
14799                 appendStringLiteralAH(query, labels[i].label, fout);
14800                 appendPQExpBufferStr(query, ";\n");
14801         }
14802
14803         if (query->len > 0)
14804         {
14805                 PQExpBuffer tag = createPQExpBuffer();
14806
14807                 appendPQExpBuffer(tag, "%s %s", type, name);
14808                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14809                                          tag->data, namespace, NULL, owner,
14810                                          false, "SECURITY LABEL", SECTION_NONE,
14811                                          query->data, "", NULL,
14812                                          &(dumpId), 1,
14813                                          NULL, NULL);
14814                 destroyPQExpBuffer(tag);
14815         }
14816
14817         destroyPQExpBuffer(query);
14818 }
14819
14820 /*
14821  * dumpTableSecLabel
14822  *
14823  * As above, but dump security label for both the specified table (or view)
14824  * and its columns.
14825  */
14826 static void
14827 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
14828 {
14829         DumpOptions *dopt = fout->dopt;
14830         SecLabelItem *labels;
14831         int                     nlabels;
14832         int                     i;
14833         PQExpBuffer query;
14834         PQExpBuffer target;
14835
14836         /* do nothing, if --no-security-labels is supplied */
14837         if (dopt->no_security_labels)
14838                 return;
14839
14840         /* SecLabel are SCHEMA not data */
14841         if (dopt->dataOnly)
14842                 return;
14843
14844         /* Search for comments associated with relation, using table */
14845         nlabels = findSecLabels(fout,
14846                                                         tbinfo->dobj.catId.tableoid,
14847                                                         tbinfo->dobj.catId.oid,
14848                                                         &labels);
14849
14850         /* If security labels exist, build SECURITY LABEL statements */
14851         if (nlabels <= 0)
14852                 return;
14853
14854         query = createPQExpBuffer();
14855         target = createPQExpBuffer();
14856
14857         for (i = 0; i < nlabels; i++)
14858         {
14859                 const char *colname;
14860                 const char *provider = labels[i].provider;
14861                 const char *label = labels[i].label;
14862                 int                     objsubid = labels[i].objsubid;
14863
14864                 resetPQExpBuffer(target);
14865                 if (objsubid == 0)
14866                 {
14867                         appendPQExpBuffer(target, "%s %s", reltypename,
14868                                                           fmtQualifiedDumpable(tbinfo));
14869                 }
14870                 else
14871                 {
14872                         colname = getAttrName(objsubid, tbinfo);
14873                         /* first fmtXXX result must be consumed before calling again */
14874                         appendPQExpBuffer(target, "COLUMN %s",
14875                                                           fmtQualifiedDumpable(tbinfo));
14876                         appendPQExpBuffer(target, ".%s", fmtId(colname));
14877                 }
14878                 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
14879                                                   fmtId(provider), target->data);
14880                 appendStringLiteralAH(query, label, fout);
14881                 appendPQExpBufferStr(query, ";\n");
14882         }
14883         if (query->len > 0)
14884         {
14885                 resetPQExpBuffer(target);
14886                 appendPQExpBuffer(target, "%s %s", reltypename,
14887                                                   fmtId(tbinfo->dobj.name));
14888                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14889                                          target->data,
14890                                          tbinfo->dobj.namespace->dobj.name,
14891                                          NULL, tbinfo->rolname,
14892                                          false, "SECURITY LABEL", SECTION_NONE,
14893                                          query->data, "", NULL,
14894                                          &(tbinfo->dobj.dumpId), 1,
14895                                          NULL, NULL);
14896         }
14897         destroyPQExpBuffer(query);
14898         destroyPQExpBuffer(target);
14899 }
14900
14901 /*
14902  * findSecLabels
14903  *
14904  * Find the security label(s), if any, associated with the given object.
14905  * All the objsubid values associated with the given classoid/objoid are
14906  * found with one search.
14907  */
14908 static int
14909 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
14910 {
14911         /* static storage for table of security labels */
14912         static SecLabelItem *labels = NULL;
14913         static int      nlabels = -1;
14914
14915         SecLabelItem *middle = NULL;
14916         SecLabelItem *low;
14917         SecLabelItem *high;
14918         int                     nmatch;
14919
14920         /* Get security labels if we didn't already */
14921         if (nlabels < 0)
14922                 nlabels = collectSecLabels(fout, &labels);
14923
14924         if (nlabels <= 0)                       /* no labels, so no match is possible */
14925         {
14926                 *items = NULL;
14927                 return 0;
14928         }
14929
14930         /*
14931          * Do binary search to find some item matching the object.
14932          */
14933         low = &labels[0];
14934         high = &labels[nlabels - 1];
14935         while (low <= high)
14936         {
14937                 middle = low + (high - low) / 2;
14938
14939                 if (classoid < middle->classoid)
14940                         high = middle - 1;
14941                 else if (classoid > middle->classoid)
14942                         low = middle + 1;
14943                 else if (objoid < middle->objoid)
14944                         high = middle - 1;
14945                 else if (objoid > middle->objoid)
14946                         low = middle + 1;
14947                 else
14948                         break;                          /* found a match */
14949         }
14950
14951         if (low > high)                         /* no matches */
14952         {
14953                 *items = NULL;
14954                 return 0;
14955         }
14956
14957         /*
14958          * Now determine how many items match the object.  The search loop
14959          * invariant still holds: only items between low and high inclusive could
14960          * match.
14961          */
14962         nmatch = 1;
14963         while (middle > low)
14964         {
14965                 if (classoid != middle[-1].classoid ||
14966                         objoid != middle[-1].objoid)
14967                         break;
14968                 middle--;
14969                 nmatch++;
14970         }
14971
14972         *items = middle;
14973
14974         middle += nmatch;
14975         while (middle <= high)
14976         {
14977                 if (classoid != middle->classoid ||
14978                         objoid != middle->objoid)
14979                         break;
14980                 middle++;
14981                 nmatch++;
14982         }
14983
14984         return nmatch;
14985 }
14986
14987 /*
14988  * collectSecLabels
14989  *
14990  * Construct a table of all security labels available for database objects.
14991  * It's much faster to pull them all at once.
14992  *
14993  * The table is sorted by classoid/objid/objsubid for speed in lookup.
14994  */
14995 static int
14996 collectSecLabels(Archive *fout, SecLabelItem **items)
14997 {
14998         PGresult   *res;
14999         PQExpBuffer query;
15000         int                     i_label;
15001         int                     i_provider;
15002         int                     i_classoid;
15003         int                     i_objoid;
15004         int                     i_objsubid;
15005         int                     ntups;
15006         int                     i;
15007         SecLabelItem *labels;
15008
15009         query = createPQExpBuffer();
15010
15011         appendPQExpBufferStr(query,
15012                                                  "SELECT label, provider, classoid, objoid, objsubid "
15013                                                  "FROM pg_catalog.pg_seclabel "
15014                                                  "ORDER BY classoid, objoid, objsubid");
15015
15016         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15017
15018         /* Construct lookup table containing OIDs in numeric form */
15019         i_label = PQfnumber(res, "label");
15020         i_provider = PQfnumber(res, "provider");
15021         i_classoid = PQfnumber(res, "classoid");
15022         i_objoid = PQfnumber(res, "objoid");
15023         i_objsubid = PQfnumber(res, "objsubid");
15024
15025         ntups = PQntuples(res);
15026
15027         labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
15028
15029         for (i = 0; i < ntups; i++)
15030         {
15031                 labels[i].label = PQgetvalue(res, i, i_label);
15032                 labels[i].provider = PQgetvalue(res, i, i_provider);
15033                 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
15034                 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
15035                 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
15036         }
15037
15038         /* Do NOT free the PGresult since we are keeping pointers into it */
15039         destroyPQExpBuffer(query);
15040
15041         *items = labels;
15042         return ntups;
15043 }
15044
15045 /*
15046  * dumpTable
15047  *        write out to fout the declarations (not data) of a user-defined table
15048  */
15049 static void
15050 dumpTable(Archive *fout, TableInfo *tbinfo)
15051 {
15052         DumpOptions *dopt = fout->dopt;
15053         char       *namecopy;
15054
15055         /*
15056          * noop if we are not dumping anything about this table, or if we are
15057          * doing a data-only dump
15058          */
15059         if (!tbinfo->dobj.dump || dopt->dataOnly)
15060                 return;
15061
15062         if (tbinfo->relkind == RELKIND_SEQUENCE)
15063                 dumpSequence(fout, tbinfo);
15064         else
15065                 dumpTableSchema(fout, tbinfo);
15066
15067         /* Handle the ACL here */
15068         namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
15069         if (tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15070         {
15071                 const char *objtype =
15072                 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" : "TABLE";
15073
15074                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15075                                 objtype, namecopy, NULL,
15076                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15077                                 tbinfo->relacl, tbinfo->rrelacl,
15078                                 tbinfo->initrelacl, tbinfo->initrrelacl);
15079         }
15080
15081         /*
15082          * Handle column ACLs, if any.  Note: we pull these with a separate query
15083          * rather than trying to fetch them during getTableAttrs, so that we won't
15084          * miss ACLs on system columns.
15085          */
15086         if (fout->remoteVersion >= 80400 && tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15087         {
15088                 PQExpBuffer query = createPQExpBuffer();
15089                 PGresult   *res;
15090                 int                     i;
15091
15092                 if (fout->remoteVersion >= 90600)
15093                 {
15094                         PQExpBuffer acl_subquery = createPQExpBuffer();
15095                         PQExpBuffer racl_subquery = createPQExpBuffer();
15096                         PQExpBuffer initacl_subquery = createPQExpBuffer();
15097                         PQExpBuffer initracl_subquery = createPQExpBuffer();
15098
15099                         buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
15100                                                         initracl_subquery, "at.attacl", "c.relowner", "'c'",
15101                                                         dopt->binary_upgrade);
15102
15103                         appendPQExpBuffer(query,
15104                                                           "SELECT at.attname, "
15105                                                           "%s AS attacl, "
15106                                                           "%s AS rattacl, "
15107                                                           "%s AS initattacl, "
15108                                                           "%s AS initrattacl "
15109                                                           "FROM pg_catalog.pg_attribute at "
15110                                                           "JOIN pg_catalog.pg_class c ON (at.attrelid = c.oid) "
15111                                                           "LEFT JOIN pg_catalog.pg_init_privs pip ON "
15112                                                           "(at.attrelid = pip.objoid "
15113                                                           "AND pip.classoid = 'pg_catalog.pg_class'::pg_catalog.regclass "
15114                                                           "AND at.attnum = pip.objsubid) "
15115                                                           "WHERE at.attrelid = '%u'::pg_catalog.oid AND "
15116                                                           "NOT at.attisdropped "
15117                                                           "AND ("
15118                                                           "%s IS NOT NULL OR "
15119                                                           "%s IS NOT NULL OR "
15120                                                           "%s IS NOT NULL OR "
15121                                                           "%s IS NOT NULL)"
15122                                                           "ORDER BY at.attnum",
15123                                                           acl_subquery->data,
15124                                                           racl_subquery->data,
15125                                                           initacl_subquery->data,
15126                                                           initracl_subquery->data,
15127                                                           tbinfo->dobj.catId.oid,
15128                                                           acl_subquery->data,
15129                                                           racl_subquery->data,
15130                                                           initacl_subquery->data,
15131                                                           initracl_subquery->data);
15132
15133                         destroyPQExpBuffer(acl_subquery);
15134                         destroyPQExpBuffer(racl_subquery);
15135                         destroyPQExpBuffer(initacl_subquery);
15136                         destroyPQExpBuffer(initracl_subquery);
15137                 }
15138                 else
15139                 {
15140                         appendPQExpBuffer(query,
15141                                                           "SELECT attname, attacl, NULL as rattacl, "
15142                                                           "NULL AS initattacl, NULL AS initrattacl "
15143                                                           "FROM pg_catalog.pg_attribute "
15144                                                           "WHERE attrelid = '%u'::pg_catalog.oid AND NOT attisdropped "
15145                                                           "AND attacl IS NOT NULL "
15146                                                           "ORDER BY attnum",
15147                                                           tbinfo->dobj.catId.oid);
15148                 }
15149
15150                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15151
15152                 for (i = 0; i < PQntuples(res); i++)
15153                 {
15154                         char       *attname = PQgetvalue(res, i, 0);
15155                         char       *attacl = PQgetvalue(res, i, 1);
15156                         char       *rattacl = PQgetvalue(res, i, 2);
15157                         char       *initattacl = PQgetvalue(res, i, 3);
15158                         char       *initrattacl = PQgetvalue(res, i, 4);
15159                         char       *attnamecopy;
15160
15161                         attnamecopy = pg_strdup(fmtId(attname));
15162                         /* Column's GRANT type is always TABLE */
15163                         dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15164                                         "TABLE", namecopy, attnamecopy,
15165                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15166                                         attacl, rattacl, initattacl, initrattacl);
15167                         free(attnamecopy);
15168                 }
15169                 PQclear(res);
15170                 destroyPQExpBuffer(query);
15171         }
15172
15173         free(namecopy);
15174
15175         return;
15176 }
15177
15178 /*
15179  * Create the AS clause for a view or materialized view. The semicolon is
15180  * stripped because a materialized view must add a WITH NO DATA clause.
15181  *
15182  * This returns a new buffer which must be freed by the caller.
15183  */
15184 static PQExpBuffer
15185 createViewAsClause(Archive *fout, TableInfo *tbinfo)
15186 {
15187         PQExpBuffer query = createPQExpBuffer();
15188         PQExpBuffer result = createPQExpBuffer();
15189         PGresult   *res;
15190         int                     len;
15191
15192         /* Fetch the view definition */
15193         appendPQExpBuffer(query,
15194                                           "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
15195                                           tbinfo->dobj.catId.oid);
15196
15197         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15198
15199         if (PQntuples(res) != 1)
15200         {
15201                 if (PQntuples(res) < 1)
15202                         exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
15203                                                   tbinfo->dobj.name);
15204                 else
15205                         exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
15206                                                   tbinfo->dobj.name);
15207         }
15208
15209         len = PQgetlength(res, 0, 0);
15210
15211         if (len == 0)
15212                 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
15213                                           tbinfo->dobj.name);
15214
15215         /* Strip off the trailing semicolon so that other things may follow. */
15216         Assert(PQgetvalue(res, 0, 0)[len - 1] == ';');
15217         appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
15218
15219         PQclear(res);
15220         destroyPQExpBuffer(query);
15221
15222         return result;
15223 }
15224
15225 /*
15226  * Create a dummy AS clause for a view.  This is used when the real view
15227  * definition has to be postponed because of circular dependencies.
15228  * We must duplicate the view's external properties -- column names and types
15229  * (including collation) -- so that it works for subsequent references.
15230  *
15231  * This returns a new buffer which must be freed by the caller.
15232  */
15233 static PQExpBuffer
15234 createDummyViewAsClause(Archive *fout, TableInfo *tbinfo)
15235 {
15236         PQExpBuffer result = createPQExpBuffer();
15237         int                     j;
15238
15239         appendPQExpBufferStr(result, "SELECT");
15240
15241         for (j = 0; j < tbinfo->numatts; j++)
15242         {
15243                 if (j > 0)
15244                         appendPQExpBufferChar(result, ',');
15245                 appendPQExpBufferStr(result, "\n    ");
15246
15247                 appendPQExpBuffer(result, "NULL::%s", tbinfo->atttypnames[j]);
15248
15249                 /*
15250                  * Must add collation if not default for the type, because CREATE OR
15251                  * REPLACE VIEW won't change it
15252                  */
15253                 if (OidIsValid(tbinfo->attcollation[j]))
15254                 {
15255                         CollInfo   *coll;
15256
15257                         coll = findCollationByOid(tbinfo->attcollation[j]);
15258                         if (coll)
15259                                 appendPQExpBuffer(result, " COLLATE %s",
15260                                                                   fmtQualifiedDumpable(coll));
15261                 }
15262
15263                 appendPQExpBuffer(result, " AS %s", fmtId(tbinfo->attnames[j]));
15264         }
15265
15266         return result;
15267 }
15268
15269 /*
15270  * dumpTableSchema
15271  *        write the declaration (not data) of one user-defined table or view
15272  */
15273 static void
15274 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
15275 {
15276         DumpOptions *dopt = fout->dopt;
15277         PQExpBuffer q = createPQExpBuffer();
15278         PQExpBuffer delq = createPQExpBuffer();
15279         char       *qrelname;
15280         char       *qualrelname;
15281         int                     numParents;
15282         TableInfo **parents;
15283         int                     actual_atts;    /* number of attrs in this CREATE statement */
15284         const char *reltypename;
15285         char       *storage;
15286         char       *srvname;
15287         char       *ftoptions;
15288         int                     j,
15289                                 k;
15290
15291         qrelname = pg_strdup(fmtId(tbinfo->dobj.name));
15292         qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
15293
15294         if (dopt->binary_upgrade)
15295                 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
15296                                                                                                 tbinfo->dobj.catId.oid);
15297
15298         /* Is it a table or a view? */
15299         if (tbinfo->relkind == RELKIND_VIEW)
15300         {
15301                 PQExpBuffer result;
15302
15303                 /*
15304                  * Note: keep this code in sync with the is_view case in dumpRule()
15305                  */
15306
15307                 reltypename = "VIEW";
15308
15309                 appendPQExpBuffer(delq, "DROP VIEW %s;\n", qualrelname);
15310
15311                 if (dopt->binary_upgrade)
15312                         binary_upgrade_set_pg_class_oids(fout, q,
15313                                                                                          tbinfo->dobj.catId.oid, false);
15314
15315                 appendPQExpBuffer(q, "CREATE VIEW %s", qualrelname);
15316
15317                 if (tbinfo->dummy_view)
15318                         result = createDummyViewAsClause(fout, tbinfo);
15319                 else
15320                 {
15321                         if (nonemptyReloptions(tbinfo->reloptions))
15322                         {
15323                                 appendPQExpBufferStr(q, " WITH (");
15324                                 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15325                                 appendPQExpBufferChar(q, ')');
15326                         }
15327                         result = createViewAsClause(fout, tbinfo);
15328                 }
15329                 appendPQExpBuffer(q, " AS\n%s", result->data);
15330                 destroyPQExpBuffer(result);
15331
15332                 if (tbinfo->checkoption != NULL && !tbinfo->dummy_view)
15333                         appendPQExpBuffer(q, "\n  WITH %s CHECK OPTION", tbinfo->checkoption);
15334                 appendPQExpBufferStr(q, ";\n");
15335         }
15336         else
15337         {
15338                 switch (tbinfo->relkind)
15339                 {
15340                         case RELKIND_FOREIGN_TABLE:
15341                                 {
15342                                         PQExpBuffer query = createPQExpBuffer();
15343                                         PGresult   *res;
15344                                         int                     i_srvname;
15345                                         int                     i_ftoptions;
15346
15347                                         reltypename = "FOREIGN TABLE";
15348
15349                                         /* retrieve name of foreign server and generic options */
15350                                         appendPQExpBuffer(query,
15351                                                                           "SELECT fs.srvname, "
15352                                                                           "pg_catalog.array_to_string(ARRAY("
15353                                                                           "SELECT pg_catalog.quote_ident(option_name) || "
15354                                                                           "' ' || pg_catalog.quote_literal(option_value) "
15355                                                                           "FROM pg_catalog.pg_options_to_table(ftoptions) "
15356                                                                           "ORDER BY option_name"
15357                                                                           "), E',\n    ') AS ftoptions "
15358                                                                           "FROM pg_catalog.pg_foreign_table ft "
15359                                                                           "JOIN pg_catalog.pg_foreign_server fs "
15360                                                                           "ON (fs.oid = ft.ftserver) "
15361                                                                           "WHERE ft.ftrelid = '%u'",
15362                                                                           tbinfo->dobj.catId.oid);
15363                                         res = ExecuteSqlQueryForSingleRow(fout, query->data);
15364                                         i_srvname = PQfnumber(res, "srvname");
15365                                         i_ftoptions = PQfnumber(res, "ftoptions");
15366                                         srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
15367                                         ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
15368                                         PQclear(res);
15369                                         destroyPQExpBuffer(query);
15370                                         break;
15371                                 }
15372                         case RELKIND_MATVIEW:
15373                                 reltypename = "MATERIALIZED VIEW";
15374                                 srvname = NULL;
15375                                 ftoptions = NULL;
15376                                 break;
15377                         default:
15378                                 reltypename = "TABLE";
15379                                 srvname = NULL;
15380                                 ftoptions = NULL;
15381                 }
15382
15383                 numParents = tbinfo->numParents;
15384                 parents = tbinfo->parents;
15385
15386                 appendPQExpBuffer(delq, "DROP %s %s;\n", reltypename, qualrelname);
15387
15388                 if (dopt->binary_upgrade)
15389                         binary_upgrade_set_pg_class_oids(fout, q,
15390                                                                                          tbinfo->dobj.catId.oid, false);
15391
15392                 appendPQExpBuffer(q, "CREATE %s%s %s",
15393                                                   tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
15394                                                   "UNLOGGED " : "",
15395                                                   reltypename,
15396                                                   qualrelname);
15397
15398                 /*
15399                  * Attach to type, if reloftype; except in case of a binary upgrade,
15400                  * we dump the table normally and attach it to the type afterward.
15401                  */
15402                 if (tbinfo->reloftype && !dopt->binary_upgrade)
15403                         appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
15404
15405                 /*
15406                  * If the table is a partition, dump it as such; except in the case of
15407                  * a binary upgrade, we dump the table normally and attach it to the
15408                  * parent afterward.
15409                  */
15410                 if (tbinfo->ispartition && !dopt->binary_upgrade)
15411                 {
15412                         TableInfo  *parentRel = tbinfo->parents[0];
15413
15414                         /*
15415                          * With partitions, unlike inheritance, there can only be one
15416                          * parent.
15417                          */
15418                         if (tbinfo->numParents != 1)
15419                                 exit_horribly(NULL, "invalid number of parents %d for table \"%s\"\n",
15420                                                           tbinfo->numParents, tbinfo->dobj.name);
15421
15422                         appendPQExpBuffer(q, " PARTITION OF %s",
15423                                                           fmtQualifiedDumpable(parentRel));
15424                 }
15425
15426                 if (tbinfo->relkind != RELKIND_MATVIEW)
15427                 {
15428                         /* Dump the attributes */
15429                         actual_atts = 0;
15430                         for (j = 0; j < tbinfo->numatts; j++)
15431                         {
15432                                 /*
15433                                  * Normally, dump if it's locally defined in this table, and
15434                                  * not dropped.  But for binary upgrade, we'll dump all the
15435                                  * columns, and then fix up the dropped and nonlocal cases
15436                                  * below.
15437                                  */
15438                                 if (shouldPrintColumn(dopt, tbinfo, j))
15439                                 {
15440                                         /*
15441                                          * Default value --- suppress if to be printed separately.
15442                                          */
15443                                         bool            has_default = (tbinfo->attrdefs[j] != NULL &&
15444                                                                                            !tbinfo->attrdefs[j]->separate);
15445
15446                                         /*
15447                                          * Not Null constraint --- suppress if inherited, except
15448                                          * in binary-upgrade case where that won't work.
15449                                          */
15450                                         bool            has_notnull = (tbinfo->notnull[j] &&
15451                                                                                            (!tbinfo->inhNotNull[j] ||
15452                                                                                                 dopt->binary_upgrade));
15453
15454                                         /*
15455                                          * Skip column if fully defined by reloftype or the
15456                                          * partition parent.
15457                                          */
15458                                         if ((tbinfo->reloftype || tbinfo->ispartition) &&
15459                                                 !has_default && !has_notnull && !dopt->binary_upgrade)
15460                                                 continue;
15461
15462                                         /* Format properly if not first attr */
15463                                         if (actual_atts == 0)
15464                                                 appendPQExpBufferStr(q, " (");
15465                                         else
15466                                                 appendPQExpBufferChar(q, ',');
15467                                         appendPQExpBufferStr(q, "\n    ");
15468                                         actual_atts++;
15469
15470                                         /* Attribute name */
15471                                         appendPQExpBufferStr(q, fmtId(tbinfo->attnames[j]));
15472
15473                                         if (tbinfo->attisdropped[j])
15474                                         {
15475                                                 /*
15476                                                  * ALTER TABLE DROP COLUMN clears
15477                                                  * pg_attribute.atttypid, so we will not have gotten a
15478                                                  * valid type name; insert INTEGER as a stopgap. We'll
15479                                                  * clean things up later.
15480                                                  */
15481                                                 appendPQExpBufferStr(q, " INTEGER /* dummy */");
15482                                                 /* Skip all the rest, too */
15483                                                 continue;
15484                                         }
15485
15486                                         /*
15487                                          * Attribute type
15488                                          *
15489                                          * In binary-upgrade mode, we always include the type. If
15490                                          * we aren't in binary-upgrade mode, then we skip the type
15491                                          * when creating a typed table ('OF type_name') or a
15492                                          * partition ('PARTITION OF'), since the type comes from
15493                                          * the parent/partitioned table.
15494                                          */
15495                                         if (dopt->binary_upgrade || (!tbinfo->reloftype && !tbinfo->ispartition))
15496                                         {
15497                                                 appendPQExpBuffer(q, " %s",
15498                                                                                   tbinfo->atttypnames[j]);
15499                                         }
15500
15501                                         /* Add collation if not default for the type */
15502                                         if (OidIsValid(tbinfo->attcollation[j]))
15503                                         {
15504                                                 CollInfo   *coll;
15505
15506                                                 coll = findCollationByOid(tbinfo->attcollation[j]);
15507                                                 if (coll)
15508                                                         appendPQExpBuffer(q, " COLLATE %s",
15509                                                                                           fmtQualifiedDumpable(coll));
15510                                         }
15511
15512                                         if (has_default)
15513                                                 appendPQExpBuffer(q, " DEFAULT %s",
15514                                                                                   tbinfo->attrdefs[j]->adef_expr);
15515
15516                                         if (has_notnull)
15517                                                 appendPQExpBufferStr(q, " NOT NULL");
15518                                 }
15519                         }
15520
15521                         /*
15522                          * Add non-inherited CHECK constraints, if any.
15523                          */
15524                         for (j = 0; j < tbinfo->ncheck; j++)
15525                         {
15526                                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
15527
15528                                 if (constr->separate || !constr->conislocal)
15529                                         continue;
15530
15531                                 if (actual_atts == 0)
15532                                         appendPQExpBufferStr(q, " (\n    ");
15533                                 else
15534                                         appendPQExpBufferStr(q, ",\n    ");
15535
15536                                 appendPQExpBuffer(q, "CONSTRAINT %s ",
15537                                                                   fmtId(constr->dobj.name));
15538                                 appendPQExpBufferStr(q, constr->condef);
15539
15540                                 actual_atts++;
15541                         }
15542
15543                         if (actual_atts)
15544                                 appendPQExpBufferStr(q, "\n)");
15545                         else if (!((tbinfo->reloftype || tbinfo->ispartition) &&
15546                                            !dopt->binary_upgrade))
15547                         {
15548                                 /*
15549                                  * We must have a parenthesized attribute list, even though
15550                                  * empty, when not using the OF TYPE or PARTITION OF syntax.
15551                                  */
15552                                 appendPQExpBufferStr(q, " (\n)");
15553                         }
15554
15555                         if (tbinfo->ispartition && !dopt->binary_upgrade)
15556                         {
15557                                 appendPQExpBufferChar(q, '\n');
15558                                 appendPQExpBufferStr(q, tbinfo->partbound);
15559                         }
15560
15561                         /* Emit the INHERITS clause, except if this is a partition. */
15562                         if (numParents > 0 &&
15563                                 !tbinfo->ispartition &&
15564                                 !dopt->binary_upgrade)
15565                         {
15566                                 appendPQExpBufferStr(q, "\nINHERITS (");
15567                                 for (k = 0; k < numParents; k++)
15568                                 {
15569                                         TableInfo  *parentRel = parents[k];
15570
15571                                         if (k > 0)
15572                                                 appendPQExpBufferStr(q, ", ");
15573                                         appendPQExpBufferStr(q, fmtQualifiedDumpable(parentRel));
15574                                 }
15575                                 appendPQExpBufferChar(q, ')');
15576                         }
15577
15578                         if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15579                                 appendPQExpBuffer(q, "\nPARTITION BY %s", tbinfo->partkeydef);
15580
15581                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
15582                                 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
15583                 }
15584
15585                 if (nonemptyReloptions(tbinfo->reloptions) ||
15586                         nonemptyReloptions(tbinfo->toast_reloptions))
15587                 {
15588                         bool            addcomma = false;
15589
15590                         appendPQExpBufferStr(q, "\nWITH (");
15591                         if (nonemptyReloptions(tbinfo->reloptions))
15592                         {
15593                                 addcomma = true;
15594                                 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15595                         }
15596                         if (nonemptyReloptions(tbinfo->toast_reloptions))
15597                         {
15598                                 if (addcomma)
15599                                         appendPQExpBufferStr(q, ", ");
15600                                 appendReloptionsArrayAH(q, tbinfo->toast_reloptions, "toast.",
15601                                                                                 fout);
15602                         }
15603                         appendPQExpBufferChar(q, ')');
15604                 }
15605
15606                 /* Dump generic options if any */
15607                 if (ftoptions && ftoptions[0])
15608                         appendPQExpBuffer(q, "\nOPTIONS (\n    %s\n)", ftoptions);
15609
15610                 /*
15611                  * For materialized views, create the AS clause just like a view. At
15612                  * this point, we always mark the view as not populated.
15613                  */
15614                 if (tbinfo->relkind == RELKIND_MATVIEW)
15615                 {
15616                         PQExpBuffer result;
15617
15618                         result = createViewAsClause(fout, tbinfo);
15619                         appendPQExpBuffer(q, " AS\n%s\n  WITH NO DATA;\n",
15620                                                           result->data);
15621                         destroyPQExpBuffer(result);
15622                 }
15623                 else
15624                         appendPQExpBufferStr(q, ";\n");
15625
15626                 /*
15627                  * To create binary-compatible heap files, we have to ensure the same
15628                  * physical column order, including dropped columns, as in the
15629                  * original.  Therefore, we create dropped columns above and drop them
15630                  * here, also updating their attlen/attalign values so that the
15631                  * dropped column can be skipped properly.  (We do not bother with
15632                  * restoring the original attbyval setting.)  Also, inheritance
15633                  * relationships are set up by doing ALTER TABLE INHERIT rather than
15634                  * using an INHERITS clause --- the latter would possibly mess up the
15635                  * column order.  That also means we have to take care about setting
15636                  * attislocal correctly, plus fix up any inherited CHECK constraints.
15637                  * Analogously, we set up typed tables using ALTER TABLE / OF here.
15638                  *
15639                  * We process foreign and partitioned tables here, even though they
15640                  * lack heap storage, because they can participate in inheritance
15641                  * relationships and we want this stuff to be consistent across the
15642                  * inheritance tree.  We can exclude indexes, toast tables, sequences
15643                  * and matviews, even though they have storage, because we don't
15644                  * support altering or dropping columns in them, nor can they be part
15645                  * of inheritance trees.
15646                  */
15647                 if (dopt->binary_upgrade &&
15648                         (tbinfo->relkind == RELKIND_RELATION ||
15649                          tbinfo->relkind == RELKIND_FOREIGN_TABLE ||
15650                          tbinfo->relkind == RELKIND_PARTITIONED_TABLE))
15651                 {
15652                         for (j = 0; j < tbinfo->numatts; j++)
15653                         {
15654                                 if (tbinfo->attisdropped[j])
15655                                 {
15656                                         appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate dropped column.\n");
15657                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
15658                                                                           "SET attlen = %d, "
15659                                                                           "attalign = '%c', attbyval = false\n"
15660                                                                           "WHERE attname = ",
15661                                                                           tbinfo->attlen[j],
15662                                                                           tbinfo->attalign[j]);
15663                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15664                                         appendPQExpBufferStr(q, "\n  AND attrelid = ");
15665                                         appendStringLiteralAH(q, qualrelname, fout);
15666                                         appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15667
15668                                         if (tbinfo->relkind == RELKIND_RELATION ||
15669                                                 tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15670                                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15671                                                                                   qualrelname);
15672                                         else
15673                                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE ONLY %s ",
15674                                                                                   qualrelname);
15675                                         appendPQExpBuffer(q, "DROP COLUMN %s;\n",
15676                                                                           fmtId(tbinfo->attnames[j]));
15677                                 }
15678                                 else if (!tbinfo->attislocal[j])
15679                                 {
15680                                         appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate inherited column.\n");
15681                                         appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_attribute\n"
15682                                                                                  "SET attislocal = false\n"
15683                                                                                  "WHERE attname = ");
15684                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15685                                         appendPQExpBufferStr(q, "\n  AND attrelid = ");
15686                                         appendStringLiteralAH(q, qualrelname, fout);
15687                                         appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15688                                 }
15689                         }
15690
15691                         for (k = 0; k < tbinfo->ncheck; k++)
15692                         {
15693                                 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
15694
15695                                 if (constr->separate || constr->conislocal)
15696                                         continue;
15697
15698                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inherited constraint.\n");
15699                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15700                                                                   qualrelname);
15701                                 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
15702                                                                   fmtId(constr->dobj.name));
15703                                 appendPQExpBuffer(q, "%s;\n", constr->condef);
15704                                 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_constraint\n"
15705                                                                          "SET conislocal = false\n"
15706                                                                          "WHERE contype = 'c' AND conname = ");
15707                                 appendStringLiteralAH(q, constr->dobj.name, fout);
15708                                 appendPQExpBufferStr(q, "\n  AND conrelid = ");
15709                                 appendStringLiteralAH(q, qualrelname, fout);
15710                                 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15711                         }
15712
15713                         if (numParents > 0)
15714                         {
15715                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inheritance and partitioning this way.\n");
15716                                 for (k = 0; k < numParents; k++)
15717                                 {
15718                                         TableInfo  *parentRel = parents[k];
15719
15720                                         /* In the partitioning case, we alter the parent */
15721                                         if (tbinfo->ispartition)
15722                                                 appendPQExpBuffer(q,
15723                                                                                   "ALTER TABLE ONLY %s ATTACH PARTITION ",
15724                                                                                   fmtQualifiedDumpable(parentRel));
15725                                         else
15726                                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
15727                                                                                   qualrelname);
15728
15729                                         /* Partition needs specifying the bounds */
15730                                         if (tbinfo->ispartition)
15731                                                 appendPQExpBuffer(q, "%s %s;\n",
15732                                                                                   qualrelname,
15733                                                                                   tbinfo->partbound);
15734                                         else
15735                                                 appendPQExpBuffer(q, "%s;\n",
15736                                                                                   fmtQualifiedDumpable(parentRel));
15737                                 }
15738                         }
15739
15740                         if (tbinfo->reloftype)
15741                         {
15742                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up typed tables this way.\n");
15743                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
15744                                                                   qualrelname,
15745                                                                   tbinfo->reloftype);
15746                         }
15747                 }
15748
15749                 /*
15750                  * In binary_upgrade mode, arrange to restore the old relfrozenxid and
15751                  * relminmxid of all vacuumable relations.  (While vacuum.c processes
15752                  * TOAST tables semi-independently, here we see them only as children
15753                  * of other relations; so this "if" lacks RELKIND_TOASTVALUE, and the
15754                  * child toast table is handled below.)
15755                  */
15756                 if (dopt->binary_upgrade &&
15757                         (tbinfo->relkind == RELKIND_RELATION ||
15758                          tbinfo->relkind == RELKIND_MATVIEW))
15759                 {
15760                         appendPQExpBufferStr(q, "\n-- For binary upgrade, set heap's relfrozenxid and relminmxid\n");
15761                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
15762                                                           "SET relfrozenxid = '%u', relminmxid = '%u'\n"
15763                                                           "WHERE oid = ",
15764                                                           tbinfo->frozenxid, tbinfo->minmxid);
15765                         appendStringLiteralAH(q, qualrelname, fout);
15766                         appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15767
15768                         if (tbinfo->toast_oid)
15769                         {
15770                                 /*
15771                                  * The toast table will have the same OID at restore, so we
15772                                  * can safely target it by OID.
15773                                  */
15774                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, set toast's relfrozenxid and relminmxid\n");
15775                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
15776                                                                   "SET relfrozenxid = '%u', relminmxid = '%u'\n"
15777                                                                   "WHERE oid = '%u';\n",
15778                                                                   tbinfo->toast_frozenxid,
15779                                                                   tbinfo->toast_minmxid, tbinfo->toast_oid);
15780                         }
15781                 }
15782
15783                 /*
15784                  * In binary_upgrade mode, restore matviews' populated status by
15785                  * poking pg_class directly.  This is pretty ugly, but we can't use
15786                  * REFRESH MATERIALIZED VIEW since it's possible that some underlying
15787                  * matview is not populated even though this matview is; in any case,
15788                  * we want to transfer the matview's heap storage, not run REFRESH.
15789                  */
15790                 if (dopt->binary_upgrade && tbinfo->relkind == RELKIND_MATVIEW &&
15791                         tbinfo->relispopulated)
15792                 {
15793                         appendPQExpBufferStr(q, "\n-- For binary upgrade, mark materialized view as populated\n");
15794                         appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_class\n"
15795                                                                  "SET relispopulated = 't'\n"
15796                                                                  "WHERE oid = ");
15797                         appendStringLiteralAH(q, qualrelname, fout);
15798                         appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15799                 }
15800
15801                 /*
15802                  * Dump additional per-column properties that we can't handle in the
15803                  * main CREATE TABLE command.
15804                  */
15805                 for (j = 0; j < tbinfo->numatts; j++)
15806                 {
15807                         /* None of this applies to dropped columns */
15808                         if (tbinfo->attisdropped[j])
15809                                 continue;
15810
15811                         /*
15812                          * If we didn't dump the column definition explicitly above, and
15813                          * it is NOT NULL and did not inherit that property from a parent,
15814                          * we have to mark it separately.
15815                          */
15816                         if (!shouldPrintColumn(dopt, tbinfo, j) &&
15817                                 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
15818                         {
15819                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15820                                                                   qualrelname);
15821                                 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
15822                                                                   fmtId(tbinfo->attnames[j]));
15823                         }
15824
15825                         /*
15826                          * Dump per-column statistics information. We only issue an ALTER
15827                          * TABLE statement if the attstattarget entry for this column is
15828                          * non-negative (i.e. it's not the default value)
15829                          */
15830                         if (tbinfo->attstattarget[j] >= 0)
15831                         {
15832                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15833                                                                   qualrelname);
15834                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15835                                                                   fmtId(tbinfo->attnames[j]));
15836                                 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
15837                                                                   tbinfo->attstattarget[j]);
15838                         }
15839
15840                         /*
15841                          * Dump per-column storage information.  The statement is only
15842                          * dumped if the storage has been changed from the type's default.
15843                          */
15844                         if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
15845                         {
15846                                 switch (tbinfo->attstorage[j])
15847                                 {
15848                                         case 'p':
15849                                                 storage = "PLAIN";
15850                                                 break;
15851                                         case 'e':
15852                                                 storage = "EXTERNAL";
15853                                                 break;
15854                                         case 'm':
15855                                                 storage = "MAIN";
15856                                                 break;
15857                                         case 'x':
15858                                                 storage = "EXTENDED";
15859                                                 break;
15860                                         default:
15861                                                 storage = NULL;
15862                                 }
15863
15864                                 /*
15865                                  * Only dump the statement if it's a storage type we recognize
15866                                  */
15867                                 if (storage != NULL)
15868                                 {
15869                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15870                                                                           qualrelname);
15871                                         appendPQExpBuffer(q, "ALTER COLUMN %s ",
15872                                                                           fmtId(tbinfo->attnames[j]));
15873                                         appendPQExpBuffer(q, "SET STORAGE %s;\n",
15874                                                                           storage);
15875                                 }
15876                         }
15877
15878                         /*
15879                          * Dump per-column attributes.
15880                          */
15881                         if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
15882                         {
15883                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15884                                                                   qualrelname);
15885                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15886                                                                   fmtId(tbinfo->attnames[j]));
15887                                 appendPQExpBuffer(q, "SET (%s);\n",
15888                                                                   tbinfo->attoptions[j]);
15889                         }
15890
15891                         /*
15892                          * Dump per-column fdw options.
15893                          */
15894                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
15895                                 tbinfo->attfdwoptions[j] &&
15896                                 tbinfo->attfdwoptions[j][0] != '\0')
15897                         {
15898                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
15899                                                                   qualrelname);
15900                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15901                                                                   fmtId(tbinfo->attnames[j]));
15902                                 appendPQExpBuffer(q, "OPTIONS (\n    %s\n);\n",
15903                                                                   tbinfo->attfdwoptions[j]);
15904                         }
15905                 }
15906         }
15907
15908         /*
15909          * dump properties we only have ALTER TABLE syntax for
15910          */
15911         if ((tbinfo->relkind == RELKIND_RELATION ||
15912                  tbinfo->relkind == RELKIND_PARTITIONED_TABLE ||
15913                  tbinfo->relkind == RELKIND_MATVIEW) &&
15914                 tbinfo->relreplident != REPLICA_IDENTITY_DEFAULT)
15915         {
15916                 if (tbinfo->relreplident == REPLICA_IDENTITY_INDEX)
15917                 {
15918                         /* nothing to do, will be set when the index is dumped */
15919                 }
15920                 else if (tbinfo->relreplident == REPLICA_IDENTITY_NOTHING)
15921                 {
15922                         appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY NOTHING;\n",
15923                                                           qualrelname);
15924                 }
15925                 else if (tbinfo->relreplident == REPLICA_IDENTITY_FULL)
15926                 {
15927                         appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY FULL;\n",
15928                                                           qualrelname);
15929                 }
15930         }
15931
15932         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE && tbinfo->hasoids)
15933                 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s SET WITH OIDS;\n",
15934                                                   qualrelname);
15935
15936         if (tbinfo->forcerowsec)
15937                 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s FORCE ROW LEVEL SECURITY;\n",
15938                                                   qualrelname);
15939
15940         if (dopt->binary_upgrade)
15941                 binary_upgrade_extension_member(q, &tbinfo->dobj,
15942                                                                                 reltypename, qrelname,
15943                                                                                 tbinfo->dobj.namespace->dobj.name);
15944
15945         if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
15946                 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15947                                          tbinfo->dobj.name,
15948                                          tbinfo->dobj.namespace->dobj.name,
15949                                          (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
15950                                          tbinfo->rolname,
15951                                          (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
15952                                          reltypename,
15953                                          tbinfo->postponed_def ?
15954                                          SECTION_POST_DATA : SECTION_PRE_DATA,
15955                                          q->data, delq->data, NULL,
15956                                          NULL, 0,
15957                                          NULL, NULL);
15958
15959
15960         /* Dump Table Comments */
15961         if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
15962                 dumpTableComment(fout, tbinfo, reltypename);
15963
15964         /* Dump Table Security Labels */
15965         if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
15966                 dumpTableSecLabel(fout, tbinfo, reltypename);
15967
15968         /* Dump comments on inlined table constraints */
15969         for (j = 0; j < tbinfo->ncheck; j++)
15970         {
15971                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
15972
15973                 if (constr->separate || !constr->conislocal)
15974                         continue;
15975
15976                 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
15977                         dumpTableConstraintComment(fout, constr);
15978         }
15979
15980         destroyPQExpBuffer(q);
15981         destroyPQExpBuffer(delq);
15982         free(qrelname);
15983         free(qualrelname);
15984 }
15985
15986 /*
15987  * dumpAttrDef --- dump an attribute's default-value declaration
15988  */
15989 static void
15990 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
15991 {
15992         DumpOptions *dopt = fout->dopt;
15993         TableInfo  *tbinfo = adinfo->adtable;
15994         int                     adnum = adinfo->adnum;
15995         PQExpBuffer q;
15996         PQExpBuffer delq;
15997         char       *qualrelname;
15998         char       *tag;
15999
16000         /* Skip if table definition not to be dumped */
16001         if (!tbinfo->dobj.dump || dopt->dataOnly)
16002                 return;
16003
16004         /* Skip if not "separate"; it was dumped in the table's definition */
16005         if (!adinfo->separate)
16006                 return;
16007
16008         q = createPQExpBuffer();
16009         delq = createPQExpBuffer();
16010
16011         qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
16012
16013         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16014                                           qualrelname);
16015         appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
16016                                           fmtId(tbinfo->attnames[adnum - 1]),
16017                                           adinfo->adef_expr);
16018
16019         appendPQExpBuffer(delq, "ALTER TABLE %s ",
16020                                           qualrelname);
16021         appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
16022                                           fmtId(tbinfo->attnames[adnum - 1]));
16023
16024         tag = psprintf("%s %s", tbinfo->dobj.name, tbinfo->attnames[adnum - 1]);
16025
16026         if (adinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16027                 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
16028                                          tag,
16029                                          tbinfo->dobj.namespace->dobj.name,
16030                                          NULL,
16031                                          tbinfo->rolname,
16032                                          false, "DEFAULT", SECTION_PRE_DATA,
16033                                          q->data, delq->data, NULL,
16034                                          NULL, 0,
16035                                          NULL, NULL);
16036
16037         free(tag);
16038         destroyPQExpBuffer(q);
16039         destroyPQExpBuffer(delq);
16040         free(qualrelname);
16041 }
16042
16043 /*
16044  * getAttrName: extract the correct name for an attribute
16045  *
16046  * The array tblInfo->attnames[] only provides names of user attributes;
16047  * if a system attribute number is supplied, we have to fake it.
16048  * We also do a little bit of bounds checking for safety's sake.
16049  */
16050 static const char *
16051 getAttrName(int attrnum, TableInfo *tblInfo)
16052 {
16053         if (attrnum > 0 && attrnum <= tblInfo->numatts)
16054                 return tblInfo->attnames[attrnum - 1];
16055         switch (attrnum)
16056         {
16057                 case SelfItemPointerAttributeNumber:
16058                         return "ctid";
16059                 case ObjectIdAttributeNumber:
16060                         return "oid";
16061                 case MinTransactionIdAttributeNumber:
16062                         return "xmin";
16063                 case MinCommandIdAttributeNumber:
16064                         return "cmin";
16065                 case MaxTransactionIdAttributeNumber:
16066                         return "xmax";
16067                 case MaxCommandIdAttributeNumber:
16068                         return "cmax";
16069                 case TableOidAttributeNumber:
16070                         return "tableoid";
16071         }
16072         exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
16073                                   attrnum, tblInfo->dobj.name);
16074         return NULL;                            /* keep compiler quiet */
16075 }
16076
16077 /*
16078  * dumpIndex
16079  *        write out to fout a user-defined index
16080  */
16081 static void
16082 dumpIndex(Archive *fout, IndxInfo *indxinfo)
16083 {
16084         DumpOptions *dopt = fout->dopt;
16085         TableInfo  *tbinfo = indxinfo->indextable;
16086         bool            is_constraint = (indxinfo->indexconstraint != 0);
16087         PQExpBuffer q;
16088         PQExpBuffer delq;
16089         char       *qindxname;
16090
16091         if (dopt->dataOnly)
16092                 return;
16093
16094         q = createPQExpBuffer();
16095         delq = createPQExpBuffer();
16096
16097         qindxname = pg_strdup(fmtId(indxinfo->dobj.name));
16098
16099         /*
16100          * If there's an associated constraint, don't dump the index per se, but
16101          * do dump any comment for it.  (This is safe because dependency ordering
16102          * will have ensured the constraint is emitted first.)  Note that the
16103          * emitted comment has to be shown as depending on the constraint, not the
16104          * index, in such cases.
16105          */
16106         if (!is_constraint)
16107         {
16108                 if (dopt->binary_upgrade)
16109                         binary_upgrade_set_pg_class_oids(fout, q,
16110                                                                                          indxinfo->dobj.catId.oid, true);
16111
16112                 /* Plain secondary index */
16113                 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
16114
16115                 /* If the index is clustered, we need to record that. */
16116                 if (indxinfo->indisclustered)
16117                 {
16118                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16119                                                           fmtQualifiedDumpable(tbinfo));
16120                         /* index name is not qualified in this syntax */
16121                         appendPQExpBuffer(q, " ON %s;\n",
16122                                                           qindxname);
16123                 }
16124
16125                 /* If the index defines identity, we need to record that. */
16126                 if (indxinfo->indisreplident)
16127                 {
16128                         appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
16129                                                           fmtQualifiedDumpable(tbinfo));
16130                         /* index name is not qualified in this syntax */
16131                         appendPQExpBuffer(q, " INDEX %s;\n",
16132                                                           qindxname);
16133                 }
16134
16135                 appendPQExpBuffer(delq, "DROP INDEX %s;\n",
16136                                                   fmtQualifiedDumpable(indxinfo));
16137
16138                 if (indxinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16139                         ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
16140                                                  indxinfo->dobj.name,
16141                                                  tbinfo->dobj.namespace->dobj.name,
16142                                                  indxinfo->tablespace,
16143                                                  tbinfo->rolname, false,
16144                                                  "INDEX", SECTION_POST_DATA,
16145                                                  q->data, delq->data, NULL,
16146                                                  NULL, 0,
16147                                                  NULL, NULL);
16148         }
16149
16150         /* Dump Index Comments */
16151         if (indxinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16152                 dumpComment(fout, "INDEX", qindxname,
16153                                         tbinfo->dobj.namespace->dobj.name,
16154                                         tbinfo->rolname,
16155                                         indxinfo->dobj.catId, 0,
16156                                         is_constraint ? indxinfo->indexconstraint :
16157                                         indxinfo->dobj.dumpId);
16158
16159         destroyPQExpBuffer(q);
16160         destroyPQExpBuffer(delq);
16161         free(qindxname);
16162 }
16163
16164 /*
16165  * dumpIndexAttach
16166  *        write out to fout a partitioned-index attachment clause
16167  */
16168 static void
16169 dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo)
16170 {
16171         if (fout->dopt->dataOnly)
16172                 return;
16173
16174         if (attachinfo->partitionIdx->dobj.dump & DUMP_COMPONENT_DEFINITION)
16175         {
16176                 PQExpBuffer q = createPQExpBuffer();
16177
16178                 appendPQExpBuffer(q, "\nALTER INDEX %s ",
16179                                                   fmtQualifiedDumpable(attachinfo->parentIdx));
16180                 appendPQExpBuffer(q, "ATTACH PARTITION %s;\n",
16181                                                   fmtQualifiedDumpable(attachinfo->partitionIdx));
16182
16183                 ArchiveEntry(fout, attachinfo->dobj.catId, attachinfo->dobj.dumpId,
16184                                          attachinfo->dobj.name,
16185                                          NULL, NULL,
16186                                          "",
16187                                          false, "INDEX ATTACH", SECTION_POST_DATA,
16188                                          q->data, "", NULL,
16189                                          NULL, 0,
16190                                          NULL, NULL);
16191
16192                 destroyPQExpBuffer(q);
16193         }
16194 }
16195
16196 /*
16197  * dumpStatisticsExt
16198  *        write out to fout an extended statistics object
16199  */
16200 static void
16201 dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo)
16202 {
16203         DumpOptions *dopt = fout->dopt;
16204         PQExpBuffer q;
16205         PQExpBuffer delq;
16206         PQExpBuffer query;
16207         char       *qstatsextname;
16208         PGresult   *res;
16209         char       *stxdef;
16210
16211         /* Skip if not to be dumped */
16212         if (!statsextinfo->dobj.dump || dopt->dataOnly)
16213                 return;
16214
16215         q = createPQExpBuffer();
16216         delq = createPQExpBuffer();
16217         query = createPQExpBuffer();
16218
16219         qstatsextname = pg_strdup(fmtId(statsextinfo->dobj.name));
16220
16221         appendPQExpBuffer(query, "SELECT "
16222                                           "pg_catalog.pg_get_statisticsobjdef('%u'::pg_catalog.oid)",
16223                                           statsextinfo->dobj.catId.oid);
16224
16225         res = ExecuteSqlQueryForSingleRow(fout, query->data);
16226
16227         stxdef = PQgetvalue(res, 0, 0);
16228
16229         /* Result of pg_get_statisticsobjdef is complete except for semicolon */
16230         appendPQExpBuffer(q, "%s;\n", stxdef);
16231
16232         appendPQExpBuffer(delq, "DROP STATISTICS %s;\n",
16233                                           fmtQualifiedDumpable(statsextinfo));
16234
16235         if (statsextinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16236                 ArchiveEntry(fout, statsextinfo->dobj.catId,
16237                                          statsextinfo->dobj.dumpId,
16238                                          statsextinfo->dobj.name,
16239                                          statsextinfo->dobj.namespace->dobj.name,
16240                                          NULL,
16241                                          statsextinfo->rolname, false,
16242                                          "STATISTICS", SECTION_POST_DATA,
16243                                          q->data, delq->data, NULL,
16244                                          NULL, 0,
16245                                          NULL, NULL);
16246
16247         /* Dump Statistics Comments */
16248         if (statsextinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16249                 dumpComment(fout, "STATISTICS", qstatsextname,
16250                                         statsextinfo->dobj.namespace->dobj.name,
16251                                         statsextinfo->rolname,
16252                                         statsextinfo->dobj.catId, 0,
16253                                         statsextinfo->dobj.dumpId);
16254
16255         PQclear(res);
16256         destroyPQExpBuffer(q);
16257         destroyPQExpBuffer(delq);
16258         destroyPQExpBuffer(query);
16259         free(qstatsextname);
16260 }
16261
16262 /*
16263  * dumpConstraint
16264  *        write out to fout a user-defined constraint
16265  */
16266 static void
16267 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
16268 {
16269         DumpOptions *dopt = fout->dopt;
16270         TableInfo  *tbinfo = coninfo->contable;
16271         PQExpBuffer q;
16272         PQExpBuffer delq;
16273         char       *tag = NULL;
16274
16275         /* Skip if not to be dumped */
16276         if (!coninfo->dobj.dump || dopt->dataOnly)
16277                 return;
16278
16279         q = createPQExpBuffer();
16280         delq = createPQExpBuffer();
16281
16282         if (coninfo->contype == 'p' ||
16283                 coninfo->contype == 'u' ||
16284                 coninfo->contype == 'x')
16285         {
16286                 /* Index-related constraint */
16287                 IndxInfo   *indxinfo;
16288                 int                     k;
16289
16290                 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
16291
16292                 if (indxinfo == NULL)
16293                         exit_horribly(NULL, "missing index for constraint \"%s\"\n",
16294                                                   coninfo->dobj.name);
16295
16296                 if (dopt->binary_upgrade)
16297                         binary_upgrade_set_pg_class_oids(fout, q,
16298                                                                                          indxinfo->dobj.catId.oid, true);
16299
16300                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
16301                                                   fmtQualifiedDumpable(tbinfo));
16302                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s ",
16303                                                   fmtId(coninfo->dobj.name));
16304
16305                 if (coninfo->condef)
16306                 {
16307                         /* pg_get_constraintdef should have provided everything */
16308                         appendPQExpBuffer(q, "%s;\n", coninfo->condef);
16309                 }
16310                 else
16311                 {
16312                         appendPQExpBuffer(q, "%s (",
16313                                                           coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
16314                         for (k = 0; k < indxinfo->indnkeys; k++)
16315                         {
16316                                 int                     indkey = (int) indxinfo->indkeys[k];
16317                                 const char *attname;
16318
16319                                 if (indkey == InvalidAttrNumber)
16320                                         break;
16321                                 attname = getAttrName(indkey, tbinfo);
16322
16323                                 appendPQExpBuffer(q, "%s%s",
16324                                                                   (k == 0) ? "" : ", ",
16325                                                                   fmtId(attname));
16326                         }
16327
16328                         appendPQExpBufferChar(q, ')');
16329
16330                         if (nonemptyReloptions(indxinfo->indreloptions))
16331                         {
16332                                 appendPQExpBufferStr(q, " WITH (");
16333                                 appendReloptionsArrayAH(q, indxinfo->indreloptions, "", fout);
16334                                 appendPQExpBufferChar(q, ')');
16335                         }
16336
16337                         if (coninfo->condeferrable)
16338                         {
16339                                 appendPQExpBufferStr(q, " DEFERRABLE");
16340                                 if (coninfo->condeferred)
16341                                         appendPQExpBufferStr(q, " INITIALLY DEFERRED");
16342                         }
16343
16344                         appendPQExpBufferStr(q, ";\n");
16345                 }
16346
16347                 /* If the index is clustered, we need to record that. */
16348                 if (indxinfo->indisclustered)
16349                 {
16350                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16351                                                           fmtQualifiedDumpable(tbinfo));
16352                         /* index name is not qualified in this syntax */
16353                         appendPQExpBuffer(q, " ON %s;\n",
16354                                                           fmtId(indxinfo->dobj.name));
16355                 }
16356
16357                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s ",
16358                                                   fmtQualifiedDumpable(tbinfo));
16359                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16360                                                   fmtId(coninfo->dobj.name));
16361
16362                 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16363
16364                 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16365                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16366                                                  tag,
16367                                                  tbinfo->dobj.namespace->dobj.name,
16368                                                  indxinfo->tablespace,
16369                                                  tbinfo->rolname, false,
16370                                                  "CONSTRAINT", SECTION_POST_DATA,
16371                                                  q->data, delq->data, NULL,
16372                                                  NULL, 0,
16373                                                  NULL, NULL);
16374         }
16375         else if (coninfo->contype == 'f')
16376         {
16377                 /*
16378                  * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
16379                  * current table data is not processed
16380                  */
16381                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
16382                                                   fmtQualifiedDumpable(tbinfo));
16383                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
16384                                                   fmtId(coninfo->dobj.name),
16385                                                   coninfo->condef);
16386
16387                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s ",
16388                                                   fmtQualifiedDumpable(tbinfo));
16389                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16390                                                   fmtId(coninfo->dobj.name));
16391
16392                 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16393
16394                 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16395                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16396                                                  tag,
16397                                                  tbinfo->dobj.namespace->dobj.name,
16398                                                  NULL,
16399                                                  tbinfo->rolname, false,
16400                                                  "FK CONSTRAINT", SECTION_POST_DATA,
16401                                                  q->data, delq->data, NULL,
16402                                                  NULL, 0,
16403                                                  NULL, NULL);
16404         }
16405         else if (coninfo->contype == 'c' && tbinfo)
16406         {
16407                 /* CHECK constraint on a table */
16408
16409                 /* Ignore if not to be dumped separately, or if it was inherited */
16410                 if (coninfo->separate && coninfo->conislocal)
16411                 {
16412                         /* not ONLY since we want it to propagate to children */
16413                         appendPQExpBuffer(q, "ALTER TABLE %s\n",
16414                                                           fmtQualifiedDumpable(tbinfo));
16415                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
16416                                                           fmtId(coninfo->dobj.name),
16417                                                           coninfo->condef);
16418
16419                         appendPQExpBuffer(delq, "ALTER TABLE %s ",
16420                                                           fmtQualifiedDumpable(tbinfo));
16421                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16422                                                           fmtId(coninfo->dobj.name));
16423
16424                         tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16425
16426                         if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16427                                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16428                                                          tag,
16429                                                          tbinfo->dobj.namespace->dobj.name,
16430                                                          NULL,
16431                                                          tbinfo->rolname, false,
16432                                                          "CHECK CONSTRAINT", SECTION_POST_DATA,
16433                                                          q->data, delq->data, NULL,
16434                                                          NULL, 0,
16435                                                          NULL, NULL);
16436                 }
16437         }
16438         else if (coninfo->contype == 'c' && tbinfo == NULL)
16439         {
16440                 /* CHECK constraint on a domain */
16441                 TypeInfo   *tyinfo = coninfo->condomain;
16442
16443                 /* Ignore if not to be dumped separately */
16444                 if (coninfo->separate)
16445                 {
16446                         appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
16447                                                           fmtQualifiedDumpable(tyinfo));
16448                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
16449                                                           fmtId(coninfo->dobj.name),
16450                                                           coninfo->condef);
16451
16452                         appendPQExpBuffer(delq, "ALTER DOMAIN %s ",
16453                                                           fmtQualifiedDumpable(tyinfo));
16454                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16455                                                           fmtId(coninfo->dobj.name));
16456
16457                         tag = psprintf("%s %s", tyinfo->dobj.name, coninfo->dobj.name);
16458
16459                         if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16460                                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16461                                                          tag,
16462                                                          tyinfo->dobj.namespace->dobj.name,
16463                                                          NULL,
16464                                                          tyinfo->rolname, false,
16465                                                          "CHECK CONSTRAINT", SECTION_POST_DATA,
16466                                                          q->data, delq->data, NULL,
16467                                                          NULL, 0,
16468                                                          NULL, NULL);
16469                 }
16470         }
16471         else
16472         {
16473                 exit_horribly(NULL, "unrecognized constraint type: %c\n",
16474                                           coninfo->contype);
16475         }
16476
16477         /* Dump Constraint Comments --- only works for table constraints */
16478         if (tbinfo && coninfo->separate &&
16479                 coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16480                 dumpTableConstraintComment(fout, coninfo);
16481
16482         free(tag);
16483         destroyPQExpBuffer(q);
16484         destroyPQExpBuffer(delq);
16485 }
16486
16487 /*
16488  * dumpTableConstraintComment --- dump a constraint's comment if any
16489  *
16490  * This is split out because we need the function in two different places
16491  * depending on whether the constraint is dumped as part of CREATE TABLE
16492  * or as a separate ALTER command.
16493  */
16494 static void
16495 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
16496 {
16497         TableInfo  *tbinfo = coninfo->contable;
16498         PQExpBuffer conprefix = createPQExpBuffer();
16499         char       *qtabname;
16500
16501         qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
16502
16503         appendPQExpBuffer(conprefix, "CONSTRAINT %s ON",
16504                                           fmtId(coninfo->dobj.name));
16505
16506         if (coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16507                 dumpComment(fout, conprefix->data, qtabname,
16508                                         tbinfo->dobj.namespace->dobj.name,
16509                                         tbinfo->rolname,
16510                                         coninfo->dobj.catId, 0,
16511                                         coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
16512
16513         destroyPQExpBuffer(conprefix);
16514         free(qtabname);
16515 }
16516
16517 /*
16518  * findLastBuiltinOid_V71 -
16519  *
16520  * find the last built in oid
16521  *
16522  * For 7.1 through 8.0, we do this by retrieving datlastsysoid from the
16523  * pg_database entry for the current database.
16524  */
16525 static Oid
16526 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
16527 {
16528         PGresult   *res;
16529         Oid                     last_oid;
16530         PQExpBuffer query = createPQExpBuffer();
16531
16532         resetPQExpBuffer(query);
16533         appendPQExpBufferStr(query, "SELECT datlastsysoid from pg_database where datname = ");
16534         appendStringLiteralAH(query, dbname, fout);
16535
16536         res = ExecuteSqlQueryForSingleRow(fout, query->data);
16537         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
16538         PQclear(res);
16539         destroyPQExpBuffer(query);
16540
16541         return last_oid;
16542 }
16543
16544 /*
16545  * dumpSequence
16546  *        write the declaration (not data) of one user-defined sequence
16547  */
16548 static void
16549 dumpSequence(Archive *fout, TableInfo *tbinfo)
16550 {
16551         DumpOptions *dopt = fout->dopt;
16552         PGresult   *res;
16553         char       *startv,
16554                            *incby,
16555                            *maxv,
16556                            *minv,
16557                            *cache,
16558                            *seqtype;
16559         bool            cycled;
16560         bool            is_ascending;
16561         int64           default_minv,
16562                                 default_maxv;
16563         char            bufm[32],
16564                                 bufx[32];
16565         PQExpBuffer query = createPQExpBuffer();
16566         PQExpBuffer delqry = createPQExpBuffer();
16567         char       *qseqname;
16568
16569         qseqname = pg_strdup(fmtId(tbinfo->dobj.name));
16570
16571         if (fout->remoteVersion >= 100000)
16572         {
16573                 appendPQExpBuffer(query,
16574                                                   "SELECT format_type(seqtypid, NULL), "
16575                                                   "seqstart, seqincrement, "
16576                                                   "seqmax, seqmin, "
16577                                                   "seqcache, seqcycle "
16578                                                   "FROM pg_catalog.pg_sequence "
16579                                                   "WHERE seqrelid = '%u'::oid",
16580                                                   tbinfo->dobj.catId.oid);
16581         }
16582         else if (fout->remoteVersion >= 80400)
16583         {
16584                 /*
16585                  * Before PostgreSQL 10, sequence metadata is in the sequence itself.
16586                  *
16587                  * Note: it might seem that 'bigint' potentially needs to be
16588                  * schema-qualified, but actually that's a keyword.
16589                  */
16590                 appendPQExpBuffer(query,
16591                                                   "SELECT 'bigint' AS sequence_type, "
16592                                                   "start_value, increment_by, max_value, min_value, "
16593                                                   "cache_value, is_cycled FROM %s",
16594                                                   fmtQualifiedDumpable(tbinfo));
16595         }
16596         else
16597         {
16598                 appendPQExpBuffer(query,
16599                                                   "SELECT 'bigint' AS sequence_type, "
16600                                                   "0 AS start_value, increment_by, max_value, min_value, "
16601                                                   "cache_value, is_cycled FROM %s",
16602                                                   fmtQualifiedDumpable(tbinfo));
16603         }
16604
16605         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
16606
16607         if (PQntuples(res) != 1)
16608         {
16609                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
16610                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
16611                                                                  PQntuples(res)),
16612                                   tbinfo->dobj.name, PQntuples(res));
16613                 exit_nicely(1);
16614         }
16615
16616         seqtype = PQgetvalue(res, 0, 0);
16617         startv = PQgetvalue(res, 0, 1);
16618         incby = PQgetvalue(res, 0, 2);
16619         maxv = PQgetvalue(res, 0, 3);
16620         minv = PQgetvalue(res, 0, 4);
16621         cache = PQgetvalue(res, 0, 5);
16622         cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
16623
16624         /* Calculate default limits for a sequence of this type */
16625         is_ascending = (incby[0] != '-');
16626         if (strcmp(seqtype, "smallint") == 0)
16627         {
16628                 default_minv = is_ascending ? 1 : PG_INT16_MIN;
16629                 default_maxv = is_ascending ? PG_INT16_MAX : -1;
16630         }
16631         else if (strcmp(seqtype, "integer") == 0)
16632         {
16633                 default_minv = is_ascending ? 1 : PG_INT32_MIN;
16634                 default_maxv = is_ascending ? PG_INT32_MAX : -1;
16635         }
16636         else if (strcmp(seqtype, "bigint") == 0)
16637         {
16638                 default_minv = is_ascending ? 1 : PG_INT64_MIN;
16639                 default_maxv = is_ascending ? PG_INT64_MAX : -1;
16640         }
16641         else
16642         {
16643                 exit_horribly(NULL, "unrecognized sequence type: %s\n", seqtype);
16644                 default_minv = default_maxv = 0;        /* keep compiler quiet */
16645         }
16646
16647         /*
16648          * 64-bit strtol() isn't very portable, so convert the limits to strings
16649          * and compare that way.
16650          */
16651         snprintf(bufm, sizeof(bufm), INT64_FORMAT, default_minv);
16652         snprintf(bufx, sizeof(bufx), INT64_FORMAT, default_maxv);
16653
16654         /* Don't print minv/maxv if they match the respective default limit */
16655         if (strcmp(minv, bufm) == 0)
16656                 minv = NULL;
16657         if (strcmp(maxv, bufx) == 0)
16658                 maxv = NULL;
16659
16660         /*
16661          * Identity sequences are not to be dropped separately.
16662          */
16663         if (!tbinfo->is_identity_sequence)
16664         {
16665                 appendPQExpBuffer(delqry, "DROP SEQUENCE %s;\n",
16666                                                   fmtQualifiedDumpable(tbinfo));
16667         }
16668
16669         resetPQExpBuffer(query);
16670
16671         if (dopt->binary_upgrade)
16672         {
16673                 binary_upgrade_set_pg_class_oids(fout, query,
16674                                                                                  tbinfo->dobj.catId.oid, false);
16675                 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
16676                                                                                                 tbinfo->dobj.catId.oid);
16677         }
16678
16679         if (tbinfo->is_identity_sequence)
16680         {
16681                 TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
16682
16683                 appendPQExpBuffer(query,
16684                                                   "ALTER TABLE %s ",
16685                                                   fmtQualifiedDumpable(owning_tab));
16686                 appendPQExpBuffer(query,
16687                                                   "ALTER COLUMN %s ADD GENERATED ",
16688                                                   fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16689                 if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_ALWAYS)
16690                         appendPQExpBuffer(query, "ALWAYS");
16691                 else if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_BY_DEFAULT)
16692                         appendPQExpBuffer(query, "BY DEFAULT");
16693                 appendPQExpBuffer(query, " AS IDENTITY (\n    SEQUENCE NAME %s\n",
16694                                                   fmtQualifiedDumpable(tbinfo));
16695         }
16696         else
16697         {
16698                 appendPQExpBuffer(query,
16699                                                   "CREATE SEQUENCE %s\n",
16700                                                   fmtQualifiedDumpable(tbinfo));
16701
16702                 if (strcmp(seqtype, "bigint") != 0)
16703                         appendPQExpBuffer(query, "    AS %s\n", seqtype);
16704         }
16705
16706         if (fout->remoteVersion >= 80400)
16707                 appendPQExpBuffer(query, "    START WITH %s\n", startv);
16708
16709         appendPQExpBuffer(query, "    INCREMENT BY %s\n", incby);
16710
16711         if (minv)
16712                 appendPQExpBuffer(query, "    MINVALUE %s\n", minv);
16713         else
16714                 appendPQExpBufferStr(query, "    NO MINVALUE\n");
16715
16716         if (maxv)
16717                 appendPQExpBuffer(query, "    MAXVALUE %s\n", maxv);
16718         else
16719                 appendPQExpBufferStr(query, "    NO MAXVALUE\n");
16720
16721         appendPQExpBuffer(query,
16722                                           "    CACHE %s%s",
16723                                           cache, (cycled ? "\n    CYCLE" : ""));
16724
16725         if (tbinfo->is_identity_sequence)
16726                 appendPQExpBufferStr(query, "\n);\n");
16727         else
16728                 appendPQExpBufferStr(query, ";\n");
16729
16730         /* binary_upgrade:      no need to clear TOAST table oid */
16731
16732         if (dopt->binary_upgrade)
16733                 binary_upgrade_extension_member(query, &tbinfo->dobj,
16734                                                                                 "SEQUENCE", qseqname,
16735                                                                                 tbinfo->dobj.namespace->dobj.name);
16736
16737         if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16738                 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
16739                                          tbinfo->dobj.name,
16740                                          tbinfo->dobj.namespace->dobj.name,
16741                                          NULL,
16742                                          tbinfo->rolname,
16743                                          false, "SEQUENCE", SECTION_PRE_DATA,
16744                                          query->data, delqry->data, NULL,
16745                                          NULL, 0,
16746                                          NULL, NULL);
16747
16748         /*
16749          * If the sequence is owned by a table column, emit the ALTER for it as a
16750          * separate TOC entry immediately following the sequence's own entry. It's
16751          * OK to do this rather than using full sorting logic, because the
16752          * dependency that tells us it's owned will have forced the table to be
16753          * created first.  We can't just include the ALTER in the TOC entry
16754          * because it will fail if we haven't reassigned the sequence owner to
16755          * match the table's owner.
16756          *
16757          * We need not schema-qualify the table reference because both sequence
16758          * and table must be in the same schema.
16759          */
16760         if (OidIsValid(tbinfo->owning_tab) && !tbinfo->is_identity_sequence)
16761         {
16762                 TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
16763
16764                 if (owning_tab == NULL)
16765                         exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
16766                                                   tbinfo->owning_tab, tbinfo->dobj.catId.oid);
16767
16768                 if (owning_tab->dobj.dump & DUMP_COMPONENT_DEFINITION)
16769                 {
16770                         resetPQExpBuffer(query);
16771                         appendPQExpBuffer(query, "ALTER SEQUENCE %s",
16772                                                           fmtQualifiedDumpable(tbinfo));
16773                         appendPQExpBuffer(query, " OWNED BY %s",
16774                                                           fmtQualifiedDumpable(owning_tab));
16775                         appendPQExpBuffer(query, ".%s;\n",
16776                                                           fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16777
16778                         if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16779                                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
16780                                                          tbinfo->dobj.name,
16781                                                          tbinfo->dobj.namespace->dobj.name,
16782                                                          NULL,
16783                                                          tbinfo->rolname,
16784                                                          false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
16785                                                          query->data, "", NULL,
16786                                                          &(tbinfo->dobj.dumpId), 1,
16787                                                          NULL, NULL);
16788                 }
16789         }
16790
16791         /* Dump Sequence Comments and Security Labels */
16792         if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16793                 dumpComment(fout, "SEQUENCE", qseqname,
16794                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16795                                         tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
16796
16797         if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16798                 dumpSecLabel(fout, "SEQUENCE", qseqname,
16799                                          tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16800                                          tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
16801
16802         PQclear(res);
16803
16804         destroyPQExpBuffer(query);
16805         destroyPQExpBuffer(delqry);
16806         free(qseqname);
16807 }
16808
16809 /*
16810  * dumpSequenceData
16811  *        write the data of one user-defined sequence
16812  */
16813 static void
16814 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
16815 {
16816         TableInfo  *tbinfo = tdinfo->tdtable;
16817         PGresult   *res;
16818         char       *last;
16819         bool            called;
16820         PQExpBuffer query = createPQExpBuffer();
16821
16822         appendPQExpBuffer(query,
16823                                           "SELECT last_value, is_called FROM %s",
16824                                           fmtQualifiedDumpable(tbinfo));
16825
16826         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
16827
16828         if (PQntuples(res) != 1)
16829         {
16830                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
16831                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
16832                                                                  PQntuples(res)),
16833                                   tbinfo->dobj.name, PQntuples(res));
16834                 exit_nicely(1);
16835         }
16836
16837         last = PQgetvalue(res, 0, 0);
16838         called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
16839
16840         resetPQExpBuffer(query);
16841         appendPQExpBufferStr(query, "SELECT pg_catalog.setval(");
16842         appendStringLiteralAH(query, fmtQualifiedDumpable(tbinfo), fout);
16843         appendPQExpBuffer(query, ", %s, %s);\n",
16844                                           last, (called ? "true" : "false"));
16845
16846         if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
16847                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
16848                                          tbinfo->dobj.name,
16849                                          tbinfo->dobj.namespace->dobj.name,
16850                                          NULL,
16851                                          tbinfo->rolname,
16852                                          false, "SEQUENCE SET", SECTION_DATA,
16853                                          query->data, "", NULL,
16854                                          &(tbinfo->dobj.dumpId), 1,
16855                                          NULL, NULL);
16856
16857         PQclear(res);
16858
16859         destroyPQExpBuffer(query);
16860 }
16861
16862 /*
16863  * dumpTrigger
16864  *        write the declaration of one user-defined table trigger
16865  */
16866 static void
16867 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
16868 {
16869         DumpOptions *dopt = fout->dopt;
16870         TableInfo  *tbinfo = tginfo->tgtable;
16871         PQExpBuffer query;
16872         PQExpBuffer delqry;
16873         PQExpBuffer trigprefix;
16874         char       *qtabname;
16875         char       *tgargs;
16876         size_t          lentgargs;
16877         const char *p;
16878         int                     findx;
16879         char       *tag;
16880
16881         /*
16882          * we needn't check dobj.dump because TriggerInfo wouldn't have been
16883          * created in the first place for non-dumpable triggers
16884          */
16885         if (dopt->dataOnly)
16886                 return;
16887
16888         query = createPQExpBuffer();
16889         delqry = createPQExpBuffer();
16890         trigprefix = createPQExpBuffer();
16891
16892         qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
16893
16894         appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
16895                                           fmtId(tginfo->dobj.name));
16896         appendPQExpBuffer(delqry, "ON %s;\n",
16897                                           fmtQualifiedDumpable(tbinfo));
16898
16899         if (tginfo->tgdef)
16900         {
16901                 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
16902         }
16903         else
16904         {
16905                 if (tginfo->tgisconstraint)
16906                 {
16907                         appendPQExpBufferStr(query, "CREATE CONSTRAINT TRIGGER ");
16908                         appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
16909                 }
16910                 else
16911                 {
16912                         appendPQExpBufferStr(query, "CREATE TRIGGER ");
16913                         appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
16914                 }
16915                 appendPQExpBufferStr(query, "\n    ");
16916
16917                 /* Trigger type */
16918                 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
16919                         appendPQExpBufferStr(query, "BEFORE");
16920                 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
16921                         appendPQExpBufferStr(query, "AFTER");
16922                 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
16923                         appendPQExpBufferStr(query, "INSTEAD OF");
16924                 else
16925                 {
16926                         write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
16927                         exit_nicely(1);
16928                 }
16929
16930                 findx = 0;
16931                 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
16932                 {
16933                         appendPQExpBufferStr(query, " INSERT");
16934                         findx++;
16935                 }
16936                 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
16937                 {
16938                         if (findx > 0)
16939                                 appendPQExpBufferStr(query, " OR DELETE");
16940                         else
16941                                 appendPQExpBufferStr(query, " DELETE");
16942                         findx++;
16943                 }
16944                 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
16945                 {
16946                         if (findx > 0)
16947                                 appendPQExpBufferStr(query, " OR UPDATE");
16948                         else
16949                                 appendPQExpBufferStr(query, " UPDATE");
16950                         findx++;
16951                 }
16952                 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
16953                 {
16954                         if (findx > 0)
16955                                 appendPQExpBufferStr(query, " OR TRUNCATE");
16956                         else
16957                                 appendPQExpBufferStr(query, " TRUNCATE");
16958                         findx++;
16959                 }
16960                 appendPQExpBuffer(query, " ON %s\n",
16961                                                   fmtQualifiedDumpable(tbinfo));
16962
16963                 if (tginfo->tgisconstraint)
16964                 {
16965                         if (OidIsValid(tginfo->tgconstrrelid))
16966                         {
16967                                 /* regclass output is already quoted */
16968                                 appendPQExpBuffer(query, "    FROM %s\n    ",
16969                                                                   tginfo->tgconstrrelname);
16970                         }
16971                         if (!tginfo->tgdeferrable)
16972                                 appendPQExpBufferStr(query, "NOT ");
16973                         appendPQExpBufferStr(query, "DEFERRABLE INITIALLY ");
16974                         if (tginfo->tginitdeferred)
16975                                 appendPQExpBufferStr(query, "DEFERRED\n");
16976                         else
16977                                 appendPQExpBufferStr(query, "IMMEDIATE\n");
16978                 }
16979
16980                 if (TRIGGER_FOR_ROW(tginfo->tgtype))
16981                         appendPQExpBufferStr(query, "    FOR EACH ROW\n    ");
16982                 else
16983                         appendPQExpBufferStr(query, "    FOR EACH STATEMENT\n    ");
16984
16985                 /* regproc output is already sufficiently quoted */
16986                 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
16987                                                   tginfo->tgfname);
16988
16989                 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
16990                                                                                   &lentgargs);
16991                 p = tgargs;
16992                 for (findx = 0; findx < tginfo->tgnargs; findx++)
16993                 {
16994                         /* find the embedded null that terminates this trigger argument */
16995                         size_t          tlen = strlen(p);
16996
16997                         if (p + tlen >= tgargs + lentgargs)
16998                         {
16999                                 /* hm, not found before end of bytea value... */
17000                                 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
17001                                                   tginfo->tgargs,
17002                                                   tginfo->dobj.name,
17003                                                   tbinfo->dobj.name);
17004                                 exit_nicely(1);
17005                         }
17006
17007                         if (findx > 0)
17008                                 appendPQExpBufferStr(query, ", ");
17009                         appendStringLiteralAH(query, p, fout);
17010                         p += tlen + 1;
17011                 }
17012                 free(tgargs);
17013                 appendPQExpBufferStr(query, ");\n");
17014         }
17015
17016         if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
17017         {
17018                 appendPQExpBuffer(query, "\nALTER TABLE %s ",
17019                                                   fmtQualifiedDumpable(tbinfo));
17020                 switch (tginfo->tgenabled)
17021                 {
17022                         case 'D':
17023                         case 'f':
17024                                 appendPQExpBufferStr(query, "DISABLE");
17025                                 break;
17026                         case 'A':
17027                                 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17028                                 break;
17029                         case 'R':
17030                                 appendPQExpBufferStr(query, "ENABLE REPLICA");
17031                                 break;
17032                         default:
17033                                 appendPQExpBufferStr(query, "ENABLE");
17034                                 break;
17035                 }
17036                 appendPQExpBuffer(query, " TRIGGER %s;\n",
17037                                                   fmtId(tginfo->dobj.name));
17038         }
17039
17040         appendPQExpBuffer(trigprefix, "TRIGGER %s ON",
17041                                           fmtId(tginfo->dobj.name));
17042
17043         tag = psprintf("%s %s", tbinfo->dobj.name, tginfo->dobj.name);
17044
17045         if (tginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17046                 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
17047                                          tag,
17048                                          tbinfo->dobj.namespace->dobj.name,
17049                                          NULL,
17050                                          tbinfo->rolname, false,
17051                                          "TRIGGER", SECTION_POST_DATA,
17052                                          query->data, delqry->data, NULL,
17053                                          NULL, 0,
17054                                          NULL, NULL);
17055
17056         if (tginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17057                 dumpComment(fout, trigprefix->data, qtabname,
17058                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17059                                         tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
17060
17061         free(tag);
17062         destroyPQExpBuffer(query);
17063         destroyPQExpBuffer(delqry);
17064         destroyPQExpBuffer(trigprefix);
17065         free(qtabname);
17066 }
17067
17068 /*
17069  * dumpEventTrigger
17070  *        write the declaration of one user-defined event trigger
17071  */
17072 static void
17073 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
17074 {
17075         DumpOptions *dopt = fout->dopt;
17076         PQExpBuffer query;
17077         PQExpBuffer delqry;
17078         char       *qevtname;
17079
17080         /* Skip if not to be dumped */
17081         if (!evtinfo->dobj.dump || dopt->dataOnly)
17082                 return;
17083
17084         query = createPQExpBuffer();
17085         delqry = createPQExpBuffer();
17086
17087         qevtname = pg_strdup(fmtId(evtinfo->dobj.name));
17088
17089         appendPQExpBufferStr(query, "CREATE EVENT TRIGGER ");
17090         appendPQExpBufferStr(query, qevtname);
17091         appendPQExpBufferStr(query, " ON ");
17092         appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
17093
17094         if (strcmp("", evtinfo->evttags) != 0)
17095         {
17096                 appendPQExpBufferStr(query, "\n         WHEN TAG IN (");
17097                 appendPQExpBufferStr(query, evtinfo->evttags);
17098                 appendPQExpBufferChar(query, ')');
17099         }
17100
17101         appendPQExpBufferStr(query, "\n   EXECUTE PROCEDURE ");
17102         appendPQExpBufferStr(query, evtinfo->evtfname);
17103         appendPQExpBufferStr(query, "();\n");
17104
17105         if (evtinfo->evtenabled != 'O')
17106         {
17107                 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
17108                                                   qevtname);
17109                 switch (evtinfo->evtenabled)
17110                 {
17111                         case 'D':
17112                                 appendPQExpBufferStr(query, "DISABLE");
17113                                 break;
17114                         case 'A':
17115                                 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17116                                 break;
17117                         case 'R':
17118                                 appendPQExpBufferStr(query, "ENABLE REPLICA");
17119                                 break;
17120                         default:
17121                                 appendPQExpBufferStr(query, "ENABLE");
17122                                 break;
17123                 }
17124                 appendPQExpBufferStr(query, ";\n");
17125         }
17126
17127         appendPQExpBuffer(delqry, "DROP EVENT TRIGGER %s;\n",
17128                                           qevtname);
17129
17130         if (evtinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17131                 ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
17132                                          evtinfo->dobj.name, NULL, NULL,
17133                                          evtinfo->evtowner, false,
17134                                          "EVENT TRIGGER", SECTION_POST_DATA,
17135                                          query->data, delqry->data, NULL,
17136                                          NULL, 0,
17137                                          NULL, NULL);
17138
17139         if (evtinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17140                 dumpComment(fout, "EVENT TRIGGER", qevtname,
17141                                         NULL, evtinfo->evtowner,
17142                                         evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
17143
17144         destroyPQExpBuffer(query);
17145         destroyPQExpBuffer(delqry);
17146         free(qevtname);
17147 }
17148
17149 /*
17150  * dumpRule
17151  *              Dump a rule
17152  */
17153 static void
17154 dumpRule(Archive *fout, RuleInfo *rinfo)
17155 {
17156         DumpOptions *dopt = fout->dopt;
17157         TableInfo  *tbinfo = rinfo->ruletable;
17158         bool            is_view;
17159         PQExpBuffer query;
17160         PQExpBuffer cmd;
17161         PQExpBuffer delcmd;
17162         PQExpBuffer ruleprefix;
17163         char       *qtabname;
17164         PGresult   *res;
17165         char       *tag;
17166
17167         /* Skip if not to be dumped */
17168         if (!rinfo->dobj.dump || dopt->dataOnly)
17169                 return;
17170
17171         /*
17172          * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
17173          * we do not want to dump it as a separate object.
17174          */
17175         if (!rinfo->separate)
17176                 return;
17177
17178         /*
17179          * If it's an ON SELECT rule, we want to print it as a view definition,
17180          * instead of a rule.
17181          */
17182         is_view = (rinfo->ev_type == '1' && rinfo->is_instead);
17183
17184         query = createPQExpBuffer();
17185         cmd = createPQExpBuffer();
17186         delcmd = createPQExpBuffer();
17187         ruleprefix = createPQExpBuffer();
17188
17189         qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
17190
17191         if (is_view)
17192         {
17193                 PQExpBuffer result;
17194
17195                 /*
17196                  * We need OR REPLACE here because we'll be replacing a dummy view.
17197                  * Otherwise this should look largely like the regular view dump code.
17198                  */
17199                 appendPQExpBuffer(cmd, "CREATE OR REPLACE VIEW %s",
17200                                                   fmtQualifiedDumpable(tbinfo));
17201                 if (nonemptyReloptions(tbinfo->reloptions))
17202                 {
17203                         appendPQExpBufferStr(cmd, " WITH (");
17204                         appendReloptionsArrayAH(cmd, tbinfo->reloptions, "", fout);
17205                         appendPQExpBufferChar(cmd, ')');
17206                 }
17207                 result = createViewAsClause(fout, tbinfo);
17208                 appendPQExpBuffer(cmd, " AS\n%s", result->data);
17209                 destroyPQExpBuffer(result);
17210                 if (tbinfo->checkoption != NULL)
17211                         appendPQExpBuffer(cmd, "\n  WITH %s CHECK OPTION",
17212                                                           tbinfo->checkoption);
17213                 appendPQExpBufferStr(cmd, ";\n");
17214         }
17215         else
17216         {
17217                 /* In the rule case, just print pg_get_ruledef's result verbatim */
17218                 appendPQExpBuffer(query,
17219                                                   "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid)",
17220                                                   rinfo->dobj.catId.oid);
17221
17222                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17223
17224                 if (PQntuples(res) != 1)
17225                 {
17226                         write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
17227                                           rinfo->dobj.name, tbinfo->dobj.name);
17228                         exit_nicely(1);
17229                 }
17230
17231                 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
17232
17233                 PQclear(res);
17234         }
17235
17236         /*
17237          * Add the command to alter the rules replication firing semantics if it
17238          * differs from the default.
17239          */
17240         if (rinfo->ev_enabled != 'O')
17241         {
17242                 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtQualifiedDumpable(tbinfo));
17243                 switch (rinfo->ev_enabled)
17244                 {
17245                         case 'A':
17246                                 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
17247                                                                   fmtId(rinfo->dobj.name));
17248                                 break;
17249                         case 'R':
17250                                 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
17251                                                                   fmtId(rinfo->dobj.name));
17252                                 break;
17253                         case 'D':
17254                                 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
17255                                                                   fmtId(rinfo->dobj.name));
17256                                 break;
17257                 }
17258         }
17259
17260         if (is_view)
17261         {
17262                 /*
17263                  * We can't DROP a view's ON SELECT rule.  Instead, use CREATE OR
17264                  * REPLACE VIEW to replace the rule with something with minimal
17265                  * dependencies.
17266                  */
17267                 PQExpBuffer result;
17268
17269                 appendPQExpBuffer(delcmd, "CREATE OR REPLACE VIEW %s",
17270                                                   fmtQualifiedDumpable(tbinfo));
17271                 result = createDummyViewAsClause(fout, tbinfo);
17272                 appendPQExpBuffer(delcmd, " AS\n%s;\n", result->data);
17273                 destroyPQExpBuffer(result);
17274         }
17275         else
17276         {
17277                 appendPQExpBuffer(delcmd, "DROP RULE %s ",
17278                                                   fmtId(rinfo->dobj.name));
17279                 appendPQExpBuffer(delcmd, "ON %s;\n",
17280                                                   fmtQualifiedDumpable(tbinfo));
17281         }
17282
17283         appendPQExpBuffer(ruleprefix, "RULE %s ON",
17284                                           fmtId(rinfo->dobj.name));
17285
17286         tag = psprintf("%s %s", tbinfo->dobj.name, rinfo->dobj.name);
17287
17288         if (rinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17289                 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
17290                                          tag,
17291                                          tbinfo->dobj.namespace->dobj.name,
17292                                          NULL,
17293                                          tbinfo->rolname, false,
17294                                          "RULE", SECTION_POST_DATA,
17295                                          cmd->data, delcmd->data, NULL,
17296                                          NULL, 0,
17297                                          NULL, NULL);
17298
17299         /* Dump rule comments */
17300         if (rinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17301                 dumpComment(fout, ruleprefix->data, qtabname,
17302                                         tbinfo->dobj.namespace->dobj.name,
17303                                         tbinfo->rolname,
17304                                         rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
17305
17306         free(tag);
17307         destroyPQExpBuffer(query);
17308         destroyPQExpBuffer(cmd);
17309         destroyPQExpBuffer(delcmd);
17310         destroyPQExpBuffer(ruleprefix);
17311         free(qtabname);
17312 }
17313
17314 /*
17315  * getExtensionMembership --- obtain extension membership data
17316  *
17317  * We need to identify objects that are extension members as soon as they're
17318  * loaded, so that we can correctly determine whether they need to be dumped.
17319  * Generally speaking, extension member objects will get marked as *not* to
17320  * be dumped, as they will be recreated by the single CREATE EXTENSION
17321  * command.  However, in binary upgrade mode we still need to dump the members
17322  * individually.
17323  */
17324 void
17325 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
17326                                            int numExtensions)
17327 {
17328         PQExpBuffer query;
17329         PGresult   *res;
17330         int                     ntups,
17331                                 nextmembers,
17332                                 i;
17333         int                     i_classid,
17334                                 i_objid,
17335                                 i_refobjid;
17336         ExtensionMemberId *extmembers;
17337         ExtensionInfo *ext;
17338
17339         /* Nothing to do if no extensions */
17340         if (numExtensions == 0)
17341                 return;
17342
17343         query = createPQExpBuffer();
17344
17345         /* refclassid constraint is redundant but may speed the search */
17346         appendPQExpBufferStr(query, "SELECT "
17347                                                  "classid, objid, refobjid "
17348                                                  "FROM pg_depend "
17349                                                  "WHERE refclassid = 'pg_extension'::regclass "
17350                                                  "AND deptype = 'e' "
17351                                                  "ORDER BY 3");
17352
17353         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17354
17355         ntups = PQntuples(res);
17356
17357         i_classid = PQfnumber(res, "classid");
17358         i_objid = PQfnumber(res, "objid");
17359         i_refobjid = PQfnumber(res, "refobjid");
17360
17361         extmembers = (ExtensionMemberId *) pg_malloc(ntups * sizeof(ExtensionMemberId));
17362         nextmembers = 0;
17363
17364         /*
17365          * Accumulate data into extmembers[].
17366          *
17367          * Since we ordered the SELECT by referenced ID, we can expect that
17368          * multiple entries for the same extension will appear together; this
17369          * saves on searches.
17370          */
17371         ext = NULL;
17372
17373         for (i = 0; i < ntups; i++)
17374         {
17375                 CatalogId       objId;
17376                 Oid                     extId;
17377
17378                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17379                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17380                 extId = atooid(PQgetvalue(res, i, i_refobjid));
17381
17382                 if (ext == NULL ||
17383                         ext->dobj.catId.oid != extId)
17384                         ext = findExtensionByOid(extId);
17385
17386                 if (ext == NULL)
17387                 {
17388                         /* shouldn't happen */
17389                         fprintf(stderr, "could not find referenced extension %u\n", extId);
17390                         continue;
17391                 }
17392
17393                 extmembers[nextmembers].catId = objId;
17394                 extmembers[nextmembers].ext = ext;
17395                 nextmembers++;
17396         }
17397
17398         PQclear(res);
17399
17400         /* Remember the data for use later */
17401         setExtensionMembership(extmembers, nextmembers);
17402
17403         destroyPQExpBuffer(query);
17404 }
17405
17406 /*
17407  * processExtensionTables --- deal with extension configuration tables
17408  *
17409  * There are two parts to this process:
17410  *
17411  * 1. Identify and create dump records for extension configuration tables.
17412  *
17413  *        Extensions can mark tables as "configuration", which means that the user
17414  *        is able and expected to modify those tables after the extension has been
17415  *        loaded.  For these tables, we dump out only the data- the structure is
17416  *        expected to be handled at CREATE EXTENSION time, including any indexes or
17417  *        foreign keys, which brings us to-
17418  *
17419  * 2. Record FK dependencies between configuration tables.
17420  *
17421  *        Due to the FKs being created at CREATE EXTENSION time and therefore before
17422  *        the data is loaded, we have to work out what the best order for reloading
17423  *        the data is, to avoid FK violations when the tables are restored.  This is
17424  *        not perfect- we can't handle circular dependencies and if any exist they
17425  *        will cause an invalid dump to be produced (though at least all of the data
17426  *        is included for a user to manually restore).  This is currently documented
17427  *        but perhaps we can provide a better solution in the future.
17428  */
17429 void
17430 processExtensionTables(Archive *fout, ExtensionInfo extinfo[],
17431                                            int numExtensions)
17432 {
17433         DumpOptions *dopt = fout->dopt;
17434         PQExpBuffer query;
17435         PGresult   *res;
17436         int                     ntups,
17437                                 i;
17438         int                     i_conrelid,
17439                                 i_confrelid;
17440
17441         /* Nothing to do if no extensions */
17442         if (numExtensions == 0)
17443                 return;
17444
17445         /*
17446          * Identify extension configuration tables and create TableDataInfo
17447          * objects for them, ensuring their data will be dumped even though the
17448          * tables themselves won't be.
17449          *
17450          * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
17451          * user data in a configuration table is treated like schema data. This
17452          * seems appropriate since system data in a config table would get
17453          * reloaded by CREATE EXTENSION.
17454          */
17455         for (i = 0; i < numExtensions; i++)
17456         {
17457                 ExtensionInfo *curext = &(extinfo[i]);
17458                 char       *extconfig = curext->extconfig;
17459                 char       *extcondition = curext->extcondition;
17460                 char      **extconfigarray = NULL;
17461                 char      **extconditionarray = NULL;
17462                 int                     nconfigitems;
17463                 int                     nconditionitems;
17464
17465                 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
17466                         parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
17467                         nconfigitems == nconditionitems)
17468                 {
17469                         int                     j;
17470
17471                         for (j = 0; j < nconfigitems; j++)
17472                         {
17473                                 TableInfo  *configtbl;
17474                                 Oid                     configtbloid = atooid(extconfigarray[j]);
17475                                 bool            dumpobj =
17476                                 curext->dobj.dump & DUMP_COMPONENT_DEFINITION;
17477
17478                                 configtbl = findTableByOid(configtbloid);
17479                                 if (configtbl == NULL)
17480                                         continue;
17481
17482                                 /*
17483                                  * Tables of not-to-be-dumped extensions shouldn't be dumped
17484                                  * unless the table or its schema is explicitly included
17485                                  */
17486                                 if (!(curext->dobj.dump & DUMP_COMPONENT_DEFINITION))
17487                                 {
17488                                         /* check table explicitly requested */
17489                                         if (table_include_oids.head != NULL &&
17490                                                 simple_oid_list_member(&table_include_oids,
17491                                                                                            configtbloid))
17492                                                 dumpobj = true;
17493
17494                                         /* check table's schema explicitly requested */
17495                                         if (configtbl->dobj.namespace->dobj.dump &
17496                                                 DUMP_COMPONENT_DATA)
17497                                                 dumpobj = true;
17498                                 }
17499
17500                                 /* check table excluded by an exclusion switch */
17501                                 if (table_exclude_oids.head != NULL &&
17502                                         simple_oid_list_member(&table_exclude_oids,
17503                                                                                    configtbloid))
17504                                         dumpobj = false;
17505
17506                                 /* check schema excluded by an exclusion switch */
17507                                 if (simple_oid_list_member(&schema_exclude_oids,
17508                                                                                    configtbl->dobj.namespace->dobj.catId.oid))
17509                                         dumpobj = false;
17510
17511                                 if (dumpobj)
17512                                 {
17513                                         /*
17514                                          * Note: config tables are dumped without OIDs regardless
17515                                          * of the --oids setting.  This is because row filtering
17516                                          * conditions aren't compatible with dumping OIDs.
17517                                          */
17518                                         makeTableDataInfo(dopt, configtbl, false);
17519                                         if (configtbl->dataObj != NULL)
17520                                         {
17521                                                 if (strlen(extconditionarray[j]) > 0)
17522                                                         configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
17523                                         }
17524                                 }
17525                         }
17526                 }
17527                 if (extconfigarray)
17528                         free(extconfigarray);
17529                 if (extconditionarray)
17530                         free(extconditionarray);
17531         }
17532
17533         /*
17534          * Now that all the TableInfoData objects have been created for all the
17535          * extensions, check their FK dependencies and register them to try and
17536          * dump the data out in an order that they can be restored in.
17537          *
17538          * Note that this is not a problem for user tables as their FKs are
17539          * recreated after the data has been loaded.
17540          */
17541
17542         query = createPQExpBuffer();
17543
17544         printfPQExpBuffer(query,
17545                                           "SELECT conrelid, confrelid "
17546                                           "FROM pg_constraint "
17547                                           "JOIN pg_depend ON (objid = confrelid) "
17548                                           "WHERE contype = 'f' "
17549                                           "AND refclassid = 'pg_extension'::regclass "
17550                                           "AND classid = 'pg_class'::regclass;");
17551
17552         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17553         ntups = PQntuples(res);
17554
17555         i_conrelid = PQfnumber(res, "conrelid");
17556         i_confrelid = PQfnumber(res, "confrelid");
17557
17558         /* Now get the dependencies and register them */
17559         for (i = 0; i < ntups; i++)
17560         {
17561                 Oid                     conrelid,
17562                                         confrelid;
17563                 TableInfo  *reftable,
17564                                    *contable;
17565
17566                 conrelid = atooid(PQgetvalue(res, i, i_conrelid));
17567                 confrelid = atooid(PQgetvalue(res, i, i_confrelid));
17568                 contable = findTableByOid(conrelid);
17569                 reftable = findTableByOid(confrelid);
17570
17571                 if (reftable == NULL ||
17572                         reftable->dataObj == NULL ||
17573                         contable == NULL ||
17574                         contable->dataObj == NULL)
17575                         continue;
17576
17577                 /*
17578                  * Make referencing TABLE_DATA object depend on the referenced table's
17579                  * TABLE_DATA object.
17580                  */
17581                 addObjectDependency(&contable->dataObj->dobj,
17582                                                         reftable->dataObj->dobj.dumpId);
17583         }
17584         PQclear(res);
17585         destroyPQExpBuffer(query);
17586 }
17587
17588 /*
17589  * getDependencies --- obtain available dependency data
17590  */
17591 static void
17592 getDependencies(Archive *fout)
17593 {
17594         PQExpBuffer query;
17595         PGresult   *res;
17596         int                     ntups,
17597                                 i;
17598         int                     i_classid,
17599                                 i_objid,
17600                                 i_refclassid,
17601                                 i_refobjid,
17602                                 i_deptype;
17603         DumpableObject *dobj,
17604                            *refdobj;
17605
17606         if (g_verbose)
17607                 write_msg(NULL, "reading dependency data\n");
17608
17609         query = createPQExpBuffer();
17610
17611         /*
17612          * PIN dependencies aren't interesting, and EXTENSION dependencies were
17613          * already processed by getExtensionMembership.
17614          */
17615         appendPQExpBufferStr(query, "SELECT "
17616                                                  "classid, objid, refclassid, refobjid, deptype "
17617                                                  "FROM pg_depend "
17618                                                  "WHERE deptype != 'p' AND deptype != 'e' "
17619                                                  "ORDER BY 1,2");
17620
17621         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17622
17623         ntups = PQntuples(res);
17624
17625         i_classid = PQfnumber(res, "classid");
17626         i_objid = PQfnumber(res, "objid");
17627         i_refclassid = PQfnumber(res, "refclassid");
17628         i_refobjid = PQfnumber(res, "refobjid");
17629         i_deptype = PQfnumber(res, "deptype");
17630
17631         /*
17632          * Since we ordered the SELECT by referencing ID, we can expect that
17633          * multiple entries for the same object will appear together; this saves
17634          * on searches.
17635          */
17636         dobj = NULL;
17637
17638         for (i = 0; i < ntups; i++)
17639         {
17640                 CatalogId       objId;
17641                 CatalogId       refobjId;
17642                 char            deptype;
17643
17644                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17645                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17646                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
17647                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
17648                 deptype = *(PQgetvalue(res, i, i_deptype));
17649
17650                 if (dobj == NULL ||
17651                         dobj->catId.tableoid != objId.tableoid ||
17652                         dobj->catId.oid != objId.oid)
17653                         dobj = findObjectByCatalogId(objId);
17654
17655                 /*
17656                  * Failure to find objects mentioned in pg_depend is not unexpected,
17657                  * since for example we don't collect info about TOAST tables.
17658                  */
17659                 if (dobj == NULL)
17660                 {
17661 #ifdef NOT_USED
17662                         fprintf(stderr, "no referencing object %u %u\n",
17663                                         objId.tableoid, objId.oid);
17664 #endif
17665                         continue;
17666                 }
17667
17668                 refdobj = findObjectByCatalogId(refobjId);
17669
17670                 if (refdobj == NULL)
17671                 {
17672 #ifdef NOT_USED
17673                         fprintf(stderr, "no referenced object %u %u\n",
17674                                         refobjId.tableoid, refobjId.oid);
17675 #endif
17676                         continue;
17677                 }
17678
17679                 /*
17680                  * Ordinarily, table rowtypes have implicit dependencies on their
17681                  * tables.  However, for a composite type the implicit dependency goes
17682                  * the other way in pg_depend; which is the right thing for DROP but
17683                  * it doesn't produce the dependency ordering we need. So in that one
17684                  * case, we reverse the direction of the dependency.
17685                  */
17686                 if (deptype == 'i' &&
17687                         dobj->objType == DO_TABLE &&
17688                         refdobj->objType == DO_TYPE)
17689                         addObjectDependency(refdobj, dobj->dumpId);
17690                 else
17691                         /* normal case */
17692                         addObjectDependency(dobj, refdobj->dumpId);
17693         }
17694
17695         PQclear(res);
17696
17697         destroyPQExpBuffer(query);
17698 }
17699
17700
17701 /*
17702  * createBoundaryObjects - create dummy DumpableObjects to represent
17703  * dump section boundaries.
17704  */
17705 static DumpableObject *
17706 createBoundaryObjects(void)
17707 {
17708         DumpableObject *dobjs;
17709
17710         dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
17711
17712         dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
17713         dobjs[0].catId = nilCatalogId;
17714         AssignDumpId(dobjs + 0);
17715         dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
17716
17717         dobjs[1].objType = DO_POST_DATA_BOUNDARY;
17718         dobjs[1].catId = nilCatalogId;
17719         AssignDumpId(dobjs + 1);
17720         dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
17721
17722         return dobjs;
17723 }
17724
17725 /*
17726  * addBoundaryDependencies - add dependencies as needed to enforce the dump
17727  * section boundaries.
17728  */
17729 static void
17730 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
17731                                                 DumpableObject *boundaryObjs)
17732 {
17733         DumpableObject *preDataBound = boundaryObjs + 0;
17734         DumpableObject *postDataBound = boundaryObjs + 1;
17735         int                     i;
17736
17737         for (i = 0; i < numObjs; i++)
17738         {
17739                 DumpableObject *dobj = dobjs[i];
17740
17741                 /*
17742                  * The classification of object types here must match the SECTION_xxx
17743                  * values assigned during subsequent ArchiveEntry calls!
17744                  */
17745                 switch (dobj->objType)
17746                 {
17747                         case DO_NAMESPACE:
17748                         case DO_EXTENSION:
17749                         case DO_TYPE:
17750                         case DO_SHELL_TYPE:
17751                         case DO_FUNC:
17752                         case DO_AGG:
17753                         case DO_OPERATOR:
17754                         case DO_ACCESS_METHOD:
17755                         case DO_OPCLASS:
17756                         case DO_OPFAMILY:
17757                         case DO_COLLATION:
17758                         case DO_CONVERSION:
17759                         case DO_TABLE:
17760                         case DO_ATTRDEF:
17761                         case DO_PROCLANG:
17762                         case DO_CAST:
17763                         case DO_DUMMY_TYPE:
17764                         case DO_TSPARSER:
17765                         case DO_TSDICT:
17766                         case DO_TSTEMPLATE:
17767                         case DO_TSCONFIG:
17768                         case DO_FDW:
17769                         case DO_FOREIGN_SERVER:
17770                         case DO_TRANSFORM:
17771                         case DO_BLOB:
17772                                 /* Pre-data objects: must come before the pre-data boundary */
17773                                 addObjectDependency(preDataBound, dobj->dumpId);
17774                                 break;
17775                         case DO_TABLE_DATA:
17776                         case DO_SEQUENCE_SET:
17777                         case DO_BLOB_DATA:
17778                                 /* Data objects: must come between the boundaries */
17779                                 addObjectDependency(dobj, preDataBound->dumpId);
17780                                 addObjectDependency(postDataBound, dobj->dumpId);
17781                                 break;
17782                         case DO_INDEX:
17783                         case DO_INDEX_ATTACH:
17784                         case DO_STATSEXT:
17785                         case DO_REFRESH_MATVIEW:
17786                         case DO_TRIGGER:
17787                         case DO_EVENT_TRIGGER:
17788                         case DO_DEFAULT_ACL:
17789                         case DO_POLICY:
17790                         case DO_PUBLICATION:
17791                         case DO_PUBLICATION_REL:
17792                         case DO_SUBSCRIPTION:
17793                                 /* Post-data objects: must come after the post-data boundary */
17794                                 addObjectDependency(dobj, postDataBound->dumpId);
17795                                 break;
17796                         case DO_RULE:
17797                                 /* Rules are post-data, but only if dumped separately */
17798                                 if (((RuleInfo *) dobj)->separate)
17799                                         addObjectDependency(dobj, postDataBound->dumpId);
17800                                 break;
17801                         case DO_CONSTRAINT:
17802                         case DO_FK_CONSTRAINT:
17803                                 /* Constraints are post-data, but only if dumped separately */
17804                                 if (((ConstraintInfo *) dobj)->separate)
17805                                         addObjectDependency(dobj, postDataBound->dumpId);
17806                                 break;
17807                         case DO_PRE_DATA_BOUNDARY:
17808                                 /* nothing to do */
17809                                 break;
17810                         case DO_POST_DATA_BOUNDARY:
17811                                 /* must come after the pre-data boundary */
17812                                 addObjectDependency(dobj, preDataBound->dumpId);
17813                                 break;
17814                 }
17815         }
17816 }
17817
17818
17819 /*
17820  * BuildArchiveDependencies - create dependency data for archive TOC entries
17821  *
17822  * The raw dependency data obtained by getDependencies() is not terribly
17823  * useful in an archive dump, because in many cases there are dependency
17824  * chains linking through objects that don't appear explicitly in the dump.
17825  * For example, a view will depend on its _RETURN rule while the _RETURN rule
17826  * will depend on other objects --- but the rule will not appear as a separate
17827  * object in the dump.  We need to adjust the view's dependencies to include
17828  * whatever the rule depends on that is included in the dump.
17829  *
17830  * Just to make things more complicated, there are also "special" dependencies
17831  * such as the dependency of a TABLE DATA item on its TABLE, which we must
17832  * not rearrange because pg_restore knows that TABLE DATA only depends on
17833  * its table.  In these cases we must leave the dependencies strictly as-is
17834  * even if they refer to not-to-be-dumped objects.
17835  *
17836  * To handle this, the convention is that "special" dependencies are created
17837  * during ArchiveEntry calls, and an archive TOC item that has any such
17838  * entries will not be touched here.  Otherwise, we recursively search the
17839  * DumpableObject data structures to build the correct dependencies for each
17840  * archive TOC item.
17841  */
17842 static void
17843 BuildArchiveDependencies(Archive *fout)
17844 {
17845         ArchiveHandle *AH = (ArchiveHandle *) fout;
17846         TocEntry   *te;
17847
17848         /* Scan all TOC entries in the archive */
17849         for (te = AH->toc->next; te != AH->toc; te = te->next)
17850         {
17851                 DumpableObject *dobj;
17852                 DumpId     *dependencies;
17853                 int                     nDeps;
17854                 int                     allocDeps;
17855
17856                 /* No need to process entries that will not be dumped */
17857                 if (te->reqs == 0)
17858                         continue;
17859                 /* Ignore entries that already have "special" dependencies */
17860                 if (te->nDeps > 0)
17861                         continue;
17862                 /* Otherwise, look up the item's original DumpableObject, if any */
17863                 dobj = findObjectByDumpId(te->dumpId);
17864                 if (dobj == NULL)
17865                         continue;
17866                 /* No work if it has no dependencies */
17867                 if (dobj->nDeps <= 0)
17868                         continue;
17869                 /* Set up work array */
17870                 allocDeps = 64;
17871                 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
17872                 nDeps = 0;
17873                 /* Recursively find all dumpable dependencies */
17874                 findDumpableDependencies(AH, dobj,
17875                                                                  &dependencies, &nDeps, &allocDeps);
17876                 /* And save 'em ... */
17877                 if (nDeps > 0)
17878                 {
17879                         dependencies = (DumpId *) pg_realloc(dependencies,
17880                                                                                                  nDeps * sizeof(DumpId));
17881                         te->dependencies = dependencies;
17882                         te->nDeps = nDeps;
17883                 }
17884                 else
17885                         free(dependencies);
17886         }
17887 }
17888
17889 /* Recursive search subroutine for BuildArchiveDependencies */
17890 static void
17891 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
17892                                                  DumpId **dependencies, int *nDeps, int *allocDeps)
17893 {
17894         int                     i;
17895
17896         /*
17897          * Ignore section boundary objects: if we search through them, we'll
17898          * report lots of bogus dependencies.
17899          */
17900         if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
17901                 dobj->objType == DO_POST_DATA_BOUNDARY)
17902                 return;
17903
17904         for (i = 0; i < dobj->nDeps; i++)
17905         {
17906                 DumpId          depid = dobj->dependencies[i];
17907
17908                 if (TocIDRequired(AH, depid) != 0)
17909                 {
17910                         /* Object will be dumped, so just reference it as a dependency */
17911                         if (*nDeps >= *allocDeps)
17912                         {
17913                                 *allocDeps *= 2;
17914                                 *dependencies = (DumpId *) pg_realloc(*dependencies,
17915                                                                                                           *allocDeps * sizeof(DumpId));
17916                         }
17917                         (*dependencies)[*nDeps] = depid;
17918                         (*nDeps)++;
17919                 }
17920                 else
17921                 {
17922                         /*
17923                          * Object will not be dumped, so recursively consider its deps. We
17924                          * rely on the assumption that sortDumpableObjects already broke
17925                          * any dependency loops, else we might recurse infinitely.
17926                          */
17927                         DumpableObject *otherdobj = findObjectByDumpId(depid);
17928
17929                         if (otherdobj)
17930                                 findDumpableDependencies(AH, otherdobj,
17931                                                                                  dependencies, nDeps, allocDeps);
17932                 }
17933         }
17934 }
17935
17936
17937 /*
17938  * getFormattedTypeName - retrieve a nicely-formatted type name for the
17939  * given type OID.
17940  *
17941  * This does not guarantee to schema-qualify the output, so it should not
17942  * be used to create the target object name for CREATE or ALTER commands.
17943  *
17944  * TODO: there might be some value in caching the results.
17945  */
17946 static char *
17947 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
17948 {
17949         char       *result;
17950         PQExpBuffer query;
17951         PGresult   *res;
17952
17953         if (oid == 0)
17954         {
17955                 if ((opts & zeroAsOpaque) != 0)
17956                         return pg_strdup(g_opaque_type);
17957                 else if ((opts & zeroAsAny) != 0)
17958                         return pg_strdup("'any'");
17959                 else if ((opts & zeroAsStar) != 0)
17960                         return pg_strdup("*");
17961                 else if ((opts & zeroAsNone) != 0)
17962                         return pg_strdup("NONE");
17963         }
17964
17965         query = createPQExpBuffer();
17966         appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
17967                                           oid);
17968
17969         res = ExecuteSqlQueryForSingleRow(fout, query->data);
17970
17971         /* result of format_type is already quoted */
17972         result = pg_strdup(PQgetvalue(res, 0, 0));
17973
17974         PQclear(res);
17975         destroyPQExpBuffer(query);
17976
17977         return result;
17978 }
17979
17980 /*
17981  * Return a column list clause for the given relation.
17982  *
17983  * Special case: if there are no undropped columns in the relation, return
17984  * "", not an invalid "()" column list.
17985  */
17986 static const char *
17987 fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer)
17988 {
17989         int                     numatts = ti->numatts;
17990         char      **attnames = ti->attnames;
17991         bool       *attisdropped = ti->attisdropped;
17992         bool            needComma;
17993         int                     i;
17994
17995         appendPQExpBufferChar(buffer, '(');
17996         needComma = false;
17997         for (i = 0; i < numatts; i++)
17998         {
17999                 if (attisdropped[i])
18000                         continue;
18001                 if (needComma)
18002                         appendPQExpBufferStr(buffer, ", ");
18003                 appendPQExpBufferStr(buffer, fmtId(attnames[i]));
18004                 needComma = true;
18005         }
18006
18007         if (!needComma)
18008                 return "";                              /* no undropped columns */
18009
18010         appendPQExpBufferChar(buffer, ')');
18011         return buffer->data;
18012 }
18013
18014 /*
18015  * Check if a reloptions array is nonempty.
18016  */
18017 static bool
18018 nonemptyReloptions(const char *reloptions)
18019 {
18020         /* Don't want to print it if it's just "{}" */
18021         return (reloptions != NULL && strlen(reloptions) > 2);
18022 }
18023
18024 /*
18025  * Format a reloptions array and append it to the given buffer.
18026  *
18027  * "prefix" is prepended to the option names; typically it's "" or "toast.".
18028  */
18029 static void
18030 appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
18031                                                 const char *prefix, Archive *fout)
18032 {
18033         bool            res;
18034
18035         res = appendReloptionsArray(buffer, reloptions, prefix, fout->encoding,
18036                                                                 fout->std_strings);
18037         if (!res)
18038                 write_msg(NULL, "WARNING: could not parse reloptions array\n");
18039 }