]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_dump.c
Change PROCEDURE to FUNCTION in CREATE OPERATOR syntax
[postgresql] / src / bin / pg_dump / pg_dump.c
1 /*-------------------------------------------------------------------------
2  *
3  * pg_dump.c
4  *        pg_dump is a utility for dumping out a postgres database
5  *        into a script file.
6  *
7  * Portions Copyright (c) 1996-2018, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  *      pg_dump will read the system catalogs in a database and dump out a
11  *      script that reproduces the schema in terms of SQL that is understood
12  *      by PostgreSQL
13  *
14  *      Note that pg_dump runs in a transaction-snapshot mode transaction,
15  *      so it sees a consistent snapshot of the database including system
16  *      catalogs. However, it relies in part on various specialized backend
17  *      functions like pg_get_indexdef(), and those things tend to look at
18  *      the currently committed state.  So it is possible to get 'cache
19  *      lookup failed' error if someone performs DDL changes while a dump is
20  *      happening. The window for this sort of thing is from the acquisition
21  *      of the transaction snapshot to getSchemaData() (when pg_dump acquires
22  *      AccessShareLock on every table it intends to dump). It isn't very large,
23  *      but it can happen.
24  *
25  *      http://archives.postgresql.org/pgsql-bugs/2010-02/msg00187.php
26  *
27  * IDENTIFICATION
28  *        src/bin/pg_dump/pg_dump.c
29  *
30  *-------------------------------------------------------------------------
31  */
32 #include "postgres_fe.h"
33
34 #include <unistd.h>
35 #include <ctype.h>
36 #ifdef HAVE_TERMIOS_H
37 #include <termios.h>
38 #endif
39
40 #include "getopt_long.h"
41
42 #include "access/attnum.h"
43 #include "access/sysattr.h"
44 #include "access/transam.h"
45 #include "catalog/pg_aggregate_d.h"
46 #include "catalog/pg_am_d.h"
47 #include "catalog/pg_attribute_d.h"
48 #include "catalog/pg_cast_d.h"
49 #include "catalog/pg_class_d.h"
50 #include "catalog/pg_default_acl_d.h"
51 #include "catalog/pg_largeobject_d.h"
52 #include "catalog/pg_largeobject_metadata_d.h"
53 #include "catalog/pg_proc_d.h"
54 #include "catalog/pg_trigger_d.h"
55 #include "catalog/pg_type_d.h"
56 #include "libpq/libpq-fs.h"
57
58 #include "dumputils.h"
59 #include "parallel.h"
60 #include "pg_backup_db.h"
61 #include "pg_backup_utils.h"
62 #include "pg_dump.h"
63 #include "fe_utils/connect.h"
64 #include "fe_utils/string_utils.h"
65
66
67 typedef struct
68 {
69         const char *descr;                      /* comment for an object */
70         Oid                     classoid;               /* object class (catalog OID) */
71         Oid                     objoid;                 /* object OID */
72         int                     objsubid;               /* subobject (table column #) */
73 } CommentItem;
74
75 typedef struct
76 {
77         const char *provider;           /* label provider of this security label */
78         const char *label;                      /* security label for an object */
79         Oid                     classoid;               /* object class (catalog OID) */
80         Oid                     objoid;                 /* object OID */
81         int                     objsubid;               /* subobject (table column #) */
82 } SecLabelItem;
83
84 typedef enum OidOptions
85 {
86         zeroAsOpaque = 1,
87         zeroAsAny = 2,
88         zeroAsStar = 4,
89         zeroAsNone = 8
90 } OidOptions;
91
92 /* global decls */
93 bool            g_verbose;                      /* User wants verbose narration of our
94                                                                  * activities. */
95 static bool dosync = true;              /* Issue fsync() to make dump durable on disk. */
96
97 /* subquery used to convert user ID (eg, datdba) to user name */
98 static const char *username_subquery;
99
100 /*
101  * For 8.0 and earlier servers, pulled from pg_database, for 8.1+ we use
102  * FirstNormalObjectId - 1.
103  */
104 static Oid      g_last_builtin_oid; /* value of the last builtin oid */
105
106 /* The specified names/patterns should to match at least one entity */
107 static int      strict_names = 0;
108
109 /*
110  * Object inclusion/exclusion lists
111  *
112  * The string lists record the patterns given by command-line switches,
113  * which we then convert to lists of OIDs of matching objects.
114  */
115 static SimpleStringList schema_include_patterns = {NULL, NULL};
116 static SimpleOidList schema_include_oids = {NULL, NULL};
117 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
118 static SimpleOidList schema_exclude_oids = {NULL, NULL};
119
120 static SimpleStringList table_include_patterns = {NULL, NULL};
121 static SimpleOidList table_include_oids = {NULL, NULL};
122 static SimpleStringList table_exclude_patterns = {NULL, NULL};
123 static SimpleOidList table_exclude_oids = {NULL, NULL};
124 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
125 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
126
127
128 char            g_opaque_type[10];      /* name for the opaque type */
129
130 /* placeholders for the delimiters for comments */
131 char            g_comment_start[10];
132 char            g_comment_end[10];
133
134 static const CatalogId nilCatalogId = {0, 0};
135
136 /*
137  * Macro for producing quoted, schema-qualified name of a dumpable object.
138  */
139 #define fmtQualifiedDumpable(obj) \
140         fmtQualifiedId((obj)->dobj.namespace->dobj.name, \
141                                    (obj)->dobj.name)
142
143 static void help(const char *progname);
144 static void setup_connection(Archive *AH,
145                                  const char *dumpencoding, const char *dumpsnapshot,
146                                  char *use_role);
147 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
148 static void expand_schema_name_patterns(Archive *fout,
149                                                         SimpleStringList *patterns,
150                                                         SimpleOidList *oids,
151                                                         bool strict_names);
152 static void expand_table_name_patterns(Archive *fout,
153                                                    SimpleStringList *patterns,
154                                                    SimpleOidList *oids,
155                                                    bool strict_names);
156 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid);
157 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
158 static void refreshMatViewData(Archive *fout, TableDataInfo *tdinfo);
159 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
160 static void dumpComment(Archive *fout, const char *type, const char *name,
161                         const char *namespace, const char *owner,
162                         CatalogId catalogId, int subid, DumpId dumpId);
163 static int findComments(Archive *fout, Oid classoid, Oid objoid,
164                          CommentItem **items);
165 static int      collectComments(Archive *fout, CommentItem **items);
166 static void dumpSecLabel(Archive *fout, const char *type, const char *name,
167                          const char *namespace, const char *owner,
168                          CatalogId catalogId, int subid, DumpId dumpId);
169 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
170                           SecLabelItem **items);
171 static int      collectSecLabels(Archive *fout, SecLabelItem **items);
172 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
173 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
174 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
175 static void dumpType(Archive *fout, TypeInfo *tyinfo);
176 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
177 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
178 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
179 static void dumpUndefinedType(Archive *fout, TypeInfo *tyinfo);
180 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
181 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
182 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
183 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
184 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
185 static void dumpFunc(Archive *fout, FuncInfo *finfo);
186 static void dumpCast(Archive *fout, CastInfo *cast);
187 static void dumpTransform(Archive *fout, TransformInfo *transform);
188 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
189 static void dumpAccessMethod(Archive *fout, AccessMethodInfo *oprinfo);
190 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
191 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
192 static void dumpCollation(Archive *fout, CollInfo *collinfo);
193 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
194 static void dumpRule(Archive *fout, RuleInfo *rinfo);
195 static void dumpAgg(Archive *fout, AggInfo *agginfo);
196 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
197 static void dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo);
198 static void dumpTable(Archive *fout, TableInfo *tbinfo);
199 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
200 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
201 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
202 static void dumpSequenceData(Archive *fout, TableDataInfo *tdinfo);
203 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
204 static void dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo);
205 static void dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo);
206 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
207 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
208 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
209 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
210 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
211 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
212 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
213 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
214 static void dumpUserMappings(Archive *fout,
215                                  const char *servername, const char *namespace,
216                                  const char *owner, CatalogId catalogId, DumpId dumpId);
217 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
218
219 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
220                 const char *type, const char *name, const char *subname,
221                 const char *nspname, const char *owner,
222                 const char *acls, const char *racls,
223                 const char *initacls, const char *initracls);
224
225 static void getDependencies(Archive *fout);
226 static void BuildArchiveDependencies(Archive *fout);
227 static void findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
228                                                  DumpId **dependencies, int *nDeps, int *allocDeps);
229
230 static DumpableObject *createBoundaryObjects(void);
231 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
232                                                 DumpableObject *boundaryObjs);
233
234 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
235 static void getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, bool oids, char relkind);
236 static void makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo, bool oids);
237 static void buildMatViewRefreshDependencies(Archive *fout);
238 static void getTableDataFKConstraints(void);
239 static char *format_function_arguments(FuncInfo *finfo, char *funcargs,
240                                                   bool is_agg);
241 static char *format_function_arguments_old(Archive *fout,
242                                                           FuncInfo *finfo, int nallargs,
243                                                           char **allargtypes,
244                                                           char **argmodes,
245                                                           char **argnames);
246 static char *format_function_signature(Archive *fout,
247                                                   FuncInfo *finfo, bool honor_quotes);
248 static char *convertRegProcReference(Archive *fout,
249                                                 const char *proc);
250 static char *getFormattedOperatorName(Archive *fout, const char *oproid);
251 static char *convertTSFunction(Archive *fout, Oid funcOid);
252 static Oid      findLastBuiltinOid_V71(Archive *fout);
253 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
254 static void getBlobs(Archive *fout);
255 static void dumpBlob(Archive *fout, BlobInfo *binfo);
256 static int      dumpBlobs(Archive *fout, void *arg);
257 static void dumpPolicy(Archive *fout, PolicyInfo *polinfo);
258 static void dumpPublication(Archive *fout, PublicationInfo *pubinfo);
259 static void dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo);
260 static void dumpSubscription(Archive *fout, SubscriptionInfo *subinfo);
261 static void dumpDatabase(Archive *AH);
262 static void dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
263                                    const char *dbname, Oid dboid);
264 static void dumpEncoding(Archive *AH);
265 static void dumpStdStrings(Archive *AH);
266 static void dumpSearchPath(Archive *AH);
267 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
268                                                                                  PQExpBuffer upgrade_buffer,
269                                                                                  Oid pg_type_oid,
270                                                                                  bool force_array_type);
271 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
272                                                                                 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
273 static void binary_upgrade_set_pg_class_oids(Archive *fout,
274                                                                  PQExpBuffer upgrade_buffer,
275                                                                  Oid pg_class_oid, bool is_index);
276 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
277                                                                 DumpableObject *dobj,
278                                                                 const char *objtype,
279                                                                 const char *objname,
280                                                                 const char *objnamespace);
281 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
282 static const char *fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer);
283 static bool nonemptyReloptions(const char *reloptions);
284 static void appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
285                                                 const char *prefix, Archive *fout);
286 static char *get_synchronized_snapshot(Archive *fout);
287 static void setupDumpWorker(Archive *AHX);
288 static TableInfo *getRootTableInfo(TableInfo *tbinfo);
289
290
291 int
292 main(int argc, char **argv)
293 {
294         int                     c;
295         const char *filename = NULL;
296         const char *format = "p";
297         TableInfo  *tblinfo;
298         int                     numTables;
299         DumpableObject **dobjs;
300         int                     numObjs;
301         DumpableObject *boundaryObjs;
302         int                     i;
303         int                     optindex;
304         RestoreOptions *ropt;
305         Archive    *fout;                       /* the script file */
306         const char *dumpencoding = NULL;
307         const char *dumpsnapshot = NULL;
308         char       *use_role = NULL;
309         int                     numWorkers = 1;
310         trivalue        prompt_password = TRI_DEFAULT;
311         int                     compressLevel = -1;
312         int                     plainText = 0;
313         ArchiveFormat archiveFormat = archUnknown;
314         ArchiveMode archiveMode;
315
316         static DumpOptions dopt;
317
318         static struct option long_options[] = {
319                 {"data-only", no_argument, NULL, 'a'},
320                 {"blobs", no_argument, NULL, 'b'},
321                 {"no-blobs", no_argument, NULL, 'B'},
322                 {"clean", no_argument, NULL, 'c'},
323                 {"create", no_argument, NULL, 'C'},
324                 {"dbname", required_argument, NULL, 'd'},
325                 {"file", required_argument, NULL, 'f'},
326                 {"format", required_argument, NULL, 'F'},
327                 {"host", required_argument, NULL, 'h'},
328                 {"jobs", 1, NULL, 'j'},
329                 {"no-reconnect", no_argument, NULL, 'R'},
330                 {"oids", no_argument, NULL, 'o'},
331                 {"no-owner", no_argument, NULL, 'O'},
332                 {"port", required_argument, NULL, 'p'},
333                 {"schema", required_argument, NULL, 'n'},
334                 {"exclude-schema", required_argument, NULL, 'N'},
335                 {"schema-only", no_argument, NULL, 's'},
336                 {"superuser", required_argument, NULL, 'S'},
337                 {"table", required_argument, NULL, 't'},
338                 {"exclude-table", required_argument, NULL, 'T'},
339                 {"no-password", no_argument, NULL, 'w'},
340                 {"password", no_argument, NULL, 'W'},
341                 {"username", required_argument, NULL, 'U'},
342                 {"verbose", no_argument, NULL, 'v'},
343                 {"no-privileges", no_argument, NULL, 'x'},
344                 {"no-acl", no_argument, NULL, 'x'},
345                 {"compress", required_argument, NULL, 'Z'},
346                 {"encoding", required_argument, NULL, 'E'},
347                 {"help", no_argument, NULL, '?'},
348                 {"version", no_argument, NULL, 'V'},
349
350                 /*
351                  * the following options don't have an equivalent short option letter
352                  */
353                 {"attribute-inserts", no_argument, &dopt.column_inserts, 1},
354                 {"binary-upgrade", no_argument, &dopt.binary_upgrade, 1},
355                 {"column-inserts", no_argument, &dopt.column_inserts, 1},
356                 {"disable-dollar-quoting", no_argument, &dopt.disable_dollar_quoting, 1},
357                 {"disable-triggers", no_argument, &dopt.disable_triggers, 1},
358                 {"enable-row-security", no_argument, &dopt.enable_row_security, 1},
359                 {"exclude-table-data", required_argument, NULL, 4},
360                 {"if-exists", no_argument, &dopt.if_exists, 1},
361                 {"inserts", no_argument, &dopt.dump_inserts, 1},
362                 {"lock-wait-timeout", required_argument, NULL, 2},
363                 {"no-tablespaces", no_argument, &dopt.outputNoTablespaces, 1},
364                 {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
365                 {"load-via-partition-root", no_argument, &dopt.load_via_partition_root, 1},
366                 {"role", required_argument, NULL, 3},
367                 {"section", required_argument, NULL, 5},
368                 {"serializable-deferrable", no_argument, &dopt.serializable_deferrable, 1},
369                 {"snapshot", required_argument, NULL, 6},
370                 {"strict-names", no_argument, &strict_names, 1},
371                 {"use-set-session-authorization", no_argument, &dopt.use_setsessauth, 1},
372                 {"no-comments", no_argument, &dopt.no_comments, 1},
373                 {"no-publications", no_argument, &dopt.no_publications, 1},
374                 {"no-security-labels", no_argument, &dopt.no_security_labels, 1},
375                 {"no-synchronized-snapshots", no_argument, &dopt.no_synchronized_snapshots, 1},
376                 {"no-unlogged-table-data", no_argument, &dopt.no_unlogged_table_data, 1},
377                 {"no-subscriptions", no_argument, &dopt.no_subscriptions, 1},
378                 {"no-sync", no_argument, NULL, 7},
379                 {"on-conflict-do-nothing", no_argument, &dopt.do_nothing, 1},
380
381                 {NULL, 0, NULL, 0}
382         };
383
384         set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
385
386         /*
387          * Initialize what we need for parallel execution, especially for thread
388          * support on Windows.
389          */
390         init_parallel_dump_utils();
391
392         g_verbose = false;
393
394         strcpy(g_comment_start, "-- ");
395         g_comment_end[0] = '\0';
396         strcpy(g_opaque_type, "opaque");
397
398         progname = get_progname(argv[0]);
399
400         if (argc > 1)
401         {
402                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
403                 {
404                         help(progname);
405                         exit_nicely(0);
406                 }
407                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
408                 {
409                         puts("pg_dump (PostgreSQL) " PG_VERSION);
410                         exit_nicely(0);
411                 }
412         }
413
414         InitDumpOptions(&dopt);
415
416         while ((c = getopt_long(argc, argv, "abBcCd:E:f:F:h:j:n:N:oOp:RsS:t:T:U:vwWxZ:",
417                                                         long_options, &optindex)) != -1)
418         {
419                 switch (c)
420                 {
421                         case 'a':                       /* Dump data only */
422                                 dopt.dataOnly = true;
423                                 break;
424
425                         case 'b':                       /* Dump blobs */
426                                 dopt.outputBlobs = true;
427                                 break;
428
429                         case 'B':                       /* Don't dump blobs */
430                                 dopt.dontOutputBlobs = true;
431                                 break;
432
433                         case 'c':                       /* clean (i.e., drop) schema prior to create */
434                                 dopt.outputClean = 1;
435                                 break;
436
437                         case 'C':                       /* Create DB */
438                                 dopt.outputCreateDB = 1;
439                                 break;
440
441                         case 'd':                       /* database name */
442                                 dopt.dbname = pg_strdup(optarg);
443                                 break;
444
445                         case 'E':                       /* Dump encoding */
446                                 dumpencoding = pg_strdup(optarg);
447                                 break;
448
449                         case 'f':
450                                 filename = pg_strdup(optarg);
451                                 break;
452
453                         case 'F':
454                                 format = pg_strdup(optarg);
455                                 break;
456
457                         case 'h':                       /* server host */
458                                 dopt.pghost = pg_strdup(optarg);
459                                 break;
460
461                         case 'j':                       /* number of dump jobs */
462                                 numWorkers = atoi(optarg);
463                                 break;
464
465                         case 'n':                       /* include schema(s) */
466                                 simple_string_list_append(&schema_include_patterns, optarg);
467                                 dopt.include_everything = false;
468                                 break;
469
470                         case 'N':                       /* exclude schema(s) */
471                                 simple_string_list_append(&schema_exclude_patterns, optarg);
472                                 break;
473
474                         case 'o':                       /* Dump oids */
475                                 dopt.oids = true;
476                                 break;
477
478                         case 'O':                       /* Don't reconnect to match owner */
479                                 dopt.outputNoOwner = 1;
480                                 break;
481
482                         case 'p':                       /* server port */
483                                 dopt.pgport = pg_strdup(optarg);
484                                 break;
485
486                         case 'R':
487                                 /* no-op, still accepted for backwards compatibility */
488                                 break;
489
490                         case 's':                       /* dump schema only */
491                                 dopt.schemaOnly = true;
492                                 break;
493
494                         case 'S':                       /* Username for superuser in plain text output */
495                                 dopt.outputSuperuser = pg_strdup(optarg);
496                                 break;
497
498                         case 't':                       /* include table(s) */
499                                 simple_string_list_append(&table_include_patterns, optarg);
500                                 dopt.include_everything = false;
501                                 break;
502
503                         case 'T':                       /* exclude table(s) */
504                                 simple_string_list_append(&table_exclude_patterns, optarg);
505                                 break;
506
507                         case 'U':
508                                 dopt.username = pg_strdup(optarg);
509                                 break;
510
511                         case 'v':                       /* verbose */
512                                 g_verbose = true;
513                                 break;
514
515                         case 'w':
516                                 prompt_password = TRI_NO;
517                                 break;
518
519                         case 'W':
520                                 prompt_password = TRI_YES;
521                                 break;
522
523                         case 'x':                       /* skip ACL dump */
524                                 dopt.aclsSkip = true;
525                                 break;
526
527                         case 'Z':                       /* Compression Level */
528                                 compressLevel = atoi(optarg);
529                                 if (compressLevel < 0 || compressLevel > 9)
530                                 {
531                                         write_msg(NULL, "compression level must be in range 0..9\n");
532                                         exit_nicely(1);
533                                 }
534                                 break;
535
536                         case 0:
537                                 /* This covers the long options. */
538                                 break;
539
540                         case 2:                         /* lock-wait-timeout */
541                                 dopt.lockWaitTimeout = pg_strdup(optarg);
542                                 break;
543
544                         case 3:                         /* SET ROLE */
545                                 use_role = pg_strdup(optarg);
546                                 break;
547
548                         case 4:                         /* exclude table(s) data */
549                                 simple_string_list_append(&tabledata_exclude_patterns, optarg);
550                                 break;
551
552                         case 5:                         /* section */
553                                 set_dump_section(optarg, &dopt.dumpSections);
554                                 break;
555
556                         case 6:                         /* snapshot */
557                                 dumpsnapshot = pg_strdup(optarg);
558                                 break;
559
560                         case 7:                         /* no-sync */
561                                 dosync = false;
562                                 break;
563
564                         default:
565                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
566                                 exit_nicely(1);
567                 }
568         }
569
570         /*
571          * Non-option argument specifies database name as long as it wasn't
572          * already specified with -d / --dbname
573          */
574         if (optind < argc && dopt.dbname == NULL)
575                 dopt.dbname = argv[optind++];
576
577         /* Complain if any arguments remain */
578         if (optind < argc)
579         {
580                 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
581                                 progname, argv[optind]);
582                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
583                                 progname);
584                 exit_nicely(1);
585         }
586
587         /* --column-inserts implies --inserts */
588         if (dopt.column_inserts)
589                 dopt.dump_inserts = 1;
590
591         /*
592          * Binary upgrade mode implies dumping sequence data even in schema-only
593          * mode.  This is not exposed as a separate option, but kept separate
594          * internally for clarity.
595          */
596         if (dopt.binary_upgrade)
597                 dopt.sequence_data = 1;
598
599         if (dopt.dataOnly && dopt.schemaOnly)
600         {
601                 write_msg(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
602                 exit_nicely(1);
603         }
604
605         if (dopt.dataOnly && dopt.outputClean)
606         {
607                 write_msg(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
608                 exit_nicely(1);
609         }
610
611         if (dopt.dump_inserts && dopt.oids)
612         {
613                 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
614                 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
615                 exit_nicely(1);
616         }
617
618         if (dopt.if_exists && !dopt.outputClean)
619                 exit_horribly(NULL, "option --if-exists requires option -c/--clean\n");
620
621         if (dopt.do_nothing && !(dopt.dump_inserts || dopt.column_inserts))
622                 exit_horribly(NULL, "option --on-conflict-do-nothing requires option --inserts or --column-inserts\n");
623
624         /* Identify archive format to emit */
625         archiveFormat = parseArchiveFormat(format, &archiveMode);
626
627         /* archiveFormat specific setup */
628         if (archiveFormat == archNull)
629                 plainText = 1;
630
631         /* Custom and directory formats are compressed by default, others not */
632         if (compressLevel == -1)
633         {
634 #ifdef HAVE_LIBZ
635                 if (archiveFormat == archCustom || archiveFormat == archDirectory)
636                         compressLevel = Z_DEFAULT_COMPRESSION;
637                 else
638 #endif
639                         compressLevel = 0;
640         }
641
642 #ifndef HAVE_LIBZ
643         if (compressLevel != 0)
644                 write_msg(NULL, "WARNING: requested compression not available in this "
645                                   "installation -- archive will be uncompressed\n");
646         compressLevel = 0;
647 #endif
648
649         /*
650          * If emitting an archive format, we always want to emit a DATABASE item,
651          * in case --create is specified at pg_restore time.
652          */
653         if (!plainText)
654                 dopt.outputCreateDB = 1;
655
656         /*
657          * On Windows we can only have at most MAXIMUM_WAIT_OBJECTS (= 64 usually)
658          * parallel jobs because that's the maximum limit for the
659          * WaitForMultipleObjects() call.
660          */
661         if (numWorkers <= 0
662 #ifdef WIN32
663                 || numWorkers > MAXIMUM_WAIT_OBJECTS
664 #endif
665                 )
666                 exit_horribly(NULL, "invalid number of parallel jobs\n");
667
668         /* Parallel backup only in the directory archive format so far */
669         if (archiveFormat != archDirectory && numWorkers > 1)
670                 exit_horribly(NULL, "parallel backup only supported by the directory format\n");
671
672         /* Open the output file */
673         fout = CreateArchive(filename, archiveFormat, compressLevel, dosync,
674                                                  archiveMode, setupDumpWorker);
675
676         /* Make dump options accessible right away */
677         SetArchiveOptions(fout, &dopt, NULL);
678
679         /* Register the cleanup hook */
680         on_exit_close_archive(fout);
681
682         /* Let the archiver know how noisy to be */
683         fout->verbose = g_verbose;
684
685         /*
686          * We allow the server to be back to 8.0, and up to any minor release of
687          * our own major version.  (See also version check in pg_dumpall.c.)
688          */
689         fout->minRemoteVersion = 80000;
690         fout->maxRemoteVersion = (PG_VERSION_NUM / 100) * 100 + 99;
691
692         fout->numWorkers = numWorkers;
693
694         /*
695          * Open the database using the Archiver, so it knows about it. Errors mean
696          * death.
697          */
698         ConnectDatabase(fout, dopt.dbname, dopt.pghost, dopt.pgport, dopt.username, prompt_password);
699         setup_connection(fout, dumpencoding, dumpsnapshot, use_role);
700
701         /*
702          * Disable security label support if server version < v9.1.x (prevents
703          * access to nonexistent pg_seclabel catalog)
704          */
705         if (fout->remoteVersion < 90100)
706                 dopt.no_security_labels = 1;
707
708         /*
709          * On hot standbys, never try to dump unlogged table data, since it will
710          * just throw an error.
711          */
712         if (fout->isStandby)
713                 dopt.no_unlogged_table_data = true;
714
715         /* Select the appropriate subquery to convert user IDs to names */
716         if (fout->remoteVersion >= 80100)
717                 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
718         else
719                 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
720
721         /* check the version for the synchronized snapshots feature */
722         if (numWorkers > 1 && fout->remoteVersion < 90200
723                 && !dopt.no_synchronized_snapshots)
724                 exit_horribly(NULL,
725                                           "Synchronized snapshots are not supported by this server version.\n"
726                                           "Run with --no-synchronized-snapshots instead if you do not need\n"
727                                           "synchronized snapshots.\n");
728
729         /* check the version when a snapshot is explicitly specified by user */
730         if (dumpsnapshot && fout->remoteVersion < 90200)
731                 exit_horribly(NULL,
732                                           "Exported snapshots are not supported by this server version.\n");
733
734         /*
735          * Find the last built-in OID, if needed (prior to 8.1)
736          *
737          * With 8.1 and above, we can just use FirstNormalObjectId - 1.
738          */
739         if (fout->remoteVersion < 80100)
740                 g_last_builtin_oid = findLastBuiltinOid_V71(fout);
741         else
742                 g_last_builtin_oid = FirstNormalObjectId - 1;
743
744         if (g_verbose)
745                 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
746
747         /* Expand schema selection patterns into OID lists */
748         if (schema_include_patterns.head != NULL)
749         {
750                 expand_schema_name_patterns(fout, &schema_include_patterns,
751                                                                         &schema_include_oids,
752                                                                         strict_names);
753                 if (schema_include_oids.head == NULL)
754                         exit_horribly(NULL, "no matching schemas were found\n");
755         }
756         expand_schema_name_patterns(fout, &schema_exclude_patterns,
757                                                                 &schema_exclude_oids,
758                                                                 false);
759         /* non-matching exclusion patterns aren't an error */
760
761         /* Expand table selection patterns into OID lists */
762         if (table_include_patterns.head != NULL)
763         {
764                 expand_table_name_patterns(fout, &table_include_patterns,
765                                                                    &table_include_oids,
766                                                                    strict_names);
767                 if (table_include_oids.head == NULL)
768                         exit_horribly(NULL, "no matching tables were found\n");
769         }
770         expand_table_name_patterns(fout, &table_exclude_patterns,
771                                                            &table_exclude_oids,
772                                                            false);
773
774         expand_table_name_patterns(fout, &tabledata_exclude_patterns,
775                                                            &tabledata_exclude_oids,
776                                                            false);
777
778         /* non-matching exclusion patterns aren't an error */
779
780         /*
781          * Dumping blobs is the default for dumps where an inclusion switch is not
782          * used (an "include everything" dump).  -B can be used to exclude blobs
783          * from those dumps.  -b can be used to include blobs even when an
784          * inclusion switch is used.
785          *
786          * -s means "schema only" and blobs are data, not schema, so we never
787          * include blobs when -s is used.
788          */
789         if (dopt.include_everything && !dopt.schemaOnly && !dopt.dontOutputBlobs)
790                 dopt.outputBlobs = true;
791
792         /*
793          * Now scan the database and create DumpableObject structs for all the
794          * objects we intend to dump.
795          */
796         tblinfo = getSchemaData(fout, &numTables);
797
798         if (fout->remoteVersion < 80400)
799                 guessConstraintInheritance(tblinfo, numTables);
800
801         if (!dopt.schemaOnly)
802         {
803                 getTableData(&dopt, tblinfo, numTables, dopt.oids, 0);
804                 buildMatViewRefreshDependencies(fout);
805                 if (dopt.dataOnly)
806                         getTableDataFKConstraints();
807         }
808
809         if (dopt.schemaOnly && dopt.sequence_data)
810                 getTableData(&dopt, tblinfo, numTables, dopt.oids, RELKIND_SEQUENCE);
811
812         /*
813          * In binary-upgrade mode, we do not have to worry about the actual blob
814          * data or the associated metadata that resides in the pg_largeobject and
815          * pg_largeobject_metadata tables, respectively.
816          *
817          * However, we do need to collect blob information as there may be
818          * comments or other information on blobs that we do need to dump out.
819          */
820         if (dopt.outputBlobs || dopt.binary_upgrade)
821                 getBlobs(fout);
822
823         /*
824          * Collect dependency data to assist in ordering the objects.
825          */
826         getDependencies(fout);
827
828         /* Lastly, create dummy objects to represent the section boundaries */
829         boundaryObjs = createBoundaryObjects();
830
831         /* Get pointers to all the known DumpableObjects */
832         getDumpableObjects(&dobjs, &numObjs);
833
834         /*
835          * Add dummy dependencies to enforce the dump section ordering.
836          */
837         addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
838
839         /*
840          * Sort the objects into a safe dump order (no forward references).
841          *
842          * We rely on dependency information to help us determine a safe order, so
843          * the initial sort is mostly for cosmetic purposes: we sort by name to
844          * ensure that logically identical schemas will dump identically.
845          */
846         sortDumpableObjectsByTypeName(dobjs, numObjs);
847
848         /* If we do a parallel dump, we want the largest tables to go first */
849         if (archiveFormat == archDirectory && numWorkers > 1)
850                 sortDataAndIndexObjectsBySize(dobjs, numObjs);
851
852         sortDumpableObjects(dobjs, numObjs,
853                                                 boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
854
855         /*
856          * Create archive TOC entries for all the objects to be dumped, in a safe
857          * order.
858          */
859
860         /* First the special ENCODING, STDSTRINGS, and SEARCHPATH entries. */
861         dumpEncoding(fout);
862         dumpStdStrings(fout);
863         dumpSearchPath(fout);
864
865         /* The database items are always next, unless we don't want them at all */
866         if (dopt.outputCreateDB)
867                 dumpDatabase(fout);
868
869         /* Now the rearrangeable objects. */
870         for (i = 0; i < numObjs; i++)
871                 dumpDumpableObject(fout, dobjs[i]);
872
873         /*
874          * Set up options info to ensure we dump what we want.
875          */
876         ropt = NewRestoreOptions();
877         ropt->filename = filename;
878
879         /* if you change this list, see dumpOptionsFromRestoreOptions */
880         ropt->dropSchema = dopt.outputClean;
881         ropt->dataOnly = dopt.dataOnly;
882         ropt->schemaOnly = dopt.schemaOnly;
883         ropt->if_exists = dopt.if_exists;
884         ropt->column_inserts = dopt.column_inserts;
885         ropt->dumpSections = dopt.dumpSections;
886         ropt->aclsSkip = dopt.aclsSkip;
887         ropt->superuser = dopt.outputSuperuser;
888         ropt->createDB = dopt.outputCreateDB;
889         ropt->noOwner = dopt.outputNoOwner;
890         ropt->noTablespace = dopt.outputNoTablespaces;
891         ropt->disable_triggers = dopt.disable_triggers;
892         ropt->use_setsessauth = dopt.use_setsessauth;
893         ropt->disable_dollar_quoting = dopt.disable_dollar_quoting;
894         ropt->dump_inserts = dopt.dump_inserts;
895         ropt->no_comments = dopt.no_comments;
896         ropt->no_publications = dopt.no_publications;
897         ropt->no_security_labels = dopt.no_security_labels;
898         ropt->no_subscriptions = dopt.no_subscriptions;
899         ropt->lockWaitTimeout = dopt.lockWaitTimeout;
900         ropt->include_everything = dopt.include_everything;
901         ropt->enable_row_security = dopt.enable_row_security;
902         ropt->sequence_data = dopt.sequence_data;
903         ropt->binary_upgrade = dopt.binary_upgrade;
904
905         if (compressLevel == -1)
906                 ropt->compression = 0;
907         else
908                 ropt->compression = compressLevel;
909
910         ropt->suppressDumpWarnings = true;      /* We've already shown them */
911
912         SetArchiveOptions(fout, &dopt, ropt);
913
914         /* Mark which entries should be output */
915         ProcessArchiveRestoreOptions(fout);
916
917         /*
918          * The archive's TOC entries are now marked as to which ones will actually
919          * be output, so we can set up their dependency lists properly. This isn't
920          * necessary for plain-text output, though.
921          */
922         if (!plainText)
923                 BuildArchiveDependencies(fout);
924
925         /*
926          * And finally we can do the actual output.
927          *
928          * Note: for non-plain-text output formats, the output file is written
929          * inside CloseArchive().  This is, um, bizarre; but not worth changing
930          * right now.
931          */
932         if (plainText)
933                 RestoreArchive(fout);
934
935         CloseArchive(fout);
936
937         exit_nicely(0);
938 }
939
940
941 static void
942 help(const char *progname)
943 {
944         printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
945         printf(_("Usage:\n"));
946         printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
947
948         printf(_("\nGeneral options:\n"));
949         printf(_("  -f, --file=FILENAME          output file or directory name\n"));
950         printf(_("  -F, --format=c|d|t|p         output file format (custom, directory, tar,\n"
951                          "                               plain text (default))\n"));
952         printf(_("  -j, --jobs=NUM               use this many parallel jobs to dump\n"));
953         printf(_("  -v, --verbose                verbose mode\n"));
954         printf(_("  -V, --version                output version information, then exit\n"));
955         printf(_("  -Z, --compress=0-9           compression level for compressed formats\n"));
956         printf(_("  --lock-wait-timeout=TIMEOUT  fail after waiting TIMEOUT for a table lock\n"));
957         printf(_("  --no-sync                    do not wait for changes to be written safely to disk\n"));
958         printf(_("  -?, --help                   show this help, then exit\n"));
959
960         printf(_("\nOptions controlling the output content:\n"));
961         printf(_("  -a, --data-only              dump only the data, not the schema\n"));
962         printf(_("  -b, --blobs                  include large objects in dump\n"));
963         printf(_("  -B, --no-blobs               exclude large objects in dump\n"));
964         printf(_("  -c, --clean                  clean (drop) database objects before recreating\n"));
965         printf(_("  -C, --create                 include commands to create database in dump\n"));
966         printf(_("  -E, --encoding=ENCODING      dump the data in encoding ENCODING\n"));
967         printf(_("  -n, --schema=SCHEMA          dump the named schema(s) only\n"));
968         printf(_("  -N, --exclude-schema=SCHEMA  do NOT dump the named schema(s)\n"));
969         printf(_("  -o, --oids                   include OIDs in dump\n"));
970         printf(_("  -O, --no-owner               skip restoration of object ownership in\n"
971                          "                               plain-text format\n"));
972         printf(_("  -s, --schema-only            dump only the schema, no data\n"));
973         printf(_("  -S, --superuser=NAME         superuser user name to use in plain-text format\n"));
974         printf(_("  -t, --table=TABLE            dump the named table(s) only\n"));
975         printf(_("  -T, --exclude-table=TABLE    do NOT dump the named table(s)\n"));
976         printf(_("  -x, --no-privileges          do not dump privileges (grant/revoke)\n"));
977         printf(_("  --binary-upgrade             for use by upgrade utilities only\n"));
978         printf(_("  --column-inserts             dump data as INSERT commands with column names\n"));
979         printf(_("  --disable-dollar-quoting     disable dollar quoting, use SQL standard quoting\n"));
980         printf(_("  --disable-triggers           disable triggers during data-only restore\n"));
981         printf(_("  --enable-row-security        enable row security (dump only content user has\n"
982                          "                               access to)\n"));
983         printf(_("  --exclude-table-data=TABLE   do NOT dump data for the named table(s)\n"));
984         printf(_("  --if-exists                  use IF EXISTS when dropping objects\n"));
985         printf(_("  --inserts                    dump data as INSERT commands, rather than COPY\n"));
986         printf(_("  --load-via-partition-root    load partitions via the root table\n"));
987         printf(_("  --no-comments                do not dump comments\n"));
988         printf(_("  --no-publications            do not dump publications\n"));
989         printf(_("  --no-security-labels         do not dump security label assignments\n"));
990         printf(_("  --no-subscriptions           do not dump subscriptions\n"));
991         printf(_("  --no-synchronized-snapshots  do not use synchronized snapshots in parallel jobs\n"));
992         printf(_("  --no-tablespaces             do not dump tablespace assignments\n"));
993         printf(_("  --no-unlogged-table-data     do not dump unlogged table data\n"));
994         printf(_("  --on-conflict-do-nothing     add ON CONFLICT DO NOTHING to INSERT commands\n"));
995         printf(_("  --quote-all-identifiers      quote all identifiers, even if not key words\n"));
996         printf(_("  --section=SECTION            dump named section (pre-data, data, or post-data)\n"));
997         printf(_("  --serializable-deferrable    wait until the dump can run without anomalies\n"));
998         printf(_("  --snapshot=SNAPSHOT          use given snapshot for the dump\n"));
999         printf(_("  --strict-names               require table and/or schema include patterns to\n"
1000                          "                               match at least one entity each\n"));
1001         printf(_("  --use-set-session-authorization\n"
1002                          "                               use SET SESSION AUTHORIZATION commands instead of\n"
1003                          "                               ALTER OWNER commands to set ownership\n"));
1004
1005         printf(_("\nConnection options:\n"));
1006         printf(_("  -d, --dbname=DBNAME      database to dump\n"));
1007         printf(_("  -h, --host=HOSTNAME      database server host or socket directory\n"));
1008         printf(_("  -p, --port=PORT          database server port number\n"));
1009         printf(_("  -U, --username=NAME      connect as specified database user\n"));
1010         printf(_("  -w, --no-password        never prompt for password\n"));
1011         printf(_("  -W, --password           force password prompt (should happen automatically)\n"));
1012         printf(_("  --role=ROLENAME          do SET ROLE before dump\n"));
1013
1014         printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
1015                          "variable value is used.\n\n"));
1016         printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
1017 }
1018
1019 static void
1020 setup_connection(Archive *AH, const char *dumpencoding,
1021                                  const char *dumpsnapshot, char *use_role)
1022 {
1023         DumpOptions *dopt = AH->dopt;
1024         PGconn     *conn = GetConnection(AH);
1025         const char *std_strings;
1026
1027         PQclear(ExecuteSqlQueryForSingleRow(AH, ALWAYS_SECURE_SEARCH_PATH_SQL));
1028
1029         /*
1030          * Set the client encoding if requested.
1031          */
1032         if (dumpencoding)
1033         {
1034                 if (PQsetClientEncoding(conn, dumpencoding) < 0)
1035                         exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
1036                                                   dumpencoding);
1037         }
1038
1039         /*
1040          * Get the active encoding and the standard_conforming_strings setting, so
1041          * we know how to escape strings.
1042          */
1043         AH->encoding = PQclientEncoding(conn);
1044
1045         std_strings = PQparameterStatus(conn, "standard_conforming_strings");
1046         AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
1047
1048         /*
1049          * Set the role if requested.  In a parallel dump worker, we'll be passed
1050          * use_role == NULL, but AH->use_role is already set (if user specified it
1051          * originally) and we should use that.
1052          */
1053         if (!use_role && AH->use_role)
1054                 use_role = AH->use_role;
1055
1056         /* Set the role if requested */
1057         if (use_role && AH->remoteVersion >= 80100)
1058         {
1059                 PQExpBuffer query = createPQExpBuffer();
1060
1061                 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
1062                 ExecuteSqlStatement(AH, query->data);
1063                 destroyPQExpBuffer(query);
1064
1065                 /* save it for possible later use by parallel workers */
1066                 if (!AH->use_role)
1067                         AH->use_role = pg_strdup(use_role);
1068         }
1069
1070         /* Set the datestyle to ISO to ensure the dump's portability */
1071         ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
1072
1073         /* Likewise, avoid using sql_standard intervalstyle */
1074         if (AH->remoteVersion >= 80400)
1075                 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
1076
1077         /*
1078          * Set extra_float_digits so that we can dump float data exactly (given
1079          * correctly implemented float I/O code, anyway)
1080          */
1081         if (AH->remoteVersion >= 90000)
1082                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
1083         else
1084                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
1085
1086         /*
1087          * If synchronized scanning is supported, disable it, to prevent
1088          * unpredictable changes in row ordering across a dump and reload.
1089          */
1090         if (AH->remoteVersion >= 80300)
1091                 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
1092
1093         /*
1094          * Disable timeouts if supported.
1095          */
1096         ExecuteSqlStatement(AH, "SET statement_timeout = 0");
1097         if (AH->remoteVersion >= 90300)
1098                 ExecuteSqlStatement(AH, "SET lock_timeout = 0");
1099         if (AH->remoteVersion >= 90600)
1100                 ExecuteSqlStatement(AH, "SET idle_in_transaction_session_timeout = 0");
1101
1102         /*
1103          * Quote all identifiers, if requested.
1104          */
1105         if (quote_all_identifiers && AH->remoteVersion >= 90100)
1106                 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
1107
1108         /*
1109          * Adjust row-security mode, if supported.
1110          */
1111         if (AH->remoteVersion >= 90500)
1112         {
1113                 if (dopt->enable_row_security)
1114                         ExecuteSqlStatement(AH, "SET row_security = on");
1115                 else
1116                         ExecuteSqlStatement(AH, "SET row_security = off");
1117         }
1118
1119         /*
1120          * Start transaction-snapshot mode transaction to dump consistent data.
1121          */
1122         ExecuteSqlStatement(AH, "BEGIN");
1123         if (AH->remoteVersion >= 90100)
1124         {
1125                 /*
1126                  * To support the combination of serializable_deferrable with the jobs
1127                  * option we use REPEATABLE READ for the worker connections that are
1128                  * passed a snapshot.  As long as the snapshot is acquired in a
1129                  * SERIALIZABLE, READ ONLY, DEFERRABLE transaction, its use within a
1130                  * REPEATABLE READ transaction provides the appropriate integrity
1131                  * guarantees.  This is a kluge, but safe for back-patching.
1132                  */
1133                 if (dopt->serializable_deferrable && AH->sync_snapshot_id == NULL)
1134                         ExecuteSqlStatement(AH,
1135                                                                 "SET TRANSACTION ISOLATION LEVEL "
1136                                                                 "SERIALIZABLE, READ ONLY, DEFERRABLE");
1137                 else
1138                         ExecuteSqlStatement(AH,
1139                                                                 "SET TRANSACTION ISOLATION LEVEL "
1140                                                                 "REPEATABLE READ, READ ONLY");
1141         }
1142         else
1143         {
1144                 ExecuteSqlStatement(AH,
1145                                                         "SET TRANSACTION ISOLATION LEVEL "
1146                                                         "SERIALIZABLE, READ ONLY");
1147         }
1148
1149         /*
1150          * If user specified a snapshot to use, select that.  In a parallel dump
1151          * worker, we'll be passed dumpsnapshot == NULL, but AH->sync_snapshot_id
1152          * is already set (if the server can handle it) and we should use that.
1153          */
1154         if (dumpsnapshot)
1155                 AH->sync_snapshot_id = pg_strdup(dumpsnapshot);
1156
1157         if (AH->sync_snapshot_id)
1158         {
1159                 PQExpBuffer query = createPQExpBuffer();
1160
1161                 appendPQExpBuffer(query, "SET TRANSACTION SNAPSHOT ");
1162                 appendStringLiteralConn(query, AH->sync_snapshot_id, conn);
1163                 ExecuteSqlStatement(AH, query->data);
1164                 destroyPQExpBuffer(query);
1165         }
1166         else if (AH->numWorkers > 1 &&
1167                          AH->remoteVersion >= 90200 &&
1168                          !dopt->no_synchronized_snapshots)
1169         {
1170                 if (AH->isStandby && AH->remoteVersion < 100000)
1171                         exit_horribly(NULL,
1172                                                   "Synchronized snapshots on standby servers are not supported by this server version.\n"
1173                                                   "Run with --no-synchronized-snapshots instead if you do not need\n"
1174                                                   "synchronized snapshots.\n");
1175
1176
1177                 AH->sync_snapshot_id = get_synchronized_snapshot(AH);
1178         }
1179 }
1180
1181 /* Set up connection for a parallel worker process */
1182 static void
1183 setupDumpWorker(Archive *AH)
1184 {
1185         /*
1186          * We want to re-select all the same values the master connection is
1187          * using.  We'll have inherited directly-usable values in
1188          * AH->sync_snapshot_id and AH->use_role, but we need to translate the
1189          * inherited encoding value back to a string to pass to setup_connection.
1190          */
1191         setup_connection(AH,
1192                                          pg_encoding_to_char(AH->encoding),
1193                                          NULL,
1194                                          NULL);
1195 }
1196
1197 static char *
1198 get_synchronized_snapshot(Archive *fout)
1199 {
1200         char       *query = "SELECT pg_catalog.pg_export_snapshot()";
1201         char       *result;
1202         PGresult   *res;
1203
1204         res = ExecuteSqlQueryForSingleRow(fout, query);
1205         result = pg_strdup(PQgetvalue(res, 0, 0));
1206         PQclear(res);
1207
1208         return result;
1209 }
1210
1211 static ArchiveFormat
1212 parseArchiveFormat(const char *format, ArchiveMode *mode)
1213 {
1214         ArchiveFormat archiveFormat;
1215
1216         *mode = archModeWrite;
1217
1218         if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
1219         {
1220                 /* This is used by pg_dumpall, and is not documented */
1221                 archiveFormat = archNull;
1222                 *mode = archModeAppend;
1223         }
1224         else if (pg_strcasecmp(format, "c") == 0)
1225                 archiveFormat = archCustom;
1226         else if (pg_strcasecmp(format, "custom") == 0)
1227                 archiveFormat = archCustom;
1228         else if (pg_strcasecmp(format, "d") == 0)
1229                 archiveFormat = archDirectory;
1230         else if (pg_strcasecmp(format, "directory") == 0)
1231                 archiveFormat = archDirectory;
1232         else if (pg_strcasecmp(format, "p") == 0)
1233                 archiveFormat = archNull;
1234         else if (pg_strcasecmp(format, "plain") == 0)
1235                 archiveFormat = archNull;
1236         else if (pg_strcasecmp(format, "t") == 0)
1237                 archiveFormat = archTar;
1238         else if (pg_strcasecmp(format, "tar") == 0)
1239                 archiveFormat = archTar;
1240         else
1241                 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
1242         return archiveFormat;
1243 }
1244
1245 /*
1246  * Find the OIDs of all schemas matching the given list of patterns,
1247  * and append them to the given OID list.
1248  */
1249 static void
1250 expand_schema_name_patterns(Archive *fout,
1251                                                         SimpleStringList *patterns,
1252                                                         SimpleOidList *oids,
1253                                                         bool strict_names)
1254 {
1255         PQExpBuffer query;
1256         PGresult   *res;
1257         SimpleStringListCell *cell;
1258         int                     i;
1259
1260         if (patterns->head == NULL)
1261                 return;                                 /* nothing to do */
1262
1263         query = createPQExpBuffer();
1264
1265         /*
1266          * The loop below runs multiple SELECTs might sometimes result in
1267          * duplicate entries in the OID list, but we don't care.
1268          */
1269
1270         for (cell = patterns->head; cell; cell = cell->next)
1271         {
1272                 appendPQExpBuffer(query,
1273                                                   "SELECT oid FROM pg_catalog.pg_namespace n\n");
1274                 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1275                                                           false, NULL, "n.nspname", NULL, NULL);
1276
1277                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1278                 if (strict_names && PQntuples(res) == 0)
1279                         exit_horribly(NULL, "no matching schemas were found for pattern \"%s\"\n", cell->val);
1280
1281                 for (i = 0; i < PQntuples(res); i++)
1282                 {
1283                         simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1284                 }
1285
1286                 PQclear(res);
1287                 resetPQExpBuffer(query);
1288         }
1289
1290         destroyPQExpBuffer(query);
1291 }
1292
1293 /*
1294  * Find the OIDs of all tables matching the given list of patterns,
1295  * and append them to the given OID list.
1296  */
1297 static void
1298 expand_table_name_patterns(Archive *fout,
1299                                                    SimpleStringList *patterns, SimpleOidList *oids,
1300                                                    bool strict_names)
1301 {
1302         PQExpBuffer query;
1303         PGresult   *res;
1304         SimpleStringListCell *cell;
1305         int                     i;
1306
1307         if (patterns->head == NULL)
1308                 return;                                 /* nothing to do */
1309
1310         query = createPQExpBuffer();
1311
1312         /*
1313          * this might sometimes result in duplicate entries in the OID list, but
1314          * we don't care.
1315          */
1316
1317         for (cell = patterns->head; cell; cell = cell->next)
1318         {
1319                 /*
1320                  * Query must remain ABSOLUTELY devoid of unqualified names.  This
1321                  * would be unnecessary given a pg_table_is_visible() variant taking a
1322                  * search_path argument.
1323                  */
1324                 appendPQExpBuffer(query,
1325                                                   "SELECT c.oid"
1326                                                   "\nFROM pg_catalog.pg_class c"
1327                                                   "\n     LEFT JOIN pg_catalog.pg_namespace n"
1328                                                   "\n     ON n.oid OPERATOR(pg_catalog.=) c.relnamespace"
1329                                                   "\nWHERE c.relkind OPERATOR(pg_catalog.=) ANY"
1330                                                   "\n    (array['%c', '%c', '%c', '%c', '%c', '%c'])\n",
1331                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1332                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
1333                                                   RELKIND_PARTITIONED_TABLE);
1334                 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1335                                                           false, "n.nspname", "c.relname", NULL,
1336                                                           "pg_catalog.pg_table_is_visible(c.oid)");
1337
1338                 ExecuteSqlStatement(fout, "RESET search_path");
1339                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1340                 PQclear(ExecuteSqlQueryForSingleRow(fout,
1341                                                                                         ALWAYS_SECURE_SEARCH_PATH_SQL));
1342                 if (strict_names && PQntuples(res) == 0)
1343                         exit_horribly(NULL, "no matching tables were found for pattern \"%s\"\n", cell->val);
1344
1345                 for (i = 0; i < PQntuples(res); i++)
1346                 {
1347                         simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1348                 }
1349
1350                 PQclear(res);
1351                 resetPQExpBuffer(query);
1352         }
1353
1354         destroyPQExpBuffer(query);
1355 }
1356
1357 /*
1358  * checkExtensionMembership
1359  *              Determine whether object is an extension member, and if so,
1360  *              record an appropriate dependency and set the object's dump flag.
1361  *
1362  * It's important to call this for each object that could be an extension
1363  * member.  Generally, we integrate this with determining the object's
1364  * to-be-dumped-ness, since extension membership overrides other rules for that.
1365  *
1366  * Returns true if object is an extension member, else false.
1367  */
1368 static bool
1369 checkExtensionMembership(DumpableObject *dobj, Archive *fout)
1370 {
1371         ExtensionInfo *ext = findOwningExtension(dobj->catId);
1372
1373         if (ext == NULL)
1374                 return false;
1375
1376         dobj->ext_member = true;
1377
1378         /* Record dependency so that getDependencies needn't deal with that */
1379         addObjectDependency(dobj, ext->dobj.dumpId);
1380
1381         /*
1382          * In 9.6 and above, mark the member object to have any non-initial ACL,
1383          * policies, and security labels dumped.
1384          *
1385          * Note that any initial ACLs (see pg_init_privs) will be removed when we
1386          * extract the information about the object.  We don't provide support for
1387          * initial policies and security labels and it seems unlikely for those to
1388          * ever exist, but we may have to revisit this later.
1389          *
1390          * Prior to 9.6, we do not include any extension member components.
1391          *
1392          * In binary upgrades, we still dump all components of the members
1393          * individually, since the idea is to exactly reproduce the database
1394          * contents rather than replace the extension contents with something
1395          * different.
1396          */
1397         if (fout->dopt->binary_upgrade)
1398                 dobj->dump = ext->dobj.dump;
1399         else
1400         {
1401                 if (fout->remoteVersion < 90600)
1402                         dobj->dump = DUMP_COMPONENT_NONE;
1403                 else
1404                         dobj->dump = ext->dobj.dump_contains & (DUMP_COMPONENT_ACL |
1405                                                                                                         DUMP_COMPONENT_SECLABEL |
1406                                                                                                         DUMP_COMPONENT_POLICY);
1407         }
1408
1409         return true;
1410 }
1411
1412 /*
1413  * selectDumpableNamespace: policy-setting subroutine
1414  *              Mark a namespace as to be dumped or not
1415  */
1416 static void
1417 selectDumpableNamespace(NamespaceInfo *nsinfo, Archive *fout)
1418 {
1419         /*
1420          * If specific tables are being dumped, do not dump any complete
1421          * namespaces. If specific namespaces are being dumped, dump just those
1422          * namespaces. Otherwise, dump all non-system namespaces.
1423          */
1424         if (table_include_oids.head != NULL)
1425                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1426         else if (schema_include_oids.head != NULL)
1427                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump =
1428                         simple_oid_list_member(&schema_include_oids,
1429                                                                    nsinfo->dobj.catId.oid) ?
1430                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1431         else if (fout->remoteVersion >= 90600 &&
1432                          strcmp(nsinfo->dobj.name, "pg_catalog") == 0)
1433         {
1434                 /*
1435                  * In 9.6 and above, we dump out any ACLs defined in pg_catalog, if
1436                  * they are interesting (and not the original ACLs which were set at
1437                  * initdb time, see pg_init_privs).
1438                  */
1439                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1440         }
1441         else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1442                          strcmp(nsinfo->dobj.name, "information_schema") == 0)
1443         {
1444                 /* Other system schemas don't get dumped */
1445                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1446         }
1447         else if (strcmp(nsinfo->dobj.name, "public") == 0)
1448         {
1449                 /*
1450                  * The public schema is a strange beast that sits in a sort of
1451                  * no-mans-land between being a system object and a user object.  We
1452                  * don't want to dump creation or comment commands for it, because
1453                  * that complicates matters for non-superuser use of pg_dump.  But we
1454                  * should dump any ACL changes that have occurred for it, and of
1455                  * course we should dump contained objects.
1456                  */
1457                 nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1458                 nsinfo->dobj.dump_contains = DUMP_COMPONENT_ALL;
1459         }
1460         else
1461                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ALL;
1462
1463         /*
1464          * In any case, a namespace can be excluded by an exclusion switch
1465          */
1466         if (nsinfo->dobj.dump_contains &&
1467                 simple_oid_list_member(&schema_exclude_oids,
1468                                                            nsinfo->dobj.catId.oid))
1469                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1470
1471         /*
1472          * If the schema belongs to an extension, allow extension membership to
1473          * override the dump decision for the schema itself.  However, this does
1474          * not change dump_contains, so this won't change what we do with objects
1475          * within the schema.  (If they belong to the extension, they'll get
1476          * suppressed by it, otherwise not.)
1477          */
1478         (void) checkExtensionMembership(&nsinfo->dobj, fout);
1479 }
1480
1481 /*
1482  * selectDumpableTable: policy-setting subroutine
1483  *              Mark a table as to be dumped or not
1484  */
1485 static void
1486 selectDumpableTable(TableInfo *tbinfo, Archive *fout)
1487 {
1488         if (checkExtensionMembership(&tbinfo->dobj, fout))
1489                 return;                                 /* extension membership overrides all else */
1490
1491         /*
1492          * If specific tables are being dumped, dump just those tables; else, dump
1493          * according to the parent namespace's dump flag.
1494          */
1495         if (table_include_oids.head != NULL)
1496                 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1497                                                                                                    tbinfo->dobj.catId.oid) ?
1498                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1499         else
1500                 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump_contains;
1501
1502         /*
1503          * In any case, a table can be excluded by an exclusion switch
1504          */
1505         if (tbinfo->dobj.dump &&
1506                 simple_oid_list_member(&table_exclude_oids,
1507                                                            tbinfo->dobj.catId.oid))
1508                 tbinfo->dobj.dump = DUMP_COMPONENT_NONE;
1509 }
1510
1511 /*
1512  * selectDumpableType: policy-setting subroutine
1513  *              Mark a type as to be dumped or not
1514  *
1515  * If it's a table's rowtype or an autogenerated array type, we also apply a
1516  * special type code to facilitate sorting into the desired order.  (We don't
1517  * want to consider those to be ordinary types because that would bring tables
1518  * up into the datatype part of the dump order.)  We still set the object's
1519  * dump flag; that's not going to cause the dummy type to be dumped, but we
1520  * need it so that casts involving such types will be dumped correctly -- see
1521  * dumpCast.  This means the flag should be set the same as for the underlying
1522  * object (the table or base type).
1523  */
1524 static void
1525 selectDumpableType(TypeInfo *tyinfo, Archive *fout)
1526 {
1527         /* skip complex types, except for standalone composite types */
1528         if (OidIsValid(tyinfo->typrelid) &&
1529                 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1530         {
1531                 TableInfo  *tytable = findTableByOid(tyinfo->typrelid);
1532
1533                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1534                 if (tytable != NULL)
1535                         tyinfo->dobj.dump = tytable->dobj.dump;
1536                 else
1537                         tyinfo->dobj.dump = DUMP_COMPONENT_NONE;
1538                 return;
1539         }
1540
1541         /* skip auto-generated array types */
1542         if (tyinfo->isArray)
1543         {
1544                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1545
1546                 /*
1547                  * Fall through to set the dump flag; we assume that the subsequent
1548                  * rules will do the same thing as they would for the array's base
1549                  * type.  (We cannot reliably look up the base type here, since
1550                  * getTypes may not have processed it yet.)
1551                  */
1552         }
1553
1554         if (checkExtensionMembership(&tyinfo->dobj, fout))
1555                 return;                                 /* extension membership overrides all else */
1556
1557         /* Dump based on if the contents of the namespace are being dumped */
1558         tyinfo->dobj.dump = tyinfo->dobj.namespace->dobj.dump_contains;
1559 }
1560
1561 /*
1562  * selectDumpableDefaultACL: policy-setting subroutine
1563  *              Mark a default ACL as to be dumped or not
1564  *
1565  * For per-schema default ACLs, dump if the schema is to be dumped.
1566  * Otherwise dump if we are dumping "everything".  Note that dataOnly
1567  * and aclsSkip are checked separately.
1568  */
1569 static void
1570 selectDumpableDefaultACL(DefaultACLInfo *dinfo, DumpOptions *dopt)
1571 {
1572         /* Default ACLs can't be extension members */
1573
1574         if (dinfo->dobj.namespace)
1575                 /* default ACLs are considered part of the namespace */
1576                 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump_contains;
1577         else
1578                 dinfo->dobj.dump = dopt->include_everything ?
1579                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1580 }
1581
1582 /*
1583  * selectDumpableCast: policy-setting subroutine
1584  *              Mark a cast as to be dumped or not
1585  *
1586  * Casts do not belong to any particular namespace (since they haven't got
1587  * names), nor do they have identifiable owners.  To distinguish user-defined
1588  * casts from built-in ones, we must resort to checking whether the cast's
1589  * OID is in the range reserved for initdb.
1590  */
1591 static void
1592 selectDumpableCast(CastInfo *cast, Archive *fout)
1593 {
1594         if (checkExtensionMembership(&cast->dobj, fout))
1595                 return;                                 /* extension membership overrides all else */
1596
1597         /*
1598          * This would be DUMP_COMPONENT_ACL for from-initdb casts, but they do not
1599          * support ACLs currently.
1600          */
1601         if (cast->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1602                 cast->dobj.dump = DUMP_COMPONENT_NONE;
1603         else
1604                 cast->dobj.dump = fout->dopt->include_everything ?
1605                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1606 }
1607
1608 /*
1609  * selectDumpableProcLang: policy-setting subroutine
1610  *              Mark a procedural language as to be dumped or not
1611  *
1612  * Procedural languages do not belong to any particular namespace.  To
1613  * identify built-in languages, we must resort to checking whether the
1614  * language's OID is in the range reserved for initdb.
1615  */
1616 static void
1617 selectDumpableProcLang(ProcLangInfo *plang, Archive *fout)
1618 {
1619         if (checkExtensionMembership(&plang->dobj, fout))
1620                 return;                                 /* extension membership overrides all else */
1621
1622         /*
1623          * Only include procedural languages when we are dumping everything.
1624          *
1625          * For from-initdb procedural languages, only include ACLs, as we do for
1626          * the pg_catalog namespace.  We need this because procedural languages do
1627          * not live in any namespace.
1628          */
1629         if (!fout->dopt->include_everything)
1630                 plang->dobj.dump = DUMP_COMPONENT_NONE;
1631         else
1632         {
1633                 if (plang->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1634                         plang->dobj.dump = fout->remoteVersion < 90600 ?
1635                                 DUMP_COMPONENT_NONE : DUMP_COMPONENT_ACL;
1636                 else
1637                         plang->dobj.dump = DUMP_COMPONENT_ALL;
1638         }
1639 }
1640
1641 /*
1642  * selectDumpableAccessMethod: policy-setting subroutine
1643  *              Mark an access method as to be dumped or not
1644  *
1645  * Access methods do not belong to any particular namespace.  To identify
1646  * built-in access methods, we must resort to checking whether the
1647  * method's OID is in the range reserved for initdb.
1648  */
1649 static void
1650 selectDumpableAccessMethod(AccessMethodInfo *method, Archive *fout)
1651 {
1652         if (checkExtensionMembership(&method->dobj, fout))
1653                 return;                                 /* extension membership overrides all else */
1654
1655         /*
1656          * This would be DUMP_COMPONENT_ACL for from-initdb access methods, but
1657          * they do not support ACLs currently.
1658          */
1659         if (method->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1660                 method->dobj.dump = DUMP_COMPONENT_NONE;
1661         else
1662                 method->dobj.dump = fout->dopt->include_everything ?
1663                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1664 }
1665
1666 /*
1667  * selectDumpableExtension: policy-setting subroutine
1668  *              Mark an extension as to be dumped or not
1669  *
1670  * Built-in extensions should be skipped except for checking ACLs, since we
1671  * assume those will already be installed in the target database.  We identify
1672  * such extensions by their having OIDs in the range reserved for initdb.
1673  * We dump all user-added extensions by default, or none of them if
1674  * include_everything is false (i.e., a --schema or --table switch was given).
1675  */
1676 static void
1677 selectDumpableExtension(ExtensionInfo *extinfo, DumpOptions *dopt)
1678 {
1679         /*
1680          * Use DUMP_COMPONENT_ACL for built-in extensions, to allow users to
1681          * change permissions on their member objects, if they wish to, and have
1682          * those changes preserved.
1683          */
1684         if (extinfo->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1685                 extinfo->dobj.dump = extinfo->dobj.dump_contains = DUMP_COMPONENT_ACL;
1686         else
1687                 extinfo->dobj.dump = extinfo->dobj.dump_contains =
1688                         dopt->include_everything ? DUMP_COMPONENT_ALL :
1689                         DUMP_COMPONENT_NONE;
1690 }
1691
1692 /*
1693  * selectDumpablePublicationTable: policy-setting subroutine
1694  *              Mark a publication table as to be dumped or not
1695  *
1696  * Publication tables have schemas, but those are ignored in decision making,
1697  * because publications are only dumped when we are dumping everything.
1698  */
1699 static void
1700 selectDumpablePublicationTable(DumpableObject *dobj, Archive *fout)
1701 {
1702         if (checkExtensionMembership(dobj, fout))
1703                 return;                                 /* extension membership overrides all else */
1704
1705         dobj->dump = fout->dopt->include_everything ?
1706                 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1707 }
1708
1709 /*
1710  * selectDumpableObject: policy-setting subroutine
1711  *              Mark a generic dumpable object as to be dumped or not
1712  *
1713  * Use this only for object types without a special-case routine above.
1714  */
1715 static void
1716 selectDumpableObject(DumpableObject *dobj, Archive *fout)
1717 {
1718         if (checkExtensionMembership(dobj, fout))
1719                 return;                                 /* extension membership overrides all else */
1720
1721         /*
1722          * Default policy is to dump if parent namespace is dumpable, or for
1723          * non-namespace-associated items, dump if we're dumping "everything".
1724          */
1725         if (dobj->namespace)
1726                 dobj->dump = dobj->namespace->dobj.dump_contains;
1727         else
1728                 dobj->dump = fout->dopt->include_everything ?
1729                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1730 }
1731
1732 /*
1733  *      Dump a table's contents for loading using the COPY command
1734  *      - this routine is called by the Archiver when it wants the table
1735  *        to be dumped.
1736  */
1737
1738 static int
1739 dumpTableData_copy(Archive *fout, void *dcontext)
1740 {
1741         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1742         TableInfo  *tbinfo = tdinfo->tdtable;
1743         const char *classname = tbinfo->dobj.name;
1744         const bool      hasoids = tbinfo->hasoids;
1745         const bool      oids = tdinfo->oids;
1746         PQExpBuffer q = createPQExpBuffer();
1747
1748         /*
1749          * Note: can't use getThreadLocalPQExpBuffer() here, we're calling fmtId
1750          * which uses it already.
1751          */
1752         PQExpBuffer clistBuf = createPQExpBuffer();
1753         PGconn     *conn = GetConnection(fout);
1754         PGresult   *res;
1755         int                     ret;
1756         char       *copybuf;
1757         const char *column_list;
1758
1759         if (g_verbose)
1760                 write_msg(NULL, "dumping contents of table \"%s.%s\"\n",
1761                                   tbinfo->dobj.namespace->dobj.name, classname);
1762
1763         /*
1764          * Specify the column list explicitly so that we have no possibility of
1765          * retrieving data in the wrong column order.  (The default column
1766          * ordering of COPY will not be what we want in certain corner cases
1767          * involving ADD COLUMN and inheritance.)
1768          */
1769         column_list = fmtCopyColumnList(tbinfo, clistBuf);
1770
1771         if (oids && hasoids)
1772         {
1773                 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1774                                                   fmtQualifiedDumpable(tbinfo),
1775                                                   column_list);
1776         }
1777         else if (tdinfo->filtercond)
1778         {
1779                 /* Note: this syntax is only supported in 8.2 and up */
1780                 appendPQExpBufferStr(q, "COPY (SELECT ");
1781                 /* klugery to get rid of parens in column list */
1782                 if (strlen(column_list) > 2)
1783                 {
1784                         appendPQExpBufferStr(q, column_list + 1);
1785                         q->data[q->len - 1] = ' ';
1786                 }
1787                 else
1788                         appendPQExpBufferStr(q, "* ");
1789                 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1790                                                   fmtQualifiedDumpable(tbinfo),
1791                                                   tdinfo->filtercond);
1792         }
1793         else
1794         {
1795                 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1796                                                   fmtQualifiedDumpable(tbinfo),
1797                                                   column_list);
1798         }
1799         res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1800         PQclear(res);
1801         destroyPQExpBuffer(clistBuf);
1802
1803         for (;;)
1804         {
1805                 ret = PQgetCopyData(conn, &copybuf, 0);
1806
1807                 if (ret < 0)
1808                         break;                          /* done or error */
1809
1810                 if (copybuf)
1811                 {
1812                         WriteData(fout, copybuf, ret);
1813                         PQfreemem(copybuf);
1814                 }
1815
1816                 /* ----------
1817                  * THROTTLE:
1818                  *
1819                  * There was considerable discussion in late July, 2000 regarding
1820                  * slowing down pg_dump when backing up large tables. Users with both
1821                  * slow & fast (multi-processor) machines experienced performance
1822                  * degradation when doing a backup.
1823                  *
1824                  * Initial attempts based on sleeping for a number of ms for each ms
1825                  * of work were deemed too complex, then a simple 'sleep in each loop'
1826                  * implementation was suggested. The latter failed because the loop
1827                  * was too tight. Finally, the following was implemented:
1828                  *
1829                  * If throttle is non-zero, then
1830                  *              See how long since the last sleep.
1831                  *              Work out how long to sleep (based on ratio).
1832                  *              If sleep is more than 100ms, then
1833                  *                      sleep
1834                  *                      reset timer
1835                  *              EndIf
1836                  * EndIf
1837                  *
1838                  * where the throttle value was the number of ms to sleep per ms of
1839                  * work. The calculation was done in each loop.
1840                  *
1841                  * Most of the hard work is done in the backend, and this solution
1842                  * still did not work particularly well: on slow machines, the ratio
1843                  * was 50:1, and on medium paced machines, 1:1, and on fast
1844                  * multi-processor machines, it had little or no effect, for reasons
1845                  * that were unclear.
1846                  *
1847                  * Further discussion ensued, and the proposal was dropped.
1848                  *
1849                  * For those people who want this feature, it can be implemented using
1850                  * gettimeofday in each loop, calculating the time since last sleep,
1851                  * multiplying that by the sleep ratio, then if the result is more
1852                  * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1853                  * function to sleep for a subsecond period ie.
1854                  *
1855                  * select(0, NULL, NULL, NULL, &tvi);
1856                  *
1857                  * This will return after the interval specified in the structure tvi.
1858                  * Finally, call gettimeofday again to save the 'last sleep time'.
1859                  * ----------
1860                  */
1861         }
1862         archprintf(fout, "\\.\n\n\n");
1863
1864         if (ret == -2)
1865         {
1866                 /* copy data transfer failed */
1867                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1868                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1869                 write_msg(NULL, "The command was: %s\n", q->data);
1870                 exit_nicely(1);
1871         }
1872
1873         /* Check command status and return to normal libpq state */
1874         res = PQgetResult(conn);
1875         if (PQresultStatus(res) != PGRES_COMMAND_OK)
1876         {
1877                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1878                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1879                 write_msg(NULL, "The command was: %s\n", q->data);
1880                 exit_nicely(1);
1881         }
1882         PQclear(res);
1883
1884         /* Do this to ensure we've pumped libpq back to idle state */
1885         if (PQgetResult(conn) != NULL)
1886                 write_msg(NULL, "WARNING: unexpected extra results during COPY of table \"%s\"\n",
1887                                   classname);
1888
1889         destroyPQExpBuffer(q);
1890         return 1;
1891 }
1892
1893 /*
1894  * Dump table data using INSERT commands.
1895  *
1896  * Caution: when we restore from an archive file direct to database, the
1897  * INSERT commands emitted by this function have to be parsed by
1898  * pg_backup_db.c's ExecuteSimpleCommands(), which will not handle comments,
1899  * E'' strings, or dollar-quoted strings.  So don't emit anything like that.
1900  */
1901 static int
1902 dumpTableData_insert(Archive *fout, void *dcontext)
1903 {
1904         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1905         TableInfo  *tbinfo = tdinfo->tdtable;
1906         DumpOptions *dopt = fout->dopt;
1907         PQExpBuffer q = createPQExpBuffer();
1908         PQExpBuffer insertStmt = NULL;
1909         PGresult   *res;
1910         int                     tuple;
1911         int                     nfields;
1912         int                     field;
1913
1914         appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1915                                           "SELECT * FROM ONLY %s",
1916                                           fmtQualifiedDumpable(tbinfo));
1917         if (tdinfo->filtercond)
1918                 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1919
1920         ExecuteSqlStatement(fout, q->data);
1921
1922         while (1)
1923         {
1924                 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1925                                                           PGRES_TUPLES_OK);
1926                 nfields = PQnfields(res);
1927                 for (tuple = 0; tuple < PQntuples(res); tuple++)
1928                 {
1929                         /*
1930                          * First time through, we build as much of the INSERT statement as
1931                          * possible in "insertStmt", which we can then just print for each
1932                          * line. If the table happens to have zero columns then this will
1933                          * be a complete statement, otherwise it will end in "VALUES(" and
1934                          * be ready to have the row's column values appended.
1935                          */
1936                         if (insertStmt == NULL)
1937                         {
1938                                 TableInfo  *targettab;
1939
1940                                 insertStmt = createPQExpBuffer();
1941
1942                                 /*
1943                                  * When load-via-partition-root is set, get the root table
1944                                  * name for the partition table, so that we can reload data
1945                                  * through the root table.
1946                                  */
1947                                 if (dopt->load_via_partition_root && tbinfo->ispartition)
1948                                         targettab = getRootTableInfo(tbinfo);
1949                                 else
1950                                         targettab = tbinfo;
1951
1952                                 appendPQExpBuffer(insertStmt, "INSERT INTO %s ",
1953                                                                   fmtQualifiedDumpable(targettab));
1954
1955                                 /* corner case for zero-column table */
1956                                 if (nfields == 0)
1957                                 {
1958                                         appendPQExpBufferStr(insertStmt, "DEFAULT VALUES;\n");
1959                                 }
1960                                 else
1961                                 {
1962                                         /* append the list of column names if required */
1963                                         if (dopt->column_inserts)
1964                                         {
1965                                                 appendPQExpBufferChar(insertStmt, '(');
1966                                                 for (field = 0; field < nfields; field++)
1967                                                 {
1968                                                         if (field > 0)
1969                                                                 appendPQExpBufferStr(insertStmt, ", ");
1970                                                         appendPQExpBufferStr(insertStmt,
1971                                                                                                  fmtId(PQfname(res, field)));
1972                                                 }
1973                                                 appendPQExpBufferStr(insertStmt, ") ");
1974                                         }
1975
1976                                         if (tbinfo->needs_override)
1977                                                 appendPQExpBufferStr(insertStmt, "OVERRIDING SYSTEM VALUE ");
1978
1979                                         appendPQExpBufferStr(insertStmt, "VALUES (");
1980                                 }
1981                         }
1982
1983                         archputs(insertStmt->data, fout);
1984
1985                         /* if it is zero-column table then we're done */
1986                         if (nfields == 0)
1987                                 continue;
1988
1989                         for (field = 0; field < nfields; field++)
1990                         {
1991                                 if (field > 0)
1992                                         archputs(", ", fout);
1993                                 if (PQgetisnull(res, tuple, field))
1994                                 {
1995                                         archputs("NULL", fout);
1996                                         continue;
1997                                 }
1998
1999                                 /* XXX This code is partially duplicated in ruleutils.c */
2000                                 switch (PQftype(res, field))
2001                                 {
2002                                         case INT2OID:
2003                                         case INT4OID:
2004                                         case INT8OID:
2005                                         case OIDOID:
2006                                         case FLOAT4OID:
2007                                         case FLOAT8OID:
2008                                         case NUMERICOID:
2009                                                 {
2010                                                         /*
2011                                                          * These types are printed without quotes unless
2012                                                          * they contain values that aren't accepted by the
2013                                                          * scanner unquoted (e.g., 'NaN').  Note that
2014                                                          * strtod() and friends might accept NaN, so we
2015                                                          * can't use that to test.
2016                                                          *
2017                                                          * In reality we only need to defend against
2018                                                          * infinity and NaN, so we need not get too crazy
2019                                                          * about pattern matching here.
2020                                                          */
2021                                                         const char *s = PQgetvalue(res, tuple, field);
2022
2023                                                         if (strspn(s, "0123456789 +-eE.") == strlen(s))
2024                                                                 archputs(s, fout);
2025                                                         else
2026                                                                 archprintf(fout, "'%s'", s);
2027                                                 }
2028                                                 break;
2029
2030                                         case BITOID:
2031                                         case VARBITOID:
2032                                                 archprintf(fout, "B'%s'",
2033                                                                    PQgetvalue(res, tuple, field));
2034                                                 break;
2035
2036                                         case BOOLOID:
2037                                                 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
2038                                                         archputs("true", fout);
2039                                                 else
2040                                                         archputs("false", fout);
2041                                                 break;
2042
2043                                         default:
2044                                                 /* All other types are printed as string literals. */
2045                                                 resetPQExpBuffer(q);
2046                                                 appendStringLiteralAH(q,
2047                                                                                           PQgetvalue(res, tuple, field),
2048                                                                                           fout);
2049                                                 archputs(q->data, fout);
2050                                                 break;
2051                                 }
2052                         }
2053
2054                         if (!dopt->do_nothing)
2055                                 archputs(");\n", fout);
2056                         else
2057                                 archputs(") ON CONFLICT DO NOTHING;\n", fout);
2058                 }
2059
2060                 if (PQntuples(res) <= 0)
2061                 {
2062                         PQclear(res);
2063                         break;
2064                 }
2065                 PQclear(res);
2066         }
2067
2068         archputs("\n\n", fout);
2069
2070         ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
2071
2072         destroyPQExpBuffer(q);
2073         if (insertStmt != NULL)
2074                 destroyPQExpBuffer(insertStmt);
2075
2076         return 1;
2077 }
2078
2079 /*
2080  * getRootTableInfo:
2081  *     get the root TableInfo for the given partition table.
2082  */
2083 static TableInfo *
2084 getRootTableInfo(TableInfo *tbinfo)
2085 {
2086         TableInfo  *parentTbinfo;
2087
2088         Assert(tbinfo->ispartition);
2089         Assert(tbinfo->numParents == 1);
2090
2091         parentTbinfo = tbinfo->parents[0];
2092         while (parentTbinfo->ispartition)
2093         {
2094                 Assert(parentTbinfo->numParents == 1);
2095                 parentTbinfo = parentTbinfo->parents[0];
2096         }
2097
2098         return parentTbinfo;
2099 }
2100
2101 /*
2102  * dumpTableData -
2103  *        dump the contents of a single table
2104  *
2105  * Actually, this just makes an ArchiveEntry for the table contents.
2106  */
2107 static void
2108 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
2109 {
2110         DumpOptions *dopt = fout->dopt;
2111         TableInfo  *tbinfo = tdinfo->tdtable;
2112         PQExpBuffer copyBuf = createPQExpBuffer();
2113         PQExpBuffer clistBuf = createPQExpBuffer();
2114         DataDumperPtr dumpFn;
2115         char       *copyStmt;
2116         const char *copyFrom;
2117
2118         if (!dopt->dump_inserts)
2119         {
2120                 /* Dump/restore using COPY */
2121                 dumpFn = dumpTableData_copy;
2122
2123                 /*
2124                  * When load-via-partition-root is set, get the root table name for
2125                  * the partition table, so that we can reload data through the root
2126                  * table.
2127                  */
2128                 if (dopt->load_via_partition_root && tbinfo->ispartition)
2129                 {
2130                         TableInfo  *parentTbinfo;
2131
2132                         parentTbinfo = getRootTableInfo(tbinfo);
2133                         copyFrom = fmtQualifiedDumpable(parentTbinfo);
2134                 }
2135                 else
2136                         copyFrom = fmtQualifiedDumpable(tbinfo);
2137
2138                 /* must use 2 steps here 'cause fmtId is nonreentrant */
2139                 appendPQExpBuffer(copyBuf, "COPY %s ",
2140                                                   copyFrom);
2141                 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
2142                                                   fmtCopyColumnList(tbinfo, clistBuf),
2143                                                   (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
2144                 copyStmt = copyBuf->data;
2145         }
2146         else
2147         {
2148                 /* Restore using INSERT */
2149                 dumpFn = dumpTableData_insert;
2150                 copyStmt = NULL;
2151         }
2152
2153         /*
2154          * Note: although the TableDataInfo is a full DumpableObject, we treat its
2155          * dependency on its table as "special" and pass it to ArchiveEntry now.
2156          * See comments for BuildArchiveDependencies.
2157          */
2158         if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2159                 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
2160                                          tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
2161                                          NULL, tbinfo->rolname,
2162                                          false, "TABLE DATA", SECTION_DATA,
2163                                          "", "", copyStmt,
2164                                          &(tbinfo->dobj.dumpId), 1,
2165                                          dumpFn, tdinfo);
2166
2167         destroyPQExpBuffer(copyBuf);
2168         destroyPQExpBuffer(clistBuf);
2169 }
2170
2171 /*
2172  * refreshMatViewData -
2173  *        load or refresh the contents of a single materialized view
2174  *
2175  * Actually, this just makes an ArchiveEntry for the REFRESH MATERIALIZED VIEW
2176  * statement.
2177  */
2178 static void
2179 refreshMatViewData(Archive *fout, TableDataInfo *tdinfo)
2180 {
2181         TableInfo  *tbinfo = tdinfo->tdtable;
2182         PQExpBuffer q;
2183
2184         /* If the materialized view is not flagged as populated, skip this. */
2185         if (!tbinfo->relispopulated)
2186                 return;
2187
2188         q = createPQExpBuffer();
2189
2190         appendPQExpBuffer(q, "REFRESH MATERIALIZED VIEW %s;\n",
2191                                           fmtQualifiedDumpable(tbinfo));
2192
2193         if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2194                 ArchiveEntry(fout,
2195                                          tdinfo->dobj.catId,    /* catalog ID */
2196                                          tdinfo->dobj.dumpId,   /* dump ID */
2197                                          tbinfo->dobj.name, /* Name */
2198                                          tbinfo->dobj.namespace->dobj.name, /* Namespace */
2199                                          NULL,          /* Tablespace */
2200                                          tbinfo->rolname,       /* Owner */
2201                                          false,         /* with oids */
2202                                          "MATERIALIZED VIEW DATA",      /* Desc */
2203                                          SECTION_POST_DATA, /* Section */
2204                                          q->data,       /* Create */
2205                                          "",            /* Del */
2206                                          NULL,          /* Copy */
2207                                          tdinfo->dobj.dependencies, /* Deps */
2208                                          tdinfo->dobj.nDeps,    /* # Deps */
2209                                          NULL,          /* Dumper */
2210                                          NULL);         /* Dumper Arg */
2211
2212         destroyPQExpBuffer(q);
2213 }
2214
2215 /*
2216  * getTableData -
2217  *        set up dumpable objects representing the contents of tables
2218  */
2219 static void
2220 getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, bool oids, char relkind)
2221 {
2222         int                     i;
2223
2224         for (i = 0; i < numTables; i++)
2225         {
2226                 if (tblinfo[i].dobj.dump & DUMP_COMPONENT_DATA &&
2227                         (!relkind || tblinfo[i].relkind == relkind))
2228                         makeTableDataInfo(dopt, &(tblinfo[i]), oids);
2229         }
2230 }
2231
2232 /*
2233  * Make a dumpable object for the data of this specific table
2234  *
2235  * Note: we make a TableDataInfo if and only if we are going to dump the
2236  * table data; the "dump" flag in such objects isn't used.
2237  */
2238 static void
2239 makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo, bool oids)
2240 {
2241         TableDataInfo *tdinfo;
2242
2243         /*
2244          * Nothing to do if we already decided to dump the table.  This will
2245          * happen for "config" tables.
2246          */
2247         if (tbinfo->dataObj != NULL)
2248                 return;
2249
2250         /* Skip VIEWs (no data to dump) */
2251         if (tbinfo->relkind == RELKIND_VIEW)
2252                 return;
2253         /* Skip FOREIGN TABLEs (no data to dump) */
2254         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
2255                 return;
2256         /* Skip partitioned tables (data in partitions) */
2257         if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
2258                 return;
2259
2260         /* Don't dump data in unlogged tables, if so requested */
2261         if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
2262                 dopt->no_unlogged_table_data)
2263                 return;
2264
2265         /* Check that the data is not explicitly excluded */
2266         if (simple_oid_list_member(&tabledata_exclude_oids,
2267                                                            tbinfo->dobj.catId.oid))
2268                 return;
2269
2270         /* OK, let's dump it */
2271         tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
2272
2273         if (tbinfo->relkind == RELKIND_MATVIEW)
2274                 tdinfo->dobj.objType = DO_REFRESH_MATVIEW;
2275         else if (tbinfo->relkind == RELKIND_SEQUENCE)
2276                 tdinfo->dobj.objType = DO_SEQUENCE_SET;
2277         else
2278                 tdinfo->dobj.objType = DO_TABLE_DATA;
2279
2280         /*
2281          * Note: use tableoid 0 so that this object won't be mistaken for
2282          * something that pg_depend entries apply to.
2283          */
2284         tdinfo->dobj.catId.tableoid = 0;
2285         tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
2286         AssignDumpId(&tdinfo->dobj);
2287         tdinfo->dobj.name = tbinfo->dobj.name;
2288         tdinfo->dobj.namespace = tbinfo->dobj.namespace;
2289         tdinfo->tdtable = tbinfo;
2290         tdinfo->oids = oids;
2291         tdinfo->filtercond = NULL;      /* might get set later */
2292         addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
2293
2294         tbinfo->dataObj = tdinfo;
2295 }
2296
2297 /*
2298  * The refresh for a materialized view must be dependent on the refresh for
2299  * any materialized view that this one is dependent on.
2300  *
2301  * This must be called after all the objects are created, but before they are
2302  * sorted.
2303  */
2304 static void
2305 buildMatViewRefreshDependencies(Archive *fout)
2306 {
2307         PQExpBuffer query;
2308         PGresult   *res;
2309         int                     ntups,
2310                                 i;
2311         int                     i_classid,
2312                                 i_objid,
2313                                 i_refobjid;
2314
2315         /* No Mat Views before 9.3. */
2316         if (fout->remoteVersion < 90300)
2317                 return;
2318
2319         query = createPQExpBuffer();
2320
2321         appendPQExpBufferStr(query, "WITH RECURSIVE w AS "
2322                                                  "( "
2323                                                  "SELECT d1.objid, d2.refobjid, c2.relkind AS refrelkind "
2324                                                  "FROM pg_depend d1 "
2325                                                  "JOIN pg_class c1 ON c1.oid = d1.objid "
2326                                                  "AND c1.relkind = " CppAsString2(RELKIND_MATVIEW)
2327                                                  " JOIN pg_rewrite r1 ON r1.ev_class = d1.objid "
2328                                                  "JOIN pg_depend d2 ON d2.classid = 'pg_rewrite'::regclass "
2329                                                  "AND d2.objid = r1.oid "
2330                                                  "AND d2.refobjid <> d1.objid "
2331                                                  "JOIN pg_class c2 ON c2.oid = d2.refobjid "
2332                                                  "AND c2.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2333                                                  CppAsString2(RELKIND_VIEW) ") "
2334                                                  "WHERE d1.classid = 'pg_class'::regclass "
2335                                                  "UNION "
2336                                                  "SELECT w.objid, d3.refobjid, c3.relkind "
2337                                                  "FROM w "
2338                                                  "JOIN pg_rewrite r3 ON r3.ev_class = w.refobjid "
2339                                                  "JOIN pg_depend d3 ON d3.classid = 'pg_rewrite'::regclass "
2340                                                  "AND d3.objid = r3.oid "
2341                                                  "AND d3.refobjid <> w.refobjid "
2342                                                  "JOIN pg_class c3 ON c3.oid = d3.refobjid "
2343                                                  "AND c3.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2344                                                  CppAsString2(RELKIND_VIEW) ") "
2345                                                  ") "
2346                                                  "SELECT 'pg_class'::regclass::oid AS classid, objid, refobjid "
2347                                                  "FROM w "
2348                                                  "WHERE refrelkind = " CppAsString2(RELKIND_MATVIEW));
2349
2350         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2351
2352         ntups = PQntuples(res);
2353
2354         i_classid = PQfnumber(res, "classid");
2355         i_objid = PQfnumber(res, "objid");
2356         i_refobjid = PQfnumber(res, "refobjid");
2357
2358         for (i = 0; i < ntups; i++)
2359         {
2360                 CatalogId       objId;
2361                 CatalogId       refobjId;
2362                 DumpableObject *dobj;
2363                 DumpableObject *refdobj;
2364                 TableInfo  *tbinfo;
2365                 TableInfo  *reftbinfo;
2366
2367                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
2368                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
2369                 refobjId.tableoid = objId.tableoid;
2370                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
2371
2372                 dobj = findObjectByCatalogId(objId);
2373                 if (dobj == NULL)
2374                         continue;
2375
2376                 Assert(dobj->objType == DO_TABLE);
2377                 tbinfo = (TableInfo *) dobj;
2378                 Assert(tbinfo->relkind == RELKIND_MATVIEW);
2379                 dobj = (DumpableObject *) tbinfo->dataObj;
2380                 if (dobj == NULL)
2381                         continue;
2382                 Assert(dobj->objType == DO_REFRESH_MATVIEW);
2383
2384                 refdobj = findObjectByCatalogId(refobjId);
2385                 if (refdobj == NULL)
2386                         continue;
2387
2388                 Assert(refdobj->objType == DO_TABLE);
2389                 reftbinfo = (TableInfo *) refdobj;
2390                 Assert(reftbinfo->relkind == RELKIND_MATVIEW);
2391                 refdobj = (DumpableObject *) reftbinfo->dataObj;
2392                 if (refdobj == NULL)
2393                         continue;
2394                 Assert(refdobj->objType == DO_REFRESH_MATVIEW);
2395
2396                 addObjectDependency(dobj, refdobj->dumpId);
2397
2398                 if (!reftbinfo->relispopulated)
2399                         tbinfo->relispopulated = false;
2400         }
2401
2402         PQclear(res);
2403
2404         destroyPQExpBuffer(query);
2405 }
2406
2407 /*
2408  * getTableDataFKConstraints -
2409  *        add dump-order dependencies reflecting foreign key constraints
2410  *
2411  * This code is executed only in a data-only dump --- in schema+data dumps
2412  * we handle foreign key issues by not creating the FK constraints until
2413  * after the data is loaded.  In a data-only dump, however, we want to
2414  * order the table data objects in such a way that a table's referenced
2415  * tables are restored first.  (In the presence of circular references or
2416  * self-references this may be impossible; we'll detect and complain about
2417  * that during the dependency sorting step.)
2418  */
2419 static void
2420 getTableDataFKConstraints(void)
2421 {
2422         DumpableObject **dobjs;
2423         int                     numObjs;
2424         int                     i;
2425
2426         /* Search through all the dumpable objects for FK constraints */
2427         getDumpableObjects(&dobjs, &numObjs);
2428         for (i = 0; i < numObjs; i++)
2429         {
2430                 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
2431                 {
2432                         ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
2433                         TableInfo  *ftable;
2434
2435                         /* Not interesting unless both tables are to be dumped */
2436                         if (cinfo->contable == NULL ||
2437                                 cinfo->contable->dataObj == NULL)
2438                                 continue;
2439                         ftable = findTableByOid(cinfo->confrelid);
2440                         if (ftable == NULL ||
2441                                 ftable->dataObj == NULL)
2442                                 continue;
2443
2444                         /*
2445                          * Okay, make referencing table's TABLE_DATA object depend on the
2446                          * referenced table's TABLE_DATA object.
2447                          */
2448                         addObjectDependency(&cinfo->contable->dataObj->dobj,
2449                                                                 ftable->dataObj->dobj.dumpId);
2450                 }
2451         }
2452         free(dobjs);
2453 }
2454
2455
2456 /*
2457  * guessConstraintInheritance:
2458  *      In pre-8.4 databases, we can't tell for certain which constraints
2459  *      are inherited.  We assume a CHECK constraint is inherited if its name
2460  *      matches the name of any constraint in the parent.  Originally this code
2461  *      tried to compare the expression texts, but that can fail for various
2462  *      reasons --- for example, if the parent and child tables are in different
2463  *      schemas, reverse-listing of function calls may produce different text
2464  *      (schema-qualified or not) depending on search path.
2465  *
2466  *      In 8.4 and up we can rely on the conislocal field to decide which
2467  *      constraints must be dumped; much safer.
2468  *
2469  *      This function assumes all conislocal flags were initialized to true.
2470  *      It clears the flag on anything that seems to be inherited.
2471  */
2472 static void
2473 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
2474 {
2475         int                     i,
2476                                 j,
2477                                 k;
2478
2479         for (i = 0; i < numTables; i++)
2480         {
2481                 TableInfo  *tbinfo = &(tblinfo[i]);
2482                 int                     numParents;
2483                 TableInfo **parents;
2484                 TableInfo  *parent;
2485
2486                 /* Sequences and views never have parents */
2487                 if (tbinfo->relkind == RELKIND_SEQUENCE ||
2488                         tbinfo->relkind == RELKIND_VIEW)
2489                         continue;
2490
2491                 /* Don't bother computing anything for non-target tables, either */
2492                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
2493                         continue;
2494
2495                 numParents = tbinfo->numParents;
2496                 parents = tbinfo->parents;
2497
2498                 if (numParents == 0)
2499                         continue;                       /* nothing to see here, move along */
2500
2501                 /* scan for inherited CHECK constraints */
2502                 for (j = 0; j < tbinfo->ncheck; j++)
2503                 {
2504                         ConstraintInfo *constr;
2505
2506                         constr = &(tbinfo->checkexprs[j]);
2507
2508                         for (k = 0; k < numParents; k++)
2509                         {
2510                                 int                     l;
2511
2512                                 parent = parents[k];
2513                                 for (l = 0; l < parent->ncheck; l++)
2514                                 {
2515                                         ConstraintInfo *pconstr = &(parent->checkexprs[l]);
2516
2517                                         if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
2518                                         {
2519                                                 constr->conislocal = false;
2520                                                 break;
2521                                         }
2522                                 }
2523                                 if (!constr->conislocal)
2524                                         break;
2525                         }
2526                 }
2527         }
2528 }
2529
2530
2531 /*
2532  * dumpDatabase:
2533  *      dump the database definition
2534  */
2535 static void
2536 dumpDatabase(Archive *fout)
2537 {
2538         DumpOptions *dopt = fout->dopt;
2539         PQExpBuffer dbQry = createPQExpBuffer();
2540         PQExpBuffer delQry = createPQExpBuffer();
2541         PQExpBuffer creaQry = createPQExpBuffer();
2542         PQExpBuffer labelq = createPQExpBuffer();
2543         PGconn     *conn = GetConnection(fout);
2544         PGresult   *res;
2545         int                     i_tableoid,
2546                                 i_oid,
2547                                 i_datname,
2548                                 i_dba,
2549                                 i_encoding,
2550                                 i_collate,
2551                                 i_ctype,
2552                                 i_frozenxid,
2553                                 i_minmxid,
2554                                 i_datacl,
2555                                 i_rdatacl,
2556                                 i_datistemplate,
2557                                 i_datconnlimit,
2558                                 i_tablespace;
2559         CatalogId       dbCatId;
2560         DumpId          dbDumpId;
2561         const char *datname,
2562                            *dba,
2563                            *encoding,
2564                            *collate,
2565                            *ctype,
2566                            *datacl,
2567                            *rdatacl,
2568                            *datistemplate,
2569                            *datconnlimit,
2570                            *tablespace;
2571         uint32          frozenxid,
2572                                 minmxid;
2573         char       *qdatname;
2574
2575         if (g_verbose)
2576                 write_msg(NULL, "saving database definition\n");
2577
2578         /* Fetch the database-level properties for this database */
2579         if (fout->remoteVersion >= 90600)
2580         {
2581                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2582                                                   "(%s datdba) AS dba, "
2583                                                   "pg_encoding_to_char(encoding) AS encoding, "
2584                                                   "datcollate, datctype, datfrozenxid, datminmxid, "
2585                                                   "(SELECT array_agg(acl ORDER BY acl::text COLLATE \"C\") FROM ( "
2586                                                   "  SELECT unnest(coalesce(datacl,acldefault('d',datdba))) AS acl "
2587                                                   "  EXCEPT SELECT unnest(acldefault('d',datdba))) as datacls)"
2588                                                   " AS datacl, "
2589                                                   "(SELECT array_agg(acl ORDER BY acl::text COLLATE \"C\") FROM ( "
2590                                                   "  SELECT unnest(acldefault('d',datdba)) AS acl "
2591                                                   "  EXCEPT SELECT unnest(coalesce(datacl,acldefault('d',datdba)))) as rdatacls)"
2592                                                   " AS rdatacl, "
2593                                                   "datistemplate, datconnlimit, "
2594                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2595                                                   "shobj_description(oid, 'pg_database') AS description "
2596
2597                                                   "FROM pg_database "
2598                                                   "WHERE datname = current_database()",
2599                                                   username_subquery);
2600         }
2601         else if (fout->remoteVersion >= 90300)
2602         {
2603                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2604                                                   "(%s datdba) AS dba, "
2605                                                   "pg_encoding_to_char(encoding) AS encoding, "
2606                                                   "datcollate, datctype, datfrozenxid, datminmxid, "
2607                                                   "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2608                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2609                                                   "shobj_description(oid, 'pg_database') AS description "
2610
2611                                                   "FROM pg_database "
2612                                                   "WHERE datname = current_database()",
2613                                                   username_subquery);
2614         }
2615         else if (fout->remoteVersion >= 80400)
2616         {
2617                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2618                                                   "(%s datdba) AS dba, "
2619                                                   "pg_encoding_to_char(encoding) AS encoding, "
2620                                                   "datcollate, datctype, datfrozenxid, 0 AS datminmxid, "
2621                                                   "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2622                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2623                                                   "shobj_description(oid, 'pg_database') AS description "
2624
2625                                                   "FROM pg_database "
2626                                                   "WHERE datname = current_database()",
2627                                                   username_subquery);
2628         }
2629         else if (fout->remoteVersion >= 80200)
2630         {
2631                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2632                                                   "(%s datdba) AS dba, "
2633                                                   "pg_encoding_to_char(encoding) AS encoding, "
2634                                                   "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2635                                                   "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2636                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2637                                                   "shobj_description(oid, 'pg_database') AS description "
2638
2639                                                   "FROM pg_database "
2640                                                   "WHERE datname = current_database()",
2641                                                   username_subquery);
2642         }
2643         else
2644         {
2645                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, datname, "
2646                                                   "(%s datdba) AS dba, "
2647                                                   "pg_encoding_to_char(encoding) AS encoding, "
2648                                                   "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2649                                                   "datacl, '' as rdatacl, datistemplate, "
2650                                                   "-1 as datconnlimit, "
2651                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
2652                                                   "FROM pg_database "
2653                                                   "WHERE datname = current_database()",
2654                                                   username_subquery);
2655         }
2656
2657         res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
2658
2659         i_tableoid = PQfnumber(res, "tableoid");
2660         i_oid = PQfnumber(res, "oid");
2661         i_datname = PQfnumber(res, "datname");
2662         i_dba = PQfnumber(res, "dba");
2663         i_encoding = PQfnumber(res, "encoding");
2664         i_collate = PQfnumber(res, "datcollate");
2665         i_ctype = PQfnumber(res, "datctype");
2666         i_frozenxid = PQfnumber(res, "datfrozenxid");
2667         i_minmxid = PQfnumber(res, "datminmxid");
2668         i_datacl = PQfnumber(res, "datacl");
2669         i_rdatacl = PQfnumber(res, "rdatacl");
2670         i_datistemplate = PQfnumber(res, "datistemplate");
2671         i_datconnlimit = PQfnumber(res, "datconnlimit");
2672         i_tablespace = PQfnumber(res, "tablespace");
2673
2674         dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
2675         dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
2676         datname = PQgetvalue(res, 0, i_datname);
2677         dba = PQgetvalue(res, 0, i_dba);
2678         encoding = PQgetvalue(res, 0, i_encoding);
2679         collate = PQgetvalue(res, 0, i_collate);
2680         ctype = PQgetvalue(res, 0, i_ctype);
2681         frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
2682         minmxid = atooid(PQgetvalue(res, 0, i_minmxid));
2683         datacl = PQgetvalue(res, 0, i_datacl);
2684         rdatacl = PQgetvalue(res, 0, i_rdatacl);
2685         datistemplate = PQgetvalue(res, 0, i_datistemplate);
2686         datconnlimit = PQgetvalue(res, 0, i_datconnlimit);
2687         tablespace = PQgetvalue(res, 0, i_tablespace);
2688
2689         qdatname = pg_strdup(fmtId(datname));
2690
2691         /*
2692          * Prepare the CREATE DATABASE command.  We must specify encoding, locale,
2693          * and tablespace since those can't be altered later.  Other DB properties
2694          * are left to the DATABASE PROPERTIES entry, so that they can be applied
2695          * after reconnecting to the target DB.
2696          */
2697         appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
2698                                           qdatname);
2699         if (strlen(encoding) > 0)
2700         {
2701                 appendPQExpBufferStr(creaQry, " ENCODING = ");
2702                 appendStringLiteralAH(creaQry, encoding, fout);
2703         }
2704         if (strlen(collate) > 0)
2705         {
2706                 appendPQExpBufferStr(creaQry, " LC_COLLATE = ");
2707                 appendStringLiteralAH(creaQry, collate, fout);
2708         }
2709         if (strlen(ctype) > 0)
2710         {
2711                 appendPQExpBufferStr(creaQry, " LC_CTYPE = ");
2712                 appendStringLiteralAH(creaQry, ctype, fout);
2713         }
2714
2715         /*
2716          * Note: looking at dopt->outputNoTablespaces here is completely the wrong
2717          * thing; the decision whether to specify a tablespace should be left till
2718          * pg_restore, so that pg_restore --no-tablespaces applies.  Ideally we'd
2719          * label the DATABASE entry with the tablespace and let the normal
2720          * tablespace selection logic work ... but CREATE DATABASE doesn't pay
2721          * attention to default_tablespace, so that won't work.
2722          */
2723         if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0 &&
2724                 !dopt->outputNoTablespaces)
2725                 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
2726                                                   fmtId(tablespace));
2727         appendPQExpBufferStr(creaQry, ";\n");
2728
2729         appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
2730                                           qdatname);
2731
2732         dbDumpId = createDumpId();
2733
2734         ArchiveEntry(fout,
2735                                  dbCatId,               /* catalog ID */
2736                                  dbDumpId,              /* dump ID */
2737                                  datname,               /* Name */
2738                                  NULL,                  /* Namespace */
2739                                  NULL,                  /* Tablespace */
2740                                  dba,                   /* Owner */
2741                                  false,                 /* with oids */
2742                                  "DATABASE",    /* Desc */
2743                                  SECTION_PRE_DATA,      /* Section */
2744                                  creaQry->data, /* Create */
2745                                  delQry->data,  /* Del */
2746                                  NULL,                  /* Copy */
2747                                  NULL,                  /* Deps */
2748                                  0,                             /* # Deps */
2749                                  NULL,                  /* Dumper */
2750                                  NULL);                 /* Dumper Arg */
2751
2752         /* Compute correct tag for archive entry */
2753         appendPQExpBuffer(labelq, "DATABASE %s", qdatname);
2754
2755         /* Dump DB comment if any */
2756         if (fout->remoteVersion >= 80200)
2757         {
2758                 /*
2759                  * 8.2 and up keep comments on shared objects in a shared table, so we
2760                  * cannot use the dumpComment() code used for other database objects.
2761                  * Be careful that the ArchiveEntry parameters match that function.
2762                  */
2763                 char       *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2764
2765                 if (comment && *comment && !dopt->no_comments)
2766                 {
2767                         resetPQExpBuffer(dbQry);
2768
2769                         /*
2770                          * Generates warning when loaded into a differently-named
2771                          * database.
2772                          */
2773                         appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", qdatname);
2774                         appendStringLiteralAH(dbQry, comment, fout);
2775                         appendPQExpBufferStr(dbQry, ";\n");
2776
2777                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2778                                                  labelq->data, NULL, NULL, dba,
2779                                                  false, "COMMENT", SECTION_NONE,
2780                                                  dbQry->data, "", NULL,
2781                                                  &(dbDumpId), 1,
2782                                                  NULL, NULL);
2783                 }
2784         }
2785         else
2786         {
2787                 dumpComment(fout, "DATABASE", qdatname, NULL, dba,
2788                                         dbCatId, 0, dbDumpId);
2789         }
2790
2791         /* Dump DB security label, if enabled */
2792         if (!dopt->no_security_labels && fout->remoteVersion >= 90200)
2793         {
2794                 PGresult   *shres;
2795                 PQExpBuffer seclabelQry;
2796
2797                 seclabelQry = createPQExpBuffer();
2798
2799                 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2800                 shres = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2801                 resetPQExpBuffer(seclabelQry);
2802                 emitShSecLabels(conn, shres, seclabelQry, "DATABASE", datname);
2803                 if (seclabelQry->len > 0)
2804                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2805                                                  labelq->data, NULL, NULL, dba,
2806                                                  false, "SECURITY LABEL", SECTION_NONE,
2807                                                  seclabelQry->data, "", NULL,
2808                                                  &(dbDumpId), 1,
2809                                                  NULL, NULL);
2810                 destroyPQExpBuffer(seclabelQry);
2811                 PQclear(shres);
2812         }
2813
2814         /*
2815          * Dump ACL if any.  Note that we do not support initial privileges
2816          * (pg_init_privs) on databases.
2817          */
2818         dumpACL(fout, dbCatId, dbDumpId, "DATABASE",
2819                         qdatname, NULL, NULL,
2820                         dba, datacl, rdatacl, "", "");
2821
2822         /*
2823          * Now construct a DATABASE PROPERTIES archive entry to restore any
2824          * non-default database-level properties.  (The reason this must be
2825          * separate is that we cannot put any additional commands into the TOC
2826          * entry that has CREATE DATABASE.  pg_restore would execute such a group
2827          * in an implicit transaction block, and the backend won't allow CREATE
2828          * DATABASE in that context.)
2829          */
2830         resetPQExpBuffer(creaQry);
2831         resetPQExpBuffer(delQry);
2832
2833         if (strlen(datconnlimit) > 0 && strcmp(datconnlimit, "-1") != 0)
2834                 appendPQExpBuffer(creaQry, "ALTER DATABASE %s CONNECTION LIMIT = %s;\n",
2835                                                   qdatname, datconnlimit);
2836
2837         if (strcmp(datistemplate, "t") == 0)
2838         {
2839                 appendPQExpBuffer(creaQry, "ALTER DATABASE %s IS_TEMPLATE = true;\n",
2840                                                   qdatname);
2841
2842                 /*
2843                  * The backend won't accept DROP DATABASE on a template database.  We
2844                  * can deal with that by removing the template marking before the DROP
2845                  * gets issued.  We'd prefer to use ALTER DATABASE IF EXISTS here, but
2846                  * since no such command is currently supported, fake it with a direct
2847                  * UPDATE on pg_database.
2848                  */
2849                 appendPQExpBufferStr(delQry, "UPDATE pg_catalog.pg_database "
2850                                                          "SET datistemplate = false WHERE datname = ");
2851                 appendStringLiteralAH(delQry, datname, fout);
2852                 appendPQExpBufferStr(delQry, ";\n");
2853         }
2854
2855         /* Add database-specific SET options */
2856         dumpDatabaseConfig(fout, creaQry, datname, dbCatId.oid);
2857
2858         /*
2859          * We stick this binary-upgrade query into the DATABASE PROPERTIES archive
2860          * entry, too, for lack of a better place.
2861          */
2862         if (dopt->binary_upgrade)
2863         {
2864                 appendPQExpBufferStr(creaQry, "\n-- For binary upgrade, set datfrozenxid and datminmxid.\n");
2865                 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
2866                                                   "SET datfrozenxid = '%u', datminmxid = '%u'\n"
2867                                                   "WHERE datname = ",
2868                                                   frozenxid, minmxid);
2869                 appendStringLiteralAH(creaQry, datname, fout);
2870                 appendPQExpBufferStr(creaQry, ";\n");
2871         }
2872
2873         if (creaQry->len > 0)
2874                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2875                                          datname, NULL, NULL, dba,
2876                                          false, "DATABASE PROPERTIES", SECTION_PRE_DATA,
2877                                          creaQry->data, delQry->data, NULL,
2878                                          &(dbDumpId), 1,
2879                                          NULL, NULL);
2880
2881         /*
2882          * pg_largeobject and pg_largeobject_metadata come from the old system
2883          * intact, so set their relfrozenxids and relminmxids.
2884          */
2885         if (dopt->binary_upgrade)
2886         {
2887                 PGresult   *lo_res;
2888                 PQExpBuffer loFrozenQry = createPQExpBuffer();
2889                 PQExpBuffer loOutQry = createPQExpBuffer();
2890                 int                     i_relfrozenxid,
2891                                         i_relminmxid;
2892
2893                 /*
2894                  * pg_largeobject
2895                  */
2896                 if (fout->remoteVersion >= 90300)
2897                         appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
2898                                                           "FROM pg_catalog.pg_class\n"
2899                                                           "WHERE oid = %u;\n",
2900                                                           LargeObjectRelationId);
2901                 else
2902                         appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
2903                                                           "FROM pg_catalog.pg_class\n"
2904                                                           "WHERE oid = %u;\n",
2905                                                           LargeObjectRelationId);
2906
2907                 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2908
2909                 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2910                 i_relminmxid = PQfnumber(lo_res, "relminmxid");
2911
2912                 appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject relfrozenxid and relminmxid\n");
2913                 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2914                                                   "SET relfrozenxid = '%u', relminmxid = '%u'\n"
2915                                                   "WHERE oid = %u;\n",
2916                                                   atooid(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2917                                                   atooid(PQgetvalue(lo_res, 0, i_relminmxid)),
2918                                                   LargeObjectRelationId);
2919                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2920                                          "pg_largeobject", NULL, NULL, "",
2921                                          false, "pg_largeobject", SECTION_PRE_DATA,
2922                                          loOutQry->data, "", NULL,
2923                                          NULL, 0,
2924                                          NULL, NULL);
2925
2926                 PQclear(lo_res);
2927
2928                 /*
2929                  * pg_largeobject_metadata
2930                  */
2931                 if (fout->remoteVersion >= 90000)
2932                 {
2933                         resetPQExpBuffer(loFrozenQry);
2934                         resetPQExpBuffer(loOutQry);
2935
2936                         if (fout->remoteVersion >= 90300)
2937                                 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
2938                                                                   "FROM pg_catalog.pg_class\n"
2939                                                                   "WHERE oid = %u;\n",
2940                                                                   LargeObjectMetadataRelationId);
2941                         else
2942                                 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
2943                                                                   "FROM pg_catalog.pg_class\n"
2944                                                                   "WHERE oid = %u;\n",
2945                                                                   LargeObjectMetadataRelationId);
2946
2947                         lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2948
2949                         i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2950                         i_relminmxid = PQfnumber(lo_res, "relminmxid");
2951
2952                         appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata relfrozenxid and relminmxid\n");
2953                         appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2954                                                           "SET relfrozenxid = '%u', relminmxid = '%u'\n"
2955                                                           "WHERE oid = %u;\n",
2956                                                           atooid(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2957                                                           atooid(PQgetvalue(lo_res, 0, i_relminmxid)),
2958                                                           LargeObjectMetadataRelationId);
2959                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2960                                                  "pg_largeobject_metadata", NULL, NULL, "",
2961                                                  false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2962                                                  loOutQry->data, "", NULL,
2963                                                  NULL, 0,
2964                                                  NULL, NULL);
2965
2966                         PQclear(lo_res);
2967                 }
2968
2969                 destroyPQExpBuffer(loFrozenQry);
2970                 destroyPQExpBuffer(loOutQry);
2971         }
2972
2973         PQclear(res);
2974
2975         free(qdatname);
2976         destroyPQExpBuffer(dbQry);
2977         destroyPQExpBuffer(delQry);
2978         destroyPQExpBuffer(creaQry);
2979         destroyPQExpBuffer(labelq);
2980 }
2981
2982 /*
2983  * Collect any database-specific or role-and-database-specific SET options
2984  * for this database, and append them to outbuf.
2985  */
2986 static void
2987 dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
2988                                    const char *dbname, Oid dboid)
2989 {
2990         PGconn     *conn = GetConnection(AH);
2991         PQExpBuffer buf = createPQExpBuffer();
2992         PGresult   *res;
2993         int                     count = 1;
2994
2995         /*
2996          * First collect database-specific options.  Pre-8.4 server versions lack
2997          * unnest(), so we do this the hard way by querying once per subscript.
2998          */
2999         for (;;)
3000         {
3001                 if (AH->remoteVersion >= 90000)
3002                         printfPQExpBuffer(buf, "SELECT setconfig[%d] FROM pg_db_role_setting "
3003                                                           "WHERE setrole = 0 AND setdatabase = '%u'::oid",
3004                                                           count, dboid);
3005                 else
3006                         printfPQExpBuffer(buf, "SELECT datconfig[%d] FROM pg_database WHERE oid = '%u'::oid", count, dboid);
3007
3008                 res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3009
3010                 if (PQntuples(res) == 1 &&
3011                         !PQgetisnull(res, 0, 0))
3012                 {
3013                         makeAlterConfigCommand(conn, PQgetvalue(res, 0, 0),
3014                                                                    "DATABASE", dbname, NULL, NULL,
3015                                                                    outbuf);
3016                         PQclear(res);
3017                         count++;
3018                 }
3019                 else
3020                 {
3021                         PQclear(res);
3022                         break;
3023                 }
3024         }
3025
3026         /* Now look for role-and-database-specific options */
3027         if (AH->remoteVersion >= 90000)
3028         {
3029                 /* Here we can assume we have unnest() */
3030                 printfPQExpBuffer(buf, "SELECT rolname, unnest(setconfig) "
3031                                                   "FROM pg_db_role_setting s, pg_roles r "
3032                                                   "WHERE setrole = r.oid AND setdatabase = '%u'::oid",
3033                                                   dboid);
3034
3035                 res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3036
3037                 if (PQntuples(res) > 0)
3038                 {
3039                         int                     i;
3040
3041                         for (i = 0; i < PQntuples(res); i++)
3042                                 makeAlterConfigCommand(conn, PQgetvalue(res, i, 1),
3043                                                                            "ROLE", PQgetvalue(res, i, 0),
3044                                                                            "DATABASE", dbname,
3045                                                                            outbuf);
3046                 }
3047
3048                 PQclear(res);
3049         }
3050
3051         destroyPQExpBuffer(buf);
3052 }
3053
3054 /*
3055  * dumpEncoding: put the correct encoding into the archive
3056  */
3057 static void
3058 dumpEncoding(Archive *AH)
3059 {
3060         const char *encname = pg_encoding_to_char(AH->encoding);
3061         PQExpBuffer qry = createPQExpBuffer();
3062
3063         if (g_verbose)
3064                 write_msg(NULL, "saving encoding = %s\n", encname);
3065
3066         appendPQExpBufferStr(qry, "SET client_encoding = ");
3067         appendStringLiteralAH(qry, encname, AH);
3068         appendPQExpBufferStr(qry, ";\n");
3069
3070         ArchiveEntry(AH, nilCatalogId, createDumpId(),
3071                                  "ENCODING", NULL, NULL, "",
3072                                  false, "ENCODING", SECTION_PRE_DATA,
3073                                  qry->data, "", NULL,
3074                                  NULL, 0,
3075                                  NULL, NULL);
3076
3077         destroyPQExpBuffer(qry);
3078 }
3079
3080
3081 /*
3082  * dumpStdStrings: put the correct escape string behavior into the archive
3083  */
3084 static void
3085 dumpStdStrings(Archive *AH)
3086 {
3087         const char *stdstrings = AH->std_strings ? "on" : "off";
3088         PQExpBuffer qry = createPQExpBuffer();
3089
3090         if (g_verbose)
3091                 write_msg(NULL, "saving standard_conforming_strings = %s\n",
3092                                   stdstrings);
3093
3094         appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
3095                                           stdstrings);
3096
3097         ArchiveEntry(AH, nilCatalogId, createDumpId(),
3098                                  "STDSTRINGS", NULL, NULL, "",
3099                                  false, "STDSTRINGS", SECTION_PRE_DATA,
3100                                  qry->data, "", NULL,
3101                                  NULL, 0,
3102                                  NULL, NULL);
3103
3104         destroyPQExpBuffer(qry);
3105 }
3106
3107 /*
3108  * dumpSearchPath: record the active search_path in the archive
3109  */
3110 static void
3111 dumpSearchPath(Archive *AH)
3112 {
3113         PQExpBuffer qry = createPQExpBuffer();
3114         PQExpBuffer path = createPQExpBuffer();
3115         PGresult   *res;
3116         char      **schemanames = NULL;
3117         int                     nschemanames = 0;
3118         int                     i;
3119
3120         /*
3121          * We use the result of current_schemas(), not the search_path GUC,
3122          * because that might contain wildcards such as "$user", which won't
3123          * necessarily have the same value during restore.  Also, this way avoids
3124          * listing schemas that may appear in search_path but not actually exist,
3125          * which seems like a prudent exclusion.
3126          */
3127         res = ExecuteSqlQueryForSingleRow(AH,
3128                                                                           "SELECT pg_catalog.current_schemas(false)");
3129
3130         if (!parsePGArray(PQgetvalue(res, 0, 0), &schemanames, &nschemanames))
3131                 exit_horribly(NULL, "could not parse result of current_schemas()\n");
3132
3133         /*
3134          * We use set_config(), not a simple "SET search_path" command, because
3135          * the latter has less-clean behavior if the search path is empty.  While
3136          * that's likely to get fixed at some point, it seems like a good idea to
3137          * be as backwards-compatible as possible in what we put into archives.
3138          */
3139         for (i = 0; i < nschemanames; i++)
3140         {
3141                 if (i > 0)
3142                         appendPQExpBufferStr(path, ", ");
3143                 appendPQExpBufferStr(path, fmtId(schemanames[i]));
3144         }
3145
3146         appendPQExpBufferStr(qry, "SELECT pg_catalog.set_config('search_path', ");
3147         appendStringLiteralAH(qry, path->data, AH);
3148         appendPQExpBufferStr(qry, ", false);\n");
3149
3150         if (g_verbose)
3151                 write_msg(NULL, "saving search_path = %s\n", path->data);
3152
3153         ArchiveEntry(AH, nilCatalogId, createDumpId(),
3154                                  "SEARCHPATH", NULL, NULL, "",
3155                                  false, "SEARCHPATH", SECTION_PRE_DATA,
3156                                  qry->data, "", NULL,
3157                                  NULL, 0,
3158                                  NULL, NULL);
3159
3160         /* Also save it in AH->searchpath, in case we're doing plain text dump */
3161         AH->searchpath = pg_strdup(qry->data);
3162
3163         if (schemanames)
3164                 free(schemanames);
3165         PQclear(res);
3166         destroyPQExpBuffer(qry);
3167         destroyPQExpBuffer(path);
3168 }
3169
3170
3171 /*
3172  * getBlobs:
3173  *      Collect schema-level data about large objects
3174  */
3175 static void
3176 getBlobs(Archive *fout)
3177 {
3178         DumpOptions *dopt = fout->dopt;
3179         PQExpBuffer blobQry = createPQExpBuffer();
3180         BlobInfo   *binfo;
3181         DumpableObject *bdata;
3182         PGresult   *res;
3183         int                     ntups;
3184         int                     i;
3185         int                     i_oid;
3186         int                     i_lomowner;
3187         int                     i_lomacl;
3188         int                     i_rlomacl;
3189         int                     i_initlomacl;
3190         int                     i_initrlomacl;
3191
3192         /* Verbose message */
3193         if (g_verbose)
3194                 write_msg(NULL, "reading large objects\n");
3195
3196         /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
3197         if (fout->remoteVersion >= 90600)
3198         {
3199                 PQExpBuffer acl_subquery = createPQExpBuffer();
3200                 PQExpBuffer racl_subquery = createPQExpBuffer();
3201                 PQExpBuffer init_acl_subquery = createPQExpBuffer();
3202                 PQExpBuffer init_racl_subquery = createPQExpBuffer();
3203
3204                 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
3205                                                 init_racl_subquery, "l.lomacl", "l.lomowner", "'L'",
3206                                                 dopt->binary_upgrade);
3207
3208                 appendPQExpBuffer(blobQry,
3209                                                   "SELECT l.oid, (%s l.lomowner) AS rolname, "
3210                                                   "%s AS lomacl, "
3211                                                   "%s AS rlomacl, "
3212                                                   "%s AS initlomacl, "
3213                                                   "%s AS initrlomacl "
3214                                                   "FROM pg_largeobject_metadata l "
3215                                                   "LEFT JOIN pg_init_privs pip ON "
3216                                                   "(l.oid = pip.objoid "
3217                                                   "AND pip.classoid = 'pg_largeobject'::regclass "
3218                                                   "AND pip.objsubid = 0) ",
3219                                                   username_subquery,
3220                                                   acl_subquery->data,
3221                                                   racl_subquery->data,
3222                                                   init_acl_subquery->data,
3223                                                   init_racl_subquery->data);
3224
3225                 destroyPQExpBuffer(acl_subquery);
3226                 destroyPQExpBuffer(racl_subquery);
3227                 destroyPQExpBuffer(init_acl_subquery);
3228                 destroyPQExpBuffer(init_racl_subquery);
3229         }
3230         else if (fout->remoteVersion >= 90000)
3231                 appendPQExpBuffer(blobQry,
3232                                                   "SELECT oid, (%s lomowner) AS rolname, lomacl, "
3233                                                   "NULL AS rlomacl, NULL AS initlomacl, "
3234                                                   "NULL AS initrlomacl "
3235                                                   " FROM pg_largeobject_metadata",
3236                                                   username_subquery);
3237         else
3238                 appendPQExpBufferStr(blobQry,
3239                                                          "SELECT DISTINCT loid AS oid, "
3240                                                          "NULL::name AS rolname, NULL::oid AS lomacl, "
3241                                                          "NULL::oid AS rlomacl, NULL::oid AS initlomacl, "
3242                                                          "NULL::oid AS initrlomacl "
3243                                                          " FROM pg_largeobject");
3244
3245         res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
3246
3247         i_oid = PQfnumber(res, "oid");
3248         i_lomowner = PQfnumber(res, "rolname");
3249         i_lomacl = PQfnumber(res, "lomacl");
3250         i_rlomacl = PQfnumber(res, "rlomacl");
3251         i_initlomacl = PQfnumber(res, "initlomacl");
3252         i_initrlomacl = PQfnumber(res, "initrlomacl");
3253
3254         ntups = PQntuples(res);
3255
3256         /*
3257          * Each large object has its own BLOB archive entry.
3258          */
3259         binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
3260
3261         for (i = 0; i < ntups; i++)
3262         {
3263                 binfo[i].dobj.objType = DO_BLOB;
3264                 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
3265                 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3266                 AssignDumpId(&binfo[i].dobj);
3267
3268                 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oid));
3269                 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_lomowner));
3270                 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, i_lomacl));
3271                 binfo[i].rblobacl = pg_strdup(PQgetvalue(res, i, i_rlomacl));
3272                 binfo[i].initblobacl = pg_strdup(PQgetvalue(res, i, i_initlomacl));
3273                 binfo[i].initrblobacl = pg_strdup(PQgetvalue(res, i, i_initrlomacl));
3274
3275                 if (PQgetisnull(res, i, i_lomacl) &&
3276                         PQgetisnull(res, i, i_rlomacl) &&
3277                         PQgetisnull(res, i, i_initlomacl) &&
3278                         PQgetisnull(res, i, i_initrlomacl))
3279                         binfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
3280
3281                 /*
3282                  * In binary-upgrade mode for blobs, we do *not* dump out the data or
3283                  * the ACLs, should any exist.  The data and ACL (if any) will be
3284                  * copied by pg_upgrade, which simply copies the pg_largeobject and
3285                  * pg_largeobject_metadata tables.
3286                  *
3287                  * We *do* dump out the definition of the blob because we need that to
3288                  * make the restoration of the comments, and anything else, work since
3289                  * pg_upgrade copies the files behind pg_largeobject and
3290                  * pg_largeobject_metadata after the dump is restored.
3291                  */
3292                 if (dopt->binary_upgrade)
3293                         binfo[i].dobj.dump &= ~(DUMP_COMPONENT_DATA | DUMP_COMPONENT_ACL);
3294         }
3295
3296         /*
3297          * If we have any large objects, a "BLOBS" archive entry is needed. This
3298          * is just a placeholder for sorting; it carries no data now.
3299          */
3300         if (ntups > 0)
3301         {
3302                 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
3303                 bdata->objType = DO_BLOB_DATA;
3304                 bdata->catId = nilCatalogId;
3305                 AssignDumpId(bdata);
3306                 bdata->name = pg_strdup("BLOBS");
3307         }
3308
3309         PQclear(res);
3310         destroyPQExpBuffer(blobQry);
3311 }
3312
3313 /*
3314  * dumpBlob
3315  *
3316  * dump the definition (metadata) of the given large object
3317  */
3318 static void
3319 dumpBlob(Archive *fout, BlobInfo *binfo)
3320 {
3321         PQExpBuffer cquery = createPQExpBuffer();
3322         PQExpBuffer dquery = createPQExpBuffer();
3323
3324         appendPQExpBuffer(cquery,
3325                                           "SELECT pg_catalog.lo_create('%s');\n",
3326                                           binfo->dobj.name);
3327
3328         appendPQExpBuffer(dquery,
3329                                           "SELECT pg_catalog.lo_unlink('%s');\n",
3330                                           binfo->dobj.name);
3331
3332         if (binfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
3333                 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
3334                                          binfo->dobj.name,
3335                                          NULL, NULL,
3336                                          binfo->rolname, false,
3337                                          "BLOB", SECTION_PRE_DATA,
3338                                          cquery->data, dquery->data, NULL,
3339                                          NULL, 0,
3340                                          NULL, NULL);
3341
3342         /* Dump comment if any */
3343         if (binfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3344                 dumpComment(fout, "LARGE OBJECT", binfo->dobj.name,
3345                                         NULL, binfo->rolname,
3346                                         binfo->dobj.catId, 0, binfo->dobj.dumpId);
3347
3348         /* Dump security label if any */
3349         if (binfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3350                 dumpSecLabel(fout, "LARGE OBJECT", binfo->dobj.name,
3351                                          NULL, binfo->rolname,
3352                                          binfo->dobj.catId, 0, binfo->dobj.dumpId);
3353
3354         /* Dump ACL if any */
3355         if (binfo->blobacl && (binfo->dobj.dump & DUMP_COMPONENT_ACL))
3356                 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
3357                                 binfo->dobj.name, NULL,
3358                                 NULL, binfo->rolname, binfo->blobacl, binfo->rblobacl,
3359                                 binfo->initblobacl, binfo->initrblobacl);
3360
3361         destroyPQExpBuffer(cquery);
3362         destroyPQExpBuffer(dquery);
3363 }
3364
3365 /*
3366  * dumpBlobs:
3367  *      dump the data contents of all large objects
3368  */
3369 static int
3370 dumpBlobs(Archive *fout, void *arg)
3371 {
3372         const char *blobQry;
3373         const char *blobFetchQry;
3374         PGconn     *conn = GetConnection(fout);
3375         PGresult   *res;
3376         char            buf[LOBBUFSIZE];
3377         int                     ntups;
3378         int                     i;
3379         int                     cnt;
3380
3381         if (g_verbose)
3382                 write_msg(NULL, "saving large objects\n");
3383
3384         /*
3385          * Currently, we re-fetch all BLOB OIDs using a cursor.  Consider scanning
3386          * the already-in-memory dumpable objects instead...
3387          */
3388         if (fout->remoteVersion >= 90000)
3389                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
3390         else
3391                 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
3392
3393         ExecuteSqlStatement(fout, blobQry);
3394
3395         /* Command to fetch from cursor */
3396         blobFetchQry = "FETCH 1000 IN bloboid";
3397
3398         do
3399         {
3400                 /* Do a fetch */
3401                 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
3402
3403                 /* Process the tuples, if any */
3404                 ntups = PQntuples(res);
3405                 for (i = 0; i < ntups; i++)
3406                 {
3407                         Oid                     blobOid;
3408                         int                     loFd;
3409
3410                         blobOid = atooid(PQgetvalue(res, i, 0));
3411                         /* Open the BLOB */
3412                         loFd = lo_open(conn, blobOid, INV_READ);
3413                         if (loFd == -1)
3414                                 exit_horribly(NULL, "could not open large object %u: %s",
3415                                                           blobOid, PQerrorMessage(conn));
3416
3417                         StartBlob(fout, blobOid);
3418
3419                         /* Now read it in chunks, sending data to archive */
3420                         do
3421                         {
3422                                 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
3423                                 if (cnt < 0)
3424                                         exit_horribly(NULL, "error reading large object %u: %s",
3425                                                                   blobOid, PQerrorMessage(conn));
3426
3427                                 WriteData(fout, buf, cnt);
3428                         } while (cnt > 0);
3429
3430                         lo_close(conn, loFd);
3431
3432                         EndBlob(fout, blobOid);
3433                 }
3434
3435                 PQclear(res);
3436         } while (ntups > 0);
3437
3438         return 1;
3439 }
3440
3441 /*
3442  * getPolicies
3443  *        get information about policies on a dumpable table.
3444  */
3445 void
3446 getPolicies(Archive *fout, TableInfo tblinfo[], int numTables)
3447 {
3448         PQExpBuffer query;
3449         PGresult   *res;
3450         PolicyInfo *polinfo;
3451         int                     i_oid;
3452         int                     i_tableoid;
3453         int                     i_polname;
3454         int                     i_polcmd;
3455         int                     i_polpermissive;
3456         int                     i_polroles;
3457         int                     i_polqual;
3458         int                     i_polwithcheck;
3459         int                     i,
3460                                 j,
3461                                 ntups;
3462
3463         if (fout->remoteVersion < 90500)
3464                 return;
3465
3466         query = createPQExpBuffer();
3467
3468         for (i = 0; i < numTables; i++)
3469         {
3470                 TableInfo  *tbinfo = &tblinfo[i];
3471
3472                 /* Ignore row security on tables not to be dumped */
3473                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_POLICY))
3474                         continue;
3475
3476                 if (g_verbose)
3477                         write_msg(NULL, "reading row security enabled for table \"%s.%s\"\n",
3478                                           tbinfo->dobj.namespace->dobj.name,
3479                                           tbinfo->dobj.name);
3480
3481                 /*
3482                  * Get row security enabled information for the table. We represent
3483                  * RLS enabled on a table by creating PolicyInfo object with an empty
3484                  * policy.
3485                  */
3486                 if (tbinfo->rowsec)
3487                 {
3488                         /*
3489                          * Note: use tableoid 0 so that this object won't be mistaken for
3490                          * something that pg_depend entries apply to.
3491                          */
3492                         polinfo = pg_malloc(sizeof(PolicyInfo));
3493                         polinfo->dobj.objType = DO_POLICY;
3494                         polinfo->dobj.catId.tableoid = 0;
3495                         polinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
3496                         AssignDumpId(&polinfo->dobj);
3497                         polinfo->dobj.namespace = tbinfo->dobj.namespace;
3498                         polinfo->dobj.name = pg_strdup(tbinfo->dobj.name);
3499                         polinfo->poltable = tbinfo;
3500                         polinfo->polname = NULL;
3501                         polinfo->polcmd = '\0';
3502                         polinfo->polpermissive = 0;
3503                         polinfo->polroles = NULL;
3504                         polinfo->polqual = NULL;
3505                         polinfo->polwithcheck = NULL;
3506                 }
3507
3508                 if (g_verbose)
3509                         write_msg(NULL, "reading policies for table \"%s.%s\"\n",
3510                                           tbinfo->dobj.namespace->dobj.name,
3511                                           tbinfo->dobj.name);
3512
3513                 resetPQExpBuffer(query);
3514
3515                 /* Get the policies for the table. */
3516                 if (fout->remoteVersion >= 100000)
3517                         appendPQExpBuffer(query,
3518                                                           "SELECT oid, tableoid, pol.polname, pol.polcmd, pol.polpermissive, "
3519                                                           "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3520                                                           "   pg_catalog.array_to_string(ARRAY(SELECT pg_catalog.quote_ident(rolname) from pg_catalog.pg_roles WHERE oid = ANY(pol.polroles)), ', ') END AS polroles, "
3521                                                           "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3522                                                           "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3523                                                           "FROM pg_catalog.pg_policy pol "
3524                                                           "WHERE polrelid = '%u'",
3525                                                           tbinfo->dobj.catId.oid);
3526                 else
3527                         appendPQExpBuffer(query,
3528                                                           "SELECT oid, tableoid, pol.polname, pol.polcmd, 't' as polpermissive, "
3529                                                           "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3530                                                           "   pg_catalog.array_to_string(ARRAY(SELECT pg_catalog.quote_ident(rolname) from pg_catalog.pg_roles WHERE oid = ANY(pol.polroles)), ', ') END AS polroles, "
3531                                                           "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3532                                                           "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3533                                                           "FROM pg_catalog.pg_policy pol "
3534                                                           "WHERE polrelid = '%u'",
3535                                                           tbinfo->dobj.catId.oid);
3536                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3537
3538                 ntups = PQntuples(res);
3539
3540                 if (ntups == 0)
3541                 {
3542                         /*
3543                          * No explicit policies to handle (only the default-deny policy,
3544                          * which is handled as part of the table definition).  Clean up
3545                          * and return.
3546                          */
3547                         PQclear(res);
3548                         continue;
3549                 }
3550
3551                 i_oid = PQfnumber(res, "oid");
3552                 i_tableoid = PQfnumber(res, "tableoid");
3553                 i_polname = PQfnumber(res, "polname");
3554                 i_polcmd = PQfnumber(res, "polcmd");
3555                 i_polpermissive = PQfnumber(res, "polpermissive");
3556                 i_polroles = PQfnumber(res, "polroles");
3557                 i_polqual = PQfnumber(res, "polqual");
3558                 i_polwithcheck = PQfnumber(res, "polwithcheck");
3559
3560                 polinfo = pg_malloc(ntups * sizeof(PolicyInfo));
3561
3562                 for (j = 0; j < ntups; j++)
3563                 {
3564                         polinfo[j].dobj.objType = DO_POLICY;
3565                         polinfo[j].dobj.catId.tableoid =
3566                                 atooid(PQgetvalue(res, j, i_tableoid));
3567                         polinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3568                         AssignDumpId(&polinfo[j].dobj);
3569                         polinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3570                         polinfo[j].poltable = tbinfo;
3571                         polinfo[j].polname = pg_strdup(PQgetvalue(res, j, i_polname));
3572                         polinfo[j].dobj.name = pg_strdup(polinfo[j].polname);
3573
3574                         polinfo[j].polcmd = *(PQgetvalue(res, j, i_polcmd));
3575                         polinfo[j].polpermissive = *(PQgetvalue(res, j, i_polpermissive)) == 't';
3576
3577                         if (PQgetisnull(res, j, i_polroles))
3578                                 polinfo[j].polroles = NULL;
3579                         else
3580                                 polinfo[j].polroles = pg_strdup(PQgetvalue(res, j, i_polroles));
3581
3582                         if (PQgetisnull(res, j, i_polqual))
3583                                 polinfo[j].polqual = NULL;
3584                         else
3585                                 polinfo[j].polqual = pg_strdup(PQgetvalue(res, j, i_polqual));
3586
3587                         if (PQgetisnull(res, j, i_polwithcheck))
3588                                 polinfo[j].polwithcheck = NULL;
3589                         else
3590                                 polinfo[j].polwithcheck
3591                                         = pg_strdup(PQgetvalue(res, j, i_polwithcheck));
3592                 }
3593                 PQclear(res);
3594         }
3595         destroyPQExpBuffer(query);
3596 }
3597
3598 /*
3599  * dumpPolicy
3600  *        dump the definition of the given policy
3601  */
3602 static void
3603 dumpPolicy(Archive *fout, PolicyInfo *polinfo)
3604 {
3605         DumpOptions *dopt = fout->dopt;
3606         TableInfo  *tbinfo = polinfo->poltable;
3607         PQExpBuffer query;
3608         PQExpBuffer delqry;
3609         const char *cmd;
3610         char       *tag;
3611
3612         if (dopt->dataOnly)
3613                 return;
3614
3615         /*
3616          * If polname is NULL, then this record is just indicating that ROW LEVEL
3617          * SECURITY is enabled for the table. Dump as ALTER TABLE <table> ENABLE
3618          * ROW LEVEL SECURITY.
3619          */
3620         if (polinfo->polname == NULL)
3621         {
3622                 query = createPQExpBuffer();
3623
3624                 appendPQExpBuffer(query, "ALTER TABLE %s ENABLE ROW LEVEL SECURITY;",
3625                                                   fmtQualifiedDumpable(polinfo));
3626
3627                 if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3628                         ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3629                                                  polinfo->dobj.name,
3630                                                  polinfo->dobj.namespace->dobj.name,
3631                                                  NULL,
3632                                                  tbinfo->rolname, false,
3633                                                  "ROW SECURITY", SECTION_POST_DATA,
3634                                                  query->data, "", NULL,
3635                                                  NULL, 0,
3636                                                  NULL, NULL);
3637
3638                 destroyPQExpBuffer(query);
3639                 return;
3640         }
3641
3642         if (polinfo->polcmd == '*')
3643                 cmd = "";
3644         else if (polinfo->polcmd == 'r')
3645                 cmd = " FOR SELECT";
3646         else if (polinfo->polcmd == 'a')
3647                 cmd = " FOR INSERT";
3648         else if (polinfo->polcmd == 'w')
3649                 cmd = " FOR UPDATE";
3650         else if (polinfo->polcmd == 'd')
3651                 cmd = " FOR DELETE";
3652         else
3653         {
3654                 write_msg(NULL, "unexpected policy command type: %c\n",
3655                                   polinfo->polcmd);
3656                 exit_nicely(1);
3657         }
3658
3659         query = createPQExpBuffer();
3660         delqry = createPQExpBuffer();
3661
3662         appendPQExpBuffer(query, "CREATE POLICY %s", fmtId(polinfo->polname));
3663
3664         appendPQExpBuffer(query, " ON %s%s%s", fmtQualifiedDumpable(tbinfo),
3665                                           !polinfo->polpermissive ? " AS RESTRICTIVE" : "", cmd);
3666
3667         if (polinfo->polroles != NULL)
3668                 appendPQExpBuffer(query, " TO %s", polinfo->polroles);
3669
3670         if (polinfo->polqual != NULL)
3671                 appendPQExpBuffer(query, " USING (%s)", polinfo->polqual);
3672
3673         if (polinfo->polwithcheck != NULL)
3674                 appendPQExpBuffer(query, " WITH CHECK (%s)", polinfo->polwithcheck);
3675
3676         appendPQExpBuffer(query, ";\n");
3677
3678         appendPQExpBuffer(delqry, "DROP POLICY %s", fmtId(polinfo->polname));
3679         appendPQExpBuffer(delqry, " ON %s;\n", fmtQualifiedDumpable(tbinfo));
3680
3681         tag = psprintf("%s %s", tbinfo->dobj.name, polinfo->dobj.name);
3682
3683         if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3684                 ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3685                                          tag,
3686                                          polinfo->dobj.namespace->dobj.name,
3687                                          NULL,
3688                                          tbinfo->rolname, false,
3689                                          "POLICY", SECTION_POST_DATA,
3690                                          query->data, delqry->data, NULL,
3691                                          NULL, 0,
3692                                          NULL, NULL);
3693
3694         free(tag);
3695         destroyPQExpBuffer(query);
3696         destroyPQExpBuffer(delqry);
3697 }
3698
3699 /*
3700  * getPublications
3701  *        get information about publications
3702  */
3703 void
3704 getPublications(Archive *fout)
3705 {
3706         DumpOptions *dopt = fout->dopt;
3707         PQExpBuffer query;
3708         PGresult   *res;
3709         PublicationInfo *pubinfo;
3710         int                     i_tableoid;
3711         int                     i_oid;
3712         int                     i_pubname;
3713         int                     i_rolname;
3714         int                     i_puballtables;
3715         int                     i_pubinsert;
3716         int                     i_pubupdate;
3717         int                     i_pubdelete;
3718         int                     i_pubtruncate;
3719         int                     i,
3720                                 ntups;
3721
3722         if (dopt->no_publications || fout->remoteVersion < 100000)
3723                 return;
3724
3725         query = createPQExpBuffer();
3726
3727         resetPQExpBuffer(query);
3728
3729         /* Get the publications. */
3730         if (fout->remoteVersion >= 110000)
3731                 appendPQExpBuffer(query,
3732                                                   "SELECT p.tableoid, p.oid, p.pubname, "
3733                                                   "(%s p.pubowner) AS rolname, "
3734                                                   "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete, p.pubtruncate "
3735                                                   "FROM pg_publication p",
3736                                                   username_subquery);
3737         else
3738                 appendPQExpBuffer(query,
3739                                                   "SELECT p.tableoid, p.oid, p.pubname, "
3740                                                   "(%s p.pubowner) AS rolname, "
3741                                                   "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete, false AS pubtruncate "
3742                                                   "FROM pg_publication p",
3743                                                   username_subquery);
3744
3745         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3746
3747         ntups = PQntuples(res);
3748
3749         i_tableoid = PQfnumber(res, "tableoid");
3750         i_oid = PQfnumber(res, "oid");
3751         i_pubname = PQfnumber(res, "pubname");
3752         i_rolname = PQfnumber(res, "rolname");
3753         i_puballtables = PQfnumber(res, "puballtables");
3754         i_pubinsert = PQfnumber(res, "pubinsert");
3755         i_pubupdate = PQfnumber(res, "pubupdate");
3756         i_pubdelete = PQfnumber(res, "pubdelete");
3757         i_pubtruncate = PQfnumber(res, "pubtruncate");
3758
3759         pubinfo = pg_malloc(ntups * sizeof(PublicationInfo));
3760
3761         for (i = 0; i < ntups; i++)
3762         {
3763                 pubinfo[i].dobj.objType = DO_PUBLICATION;
3764                 pubinfo[i].dobj.catId.tableoid =
3765                         atooid(PQgetvalue(res, i, i_tableoid));
3766                 pubinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3767                 AssignDumpId(&pubinfo[i].dobj);
3768                 pubinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_pubname));
3769                 pubinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3770                 pubinfo[i].puballtables =
3771                         (strcmp(PQgetvalue(res, i, i_puballtables), "t") == 0);
3772                 pubinfo[i].pubinsert =
3773                         (strcmp(PQgetvalue(res, i, i_pubinsert), "t") == 0);
3774                 pubinfo[i].pubupdate =
3775                         (strcmp(PQgetvalue(res, i, i_pubupdate), "t") == 0);
3776                 pubinfo[i].pubdelete =
3777                         (strcmp(PQgetvalue(res, i, i_pubdelete), "t") == 0);
3778                 pubinfo[i].pubtruncate =
3779                         (strcmp(PQgetvalue(res, i, i_pubtruncate), "t") == 0);
3780
3781                 if (strlen(pubinfo[i].rolname) == 0)
3782                         write_msg(NULL, "WARNING: owner of publication \"%s\" appears to be invalid\n",
3783                                           pubinfo[i].dobj.name);
3784
3785                 /* Decide whether we want to dump it */
3786                 selectDumpableObject(&(pubinfo[i].dobj), fout);
3787         }
3788         PQclear(res);
3789
3790         destroyPQExpBuffer(query);
3791 }
3792
3793 /*
3794  * dumpPublication
3795  *        dump the definition of the given publication
3796  */
3797 static void
3798 dumpPublication(Archive *fout, PublicationInfo *pubinfo)
3799 {
3800         PQExpBuffer delq;
3801         PQExpBuffer query;
3802         char       *qpubname;
3803         bool            first = true;
3804
3805         if (!(pubinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3806                 return;
3807
3808         delq = createPQExpBuffer();
3809         query = createPQExpBuffer();
3810
3811         qpubname = pg_strdup(fmtId(pubinfo->dobj.name));
3812
3813         appendPQExpBuffer(delq, "DROP PUBLICATION %s;\n",
3814                                           qpubname);
3815
3816         appendPQExpBuffer(query, "CREATE PUBLICATION %s",
3817                                           qpubname);
3818
3819         if (pubinfo->puballtables)
3820                 appendPQExpBufferStr(query, " FOR ALL TABLES");
3821
3822         appendPQExpBufferStr(query, " WITH (publish = '");
3823         if (pubinfo->pubinsert)
3824         {
3825                 appendPQExpBufferStr(query, "insert");
3826                 first = false;
3827         }
3828
3829         if (pubinfo->pubupdate)
3830         {
3831                 if (!first)
3832                         appendPQExpBufferStr(query, ", ");
3833
3834                 appendPQExpBufferStr(query, "update");
3835                 first = false;
3836         }
3837
3838         if (pubinfo->pubdelete)
3839         {
3840                 if (!first)
3841                         appendPQExpBufferStr(query, ", ");
3842
3843                 appendPQExpBufferStr(query, "delete");
3844                 first = false;
3845         }
3846
3847         if (pubinfo->pubtruncate)
3848         {
3849                 if (!first)
3850                         appendPQExpBufferStr(query, ", ");
3851
3852                 appendPQExpBufferStr(query, "truncate");
3853                 first = false;
3854         }
3855
3856         appendPQExpBufferStr(query, "');\n");
3857
3858         ArchiveEntry(fout, pubinfo->dobj.catId, pubinfo->dobj.dumpId,
3859                                  pubinfo->dobj.name,
3860                                  NULL,
3861                                  NULL,
3862                                  pubinfo->rolname, false,
3863                                  "PUBLICATION", SECTION_POST_DATA,
3864                                  query->data, delq->data, NULL,
3865                                  NULL, 0,
3866                                  NULL, NULL);
3867
3868         if (pubinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3869                 dumpComment(fout, "PUBLICATION", qpubname,
3870                                         NULL, pubinfo->rolname,
3871                                         pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3872
3873         if (pubinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3874                 dumpSecLabel(fout, "PUBLICATION", qpubname,
3875                                          NULL, pubinfo->rolname,
3876                                          pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3877
3878         destroyPQExpBuffer(delq);
3879         destroyPQExpBuffer(query);
3880         free(qpubname);
3881 }
3882
3883 /*
3884  * getPublicationTables
3885  *        get information about publication membership for dumpable tables.
3886  */
3887 void
3888 getPublicationTables(Archive *fout, TableInfo tblinfo[], int numTables)
3889 {
3890         PQExpBuffer query;
3891         PGresult   *res;
3892         PublicationRelInfo *pubrinfo;
3893         int                     i_tableoid;
3894         int                     i_oid;
3895         int                     i_pubname;
3896         int                     i,
3897                                 j,
3898                                 ntups;
3899
3900         if (fout->remoteVersion < 100000)
3901                 return;
3902
3903         query = createPQExpBuffer();
3904
3905         for (i = 0; i < numTables; i++)
3906         {
3907                 TableInfo  *tbinfo = &tblinfo[i];
3908
3909                 /* Only plain tables can be aded to publications. */
3910                 if (tbinfo->relkind != RELKIND_RELATION)
3911                         continue;
3912
3913                 /*
3914                  * Ignore publication membership of tables whose definitions are not
3915                  * to be dumped.
3916                  */
3917                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3918                         continue;
3919
3920                 if (g_verbose)
3921                         write_msg(NULL, "reading publication membership for table \"%s.%s\"\n",
3922                                           tbinfo->dobj.namespace->dobj.name,
3923                                           tbinfo->dobj.name);
3924
3925                 resetPQExpBuffer(query);
3926
3927                 /* Get the publication membership for the table. */
3928                 appendPQExpBuffer(query,
3929                                                   "SELECT pr.tableoid, pr.oid, p.pubname "
3930                                                   "FROM pg_publication_rel pr, pg_publication p "
3931                                                   "WHERE pr.prrelid = '%u'"
3932                                                   "  AND p.oid = pr.prpubid",
3933                                                   tbinfo->dobj.catId.oid);
3934                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3935
3936                 ntups = PQntuples(res);
3937
3938                 if (ntups == 0)
3939                 {
3940                         /*
3941                          * Table is not member of any publications. Clean up and return.
3942                          */
3943                         PQclear(res);
3944                         continue;
3945                 }
3946
3947                 i_tableoid = PQfnumber(res, "tableoid");
3948                 i_oid = PQfnumber(res, "oid");
3949                 i_pubname = PQfnumber(res, "pubname");
3950
3951                 pubrinfo = pg_malloc(ntups * sizeof(PublicationRelInfo));
3952
3953                 for (j = 0; j < ntups; j++)
3954                 {
3955                         pubrinfo[j].dobj.objType = DO_PUBLICATION_REL;
3956                         pubrinfo[j].dobj.catId.tableoid =
3957                                 atooid(PQgetvalue(res, j, i_tableoid));
3958                         pubrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3959                         AssignDumpId(&pubrinfo[j].dobj);
3960                         pubrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3961                         pubrinfo[j].dobj.name = tbinfo->dobj.name;
3962                         pubrinfo[j].pubname = pg_strdup(PQgetvalue(res, j, i_pubname));
3963                         pubrinfo[j].pubtable = tbinfo;
3964
3965                         /* Decide whether we want to dump it */
3966                         selectDumpablePublicationTable(&(pubrinfo[j].dobj), fout);
3967                 }
3968                 PQclear(res);
3969         }
3970         destroyPQExpBuffer(query);
3971 }
3972
3973 /*
3974  * dumpPublicationTable
3975  *        dump the definition of the given publication table mapping
3976  */
3977 static void
3978 dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo)
3979 {
3980         TableInfo  *tbinfo = pubrinfo->pubtable;
3981         PQExpBuffer query;
3982         char       *tag;
3983
3984         if (!(pubrinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3985                 return;
3986
3987         tag = psprintf("%s %s", pubrinfo->pubname, tbinfo->dobj.name);
3988
3989         query = createPQExpBuffer();
3990
3991         appendPQExpBuffer(query, "ALTER PUBLICATION %s ADD TABLE ONLY",
3992                                           fmtId(pubrinfo->pubname));
3993         appendPQExpBuffer(query, " %s;\n",
3994                                           fmtQualifiedDumpable(tbinfo));
3995
3996         /*
3997          * There is no point in creating drop query as drop query as the drop is
3998          * done by table drop.
3999          */
4000         ArchiveEntry(fout, pubrinfo->dobj.catId, pubrinfo->dobj.dumpId,
4001                                  tag,
4002                                  tbinfo->dobj.namespace->dobj.name,
4003                                  NULL,
4004                                  "", false,
4005                                  "PUBLICATION TABLE", SECTION_POST_DATA,
4006                                  query->data, "", NULL,
4007                                  NULL, 0,
4008                                  NULL, NULL);
4009
4010         free(tag);
4011         destroyPQExpBuffer(query);
4012 }
4013
4014 /*
4015  * Is the currently connected user a superuser?
4016  */
4017 static bool
4018 is_superuser(Archive *fout)
4019 {
4020         ArchiveHandle *AH = (ArchiveHandle *) fout;
4021         const char *val;
4022
4023         val = PQparameterStatus(AH->connection, "is_superuser");
4024
4025         if (val && strcmp(val, "on") == 0)
4026                 return true;
4027
4028         return false;
4029 }
4030
4031 /*
4032  * getSubscriptions
4033  *        get information about subscriptions
4034  */
4035 void
4036 getSubscriptions(Archive *fout)
4037 {
4038         DumpOptions *dopt = fout->dopt;
4039         PQExpBuffer query;
4040         PGresult   *res;
4041         SubscriptionInfo *subinfo;
4042         int                     i_tableoid;
4043         int                     i_oid;
4044         int                     i_subname;
4045         int                     i_rolname;
4046         int                     i_subconninfo;
4047         int                     i_subslotname;
4048         int                     i_subsynccommit;
4049         int                     i_subpublications;
4050         int                     i,
4051                                 ntups;
4052
4053         if (dopt->no_subscriptions || fout->remoteVersion < 100000)
4054                 return;
4055
4056         if (!is_superuser(fout))
4057         {
4058                 int                     n;
4059
4060                 res = ExecuteSqlQuery(fout,
4061                                                           "SELECT count(*) FROM pg_subscription "
4062                                                           "WHERE subdbid = (SELECT oid FROM pg_database"
4063                                                           "                 WHERE datname = current_database())",
4064                                                           PGRES_TUPLES_OK);
4065                 n = atoi(PQgetvalue(res, 0, 0));
4066                 if (n > 0)
4067                         write_msg(NULL, "WARNING: subscriptions not dumped because current user is not a superuser\n");
4068                 PQclear(res);
4069                 return;
4070         }
4071
4072         query = createPQExpBuffer();
4073
4074         resetPQExpBuffer(query);
4075
4076         /* Get the subscriptions in current database. */
4077         appendPQExpBuffer(query,
4078                                           "SELECT s.tableoid, s.oid, s.subname,"
4079                                           "(%s s.subowner) AS rolname, "
4080                                           " s.subconninfo, s.subslotname, s.subsynccommit, "
4081                                           " s.subpublications "
4082                                           "FROM pg_subscription s "
4083                                           "WHERE s.subdbid = (SELECT oid FROM pg_database"
4084                                           "                   WHERE datname = current_database())",
4085                                           username_subquery);
4086         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4087
4088         ntups = PQntuples(res);
4089
4090         i_tableoid = PQfnumber(res, "tableoid");
4091         i_oid = PQfnumber(res, "oid");
4092         i_subname = PQfnumber(res, "subname");
4093         i_rolname = PQfnumber(res, "rolname");
4094         i_subconninfo = PQfnumber(res, "subconninfo");
4095         i_subslotname = PQfnumber(res, "subslotname");
4096         i_subsynccommit = PQfnumber(res, "subsynccommit");
4097         i_subpublications = PQfnumber(res, "subpublications");
4098
4099         subinfo = pg_malloc(ntups * sizeof(SubscriptionInfo));
4100
4101         for (i = 0; i < ntups; i++)
4102         {
4103                 subinfo[i].dobj.objType = DO_SUBSCRIPTION;
4104                 subinfo[i].dobj.catId.tableoid =
4105                         atooid(PQgetvalue(res, i, i_tableoid));
4106                 subinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4107                 AssignDumpId(&subinfo[i].dobj);
4108                 subinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_subname));
4109                 subinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4110                 subinfo[i].subconninfo = pg_strdup(PQgetvalue(res, i, i_subconninfo));
4111                 if (PQgetisnull(res, i, i_subslotname))
4112                         subinfo[i].subslotname = NULL;
4113                 else
4114                         subinfo[i].subslotname = pg_strdup(PQgetvalue(res, i, i_subslotname));
4115                 subinfo[i].subsynccommit =
4116                         pg_strdup(PQgetvalue(res, i, i_subsynccommit));
4117                 subinfo[i].subpublications =
4118                         pg_strdup(PQgetvalue(res, i, i_subpublications));
4119
4120                 if (strlen(subinfo[i].rolname) == 0)
4121                         write_msg(NULL, "WARNING: owner of subscription \"%s\" appears to be invalid\n",
4122                                           subinfo[i].dobj.name);
4123
4124                 /* Decide whether we want to dump it */
4125                 selectDumpableObject(&(subinfo[i].dobj), fout);
4126         }
4127         PQclear(res);
4128
4129         destroyPQExpBuffer(query);
4130 }
4131
4132 /*
4133  * dumpSubscription
4134  *        dump the definition of the given subscription
4135  */
4136 static void
4137 dumpSubscription(Archive *fout, SubscriptionInfo *subinfo)
4138 {
4139         PQExpBuffer delq;
4140         PQExpBuffer query;
4141         PQExpBuffer publications;
4142         char       *qsubname;
4143         char      **pubnames = NULL;
4144         int                     npubnames = 0;
4145         int                     i;
4146
4147         if (!(subinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
4148                 return;
4149
4150         delq = createPQExpBuffer();
4151         query = createPQExpBuffer();
4152
4153         qsubname = pg_strdup(fmtId(subinfo->dobj.name));
4154
4155         appendPQExpBuffer(delq, "DROP SUBSCRIPTION %s;\n",
4156                                           qsubname);
4157
4158         appendPQExpBuffer(query, "CREATE SUBSCRIPTION %s CONNECTION ",
4159                                           qsubname);
4160         appendStringLiteralAH(query, subinfo->subconninfo, fout);
4161
4162         /* Build list of quoted publications and append them to query. */
4163         if (!parsePGArray(subinfo->subpublications, &pubnames, &npubnames))
4164         {
4165                 write_msg(NULL,
4166                                   "WARNING: could not parse subpublications array\n");
4167                 if (pubnames)
4168                         free(pubnames);
4169                 pubnames = NULL;
4170                 npubnames = 0;
4171         }
4172
4173         publications = createPQExpBuffer();
4174         for (i = 0; i < npubnames; i++)
4175         {
4176                 if (i > 0)
4177                         appendPQExpBufferStr(publications, ", ");
4178
4179                 appendPQExpBufferStr(publications, fmtId(pubnames[i]));
4180         }
4181
4182         appendPQExpBuffer(query, " PUBLICATION %s WITH (connect = false, slot_name = ", publications->data);
4183         if (subinfo->subslotname)
4184                 appendStringLiteralAH(query, subinfo->subslotname, fout);
4185         else
4186                 appendPQExpBufferStr(query, "NONE");
4187
4188         if (strcmp(subinfo->subsynccommit, "off") != 0)
4189                 appendPQExpBuffer(query, ", synchronous_commit = %s", fmtId(subinfo->subsynccommit));
4190
4191         appendPQExpBufferStr(query, ");\n");
4192
4193         ArchiveEntry(fout, subinfo->dobj.catId, subinfo->dobj.dumpId,
4194                                  subinfo->dobj.name,
4195                                  NULL,
4196                                  NULL,
4197                                  subinfo->rolname, false,
4198                                  "SUBSCRIPTION", SECTION_POST_DATA,
4199                                  query->data, delq->data, NULL,
4200                                  NULL, 0,
4201                                  NULL, NULL);
4202
4203         if (subinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
4204                 dumpComment(fout, "SUBSCRIPTION", qsubname,
4205                                         NULL, subinfo->rolname,
4206                                         subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
4207
4208         if (subinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
4209                 dumpSecLabel(fout, "SUBSCRIPTION", qsubname,
4210                                          NULL, subinfo->rolname,
4211                                          subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
4212
4213         destroyPQExpBuffer(publications);
4214         if (pubnames)
4215                 free(pubnames);
4216
4217         destroyPQExpBuffer(delq);
4218         destroyPQExpBuffer(query);
4219         free(qsubname);
4220 }
4221
4222 static void
4223 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
4224                                                                                  PQExpBuffer upgrade_buffer,
4225                                                                                  Oid pg_type_oid,
4226                                                                                  bool force_array_type)
4227 {
4228         PQExpBuffer upgrade_query = createPQExpBuffer();
4229         PGresult   *res;
4230         Oid                     pg_type_array_oid;
4231
4232         appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
4233         appendPQExpBuffer(upgrade_buffer,
4234                                           "SELECT pg_catalog.binary_upgrade_set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4235                                           pg_type_oid);
4236
4237         /* we only support old >= 8.3 for binary upgrades */
4238         appendPQExpBuffer(upgrade_query,
4239                                           "SELECT typarray "
4240                                           "FROM pg_catalog.pg_type "
4241                                           "WHERE oid = '%u'::pg_catalog.oid;",
4242                                           pg_type_oid);
4243
4244         res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4245
4246         pg_type_array_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typarray")));
4247
4248         PQclear(res);
4249
4250         if (!OidIsValid(pg_type_array_oid) && force_array_type)
4251         {
4252                 /*
4253                  * If the old version didn't assign an array type, but the new version
4254                  * does, we must select an unused type OID to assign.  This currently
4255                  * only happens for domains, when upgrading pre-v11 to v11 and up.
4256                  *
4257                  * Note: local state here is kind of ugly, but we must have some,
4258                  * since we mustn't choose the same unused OID more than once.
4259                  */
4260                 static Oid      next_possible_free_oid = FirstNormalObjectId;
4261                 bool            is_dup;
4262
4263                 do
4264                 {
4265                         ++next_possible_free_oid;
4266                         printfPQExpBuffer(upgrade_query,
4267                                                           "SELECT EXISTS(SELECT 1 "
4268                                                           "FROM pg_catalog.pg_type "
4269                                                           "WHERE oid = '%u'::pg_catalog.oid);",
4270                                                           next_possible_free_oid);
4271                         res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4272                         is_dup = (PQgetvalue(res, 0, 0)[0] == 't');
4273                         PQclear(res);
4274                 } while (is_dup);
4275
4276                 pg_type_array_oid = next_possible_free_oid;
4277         }
4278
4279         if (OidIsValid(pg_type_array_oid))
4280         {
4281                 appendPQExpBufferStr(upgrade_buffer,
4282                                                          "\n-- For binary upgrade, must preserve pg_type array oid\n");
4283                 appendPQExpBuffer(upgrade_buffer,
4284                                                   "SELECT pg_catalog.binary_upgrade_set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4285                                                   pg_type_array_oid);
4286         }
4287
4288         destroyPQExpBuffer(upgrade_query);
4289 }
4290
4291 static bool
4292 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
4293                                                                                 PQExpBuffer upgrade_buffer,
4294                                                                                 Oid pg_rel_oid)
4295 {
4296         PQExpBuffer upgrade_query = createPQExpBuffer();
4297         PGresult   *upgrade_res;
4298         Oid                     pg_type_oid;
4299         bool            toast_set = false;
4300
4301         /* we only support old >= 8.3 for binary upgrades */
4302         appendPQExpBuffer(upgrade_query,
4303                                           "SELECT c.reltype AS crel, t.reltype AS trel "
4304                                           "FROM pg_catalog.pg_class c "
4305                                           "LEFT JOIN pg_catalog.pg_class t ON "
4306                                           "  (c.reltoastrelid = t.oid) "
4307                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
4308                                           pg_rel_oid);
4309
4310         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4311
4312         pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
4313
4314         binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
4315                                                                                          pg_type_oid, false);
4316
4317         if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
4318         {
4319                 /* Toast tables do not have pg_type array rows */
4320                 Oid                     pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
4321                                                                                                                   PQfnumber(upgrade_res, "trel")));
4322
4323                 appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
4324                 appendPQExpBuffer(upgrade_buffer,
4325                                                   "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4326                                                   pg_type_toast_oid);
4327
4328                 toast_set = true;
4329         }
4330
4331         PQclear(upgrade_res);
4332         destroyPQExpBuffer(upgrade_query);
4333
4334         return toast_set;
4335 }
4336
4337 static void
4338 binary_upgrade_set_pg_class_oids(Archive *fout,
4339                                                                  PQExpBuffer upgrade_buffer, Oid pg_class_oid,
4340                                                                  bool is_index)
4341 {
4342         PQExpBuffer upgrade_query = createPQExpBuffer();
4343         PGresult   *upgrade_res;
4344         Oid                     pg_class_reltoastrelid;
4345         Oid                     pg_index_indexrelid;
4346
4347         appendPQExpBuffer(upgrade_query,
4348                                           "SELECT c.reltoastrelid, i.indexrelid "
4349                                           "FROM pg_catalog.pg_class c LEFT JOIN "
4350                                           "pg_catalog.pg_index i ON (c.reltoastrelid = i.indrelid AND i.indisvalid) "
4351                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
4352                                           pg_class_oid);
4353
4354         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
4355
4356         pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
4357         pg_index_indexrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "indexrelid")));
4358
4359         appendPQExpBufferStr(upgrade_buffer,
4360                                                  "\n-- For binary upgrade, must preserve pg_class oids\n");
4361
4362         if (!is_index)
4363         {
4364                 appendPQExpBuffer(upgrade_buffer,
4365                                                   "SELECT pg_catalog.binary_upgrade_set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
4366                                                   pg_class_oid);
4367                 /* only tables have toast tables, not indexes */
4368                 if (OidIsValid(pg_class_reltoastrelid))
4369                 {
4370                         /*
4371                          * One complexity is that the table definition might not require
4372                          * the creation of a TOAST table, and the TOAST table might have
4373                          * been created long after table creation, when the table was
4374                          * loaded with wide data.  By setting the TOAST oid we force
4375                          * creation of the TOAST heap and TOAST index by the backend so we
4376                          * can cleanly copy the files during binary upgrade.
4377                          */
4378
4379                         appendPQExpBuffer(upgrade_buffer,
4380                                                           "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
4381                                                           pg_class_reltoastrelid);
4382
4383                         /* every toast table has an index */
4384                         appendPQExpBuffer(upgrade_buffer,
4385                                                           "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4386                                                           pg_index_indexrelid);
4387                 }
4388         }
4389         else
4390                 appendPQExpBuffer(upgrade_buffer,
4391                                                   "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4392                                                   pg_class_oid);
4393
4394         appendPQExpBufferChar(upgrade_buffer, '\n');
4395
4396         PQclear(upgrade_res);
4397         destroyPQExpBuffer(upgrade_query);
4398 }
4399
4400 /*
4401  * If the DumpableObject is a member of an extension, add a suitable
4402  * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
4403  *
4404  * For somewhat historical reasons, objname should already be quoted,
4405  * but not objnamespace (if any).
4406  */
4407 static void
4408 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
4409                                                                 DumpableObject *dobj,
4410                                                                 const char *objtype,
4411                                                                 const char *objname,
4412                                                                 const char *objnamespace)
4413 {
4414         DumpableObject *extobj = NULL;
4415         int                     i;
4416
4417         if (!dobj->ext_member)
4418                 return;
4419
4420         /*
4421          * Find the parent extension.  We could avoid this search if we wanted to
4422          * add a link field to DumpableObject, but the space costs of that would
4423          * be considerable.  We assume that member objects could only have a
4424          * direct dependency on their own extension, not any others.
4425          */
4426         for (i = 0; i < dobj->nDeps; i++)
4427         {
4428                 extobj = findObjectByDumpId(dobj->dependencies[i]);
4429                 if (extobj && extobj->objType == DO_EXTENSION)
4430                         break;
4431                 extobj = NULL;
4432         }
4433         if (extobj == NULL)
4434                 exit_horribly(NULL, "could not find parent extension for %s %s\n",
4435                                           objtype, objname);
4436
4437         appendPQExpBufferStr(upgrade_buffer,
4438                                                  "\n-- For binary upgrade, handle extension membership the hard way\n");
4439         appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s ",
4440                                           fmtId(extobj->name),
4441                                           objtype);
4442         if (objnamespace && *objnamespace)
4443                 appendPQExpBuffer(upgrade_buffer, "%s.", fmtId(objnamespace));
4444         appendPQExpBuffer(upgrade_buffer, "%s;\n", objname);
4445 }
4446
4447 /*
4448  * getNamespaces:
4449  *        read all namespaces in the system catalogs and return them in the
4450  * NamespaceInfo* structure
4451  *
4452  *      numNamespaces is set to the number of namespaces read in
4453  */
4454 NamespaceInfo *
4455 getNamespaces(Archive *fout, int *numNamespaces)
4456 {
4457         DumpOptions *dopt = fout->dopt;
4458         PGresult   *res;
4459         int                     ntups;
4460         int                     i;
4461         PQExpBuffer query;
4462         NamespaceInfo *nsinfo;
4463         int                     i_tableoid;
4464         int                     i_oid;
4465         int                     i_nspname;
4466         int                     i_rolname;
4467         int                     i_nspacl;
4468         int                     i_rnspacl;
4469         int                     i_initnspacl;
4470         int                     i_initrnspacl;
4471
4472         query = createPQExpBuffer();
4473
4474         /*
4475          * we fetch all namespaces including system ones, so that every object we
4476          * read in can be linked to a containing namespace.
4477          */
4478         if (fout->remoteVersion >= 90600)
4479         {
4480                 PQExpBuffer acl_subquery = createPQExpBuffer();
4481                 PQExpBuffer racl_subquery = createPQExpBuffer();
4482                 PQExpBuffer init_acl_subquery = createPQExpBuffer();
4483                 PQExpBuffer init_racl_subquery = createPQExpBuffer();
4484
4485                 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
4486                                                 init_racl_subquery, "n.nspacl", "n.nspowner", "'n'",
4487                                                 dopt->binary_upgrade);
4488
4489                 appendPQExpBuffer(query, "SELECT n.tableoid, n.oid, n.nspname, "
4490                                                   "(%s nspowner) AS rolname, "
4491                                                   "%s as nspacl, "
4492                                                   "%s as rnspacl, "
4493                                                   "%s as initnspacl, "
4494                                                   "%s as initrnspacl "
4495                                                   "FROM pg_namespace n "
4496                                                   "LEFT JOIN pg_init_privs pip "
4497                                                   "ON (n.oid = pip.objoid "
4498                                                   "AND pip.classoid = 'pg_namespace'::regclass "
4499                                                   "AND pip.objsubid = 0",
4500                                                   username_subquery,
4501                                                   acl_subquery->data,
4502                                                   racl_subquery->data,
4503                                                   init_acl_subquery->data,
4504                                                   init_racl_subquery->data);
4505
4506                 appendPQExpBuffer(query, ") ");
4507
4508                 destroyPQExpBuffer(acl_subquery);
4509                 destroyPQExpBuffer(racl_subquery);
4510                 destroyPQExpBuffer(init_acl_subquery);
4511                 destroyPQExpBuffer(init_racl_subquery);
4512         }
4513         else
4514                 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
4515                                                   "(%s nspowner) AS rolname, "
4516                                                   "nspacl, NULL as rnspacl, "
4517                                                   "NULL AS initnspacl, NULL as initrnspacl "
4518                                                   "FROM pg_namespace",
4519                                                   username_subquery);
4520
4521         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4522
4523         ntups = PQntuples(res);
4524
4525         nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
4526
4527         i_tableoid = PQfnumber(res, "tableoid");
4528         i_oid = PQfnumber(res, "oid");
4529         i_nspname = PQfnumber(res, "nspname");
4530         i_rolname = PQfnumber(res, "rolname");
4531         i_nspacl = PQfnumber(res, "nspacl");
4532         i_rnspacl = PQfnumber(res, "rnspacl");
4533         i_initnspacl = PQfnumber(res, "initnspacl");
4534         i_initrnspacl = PQfnumber(res, "initrnspacl");
4535
4536         for (i = 0; i < ntups; i++)
4537         {
4538                 nsinfo[i].dobj.objType = DO_NAMESPACE;
4539                 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4540                 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4541                 AssignDumpId(&nsinfo[i].dobj);
4542                 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
4543                 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4544                 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
4545                 nsinfo[i].rnspacl = pg_strdup(PQgetvalue(res, i, i_rnspacl));
4546                 nsinfo[i].initnspacl = pg_strdup(PQgetvalue(res, i, i_initnspacl));
4547                 nsinfo[i].initrnspacl = pg_strdup(PQgetvalue(res, i, i_initrnspacl));
4548
4549                 /* Decide whether to dump this namespace */
4550                 selectDumpableNamespace(&nsinfo[i], fout);
4551
4552                 /*
4553                  * Do not try to dump ACL if the ACL is empty or the default.
4554                  *
4555                  * This is useful because, for some schemas/objects, the only
4556                  * component we are going to try and dump is the ACL and if we can
4557                  * remove that then 'dump' goes to zero/false and we don't consider
4558                  * this object for dumping at all later on.
4559                  */
4560                 if (PQgetisnull(res, i, i_nspacl) && PQgetisnull(res, i, i_rnspacl) &&
4561                         PQgetisnull(res, i, i_initnspacl) &&
4562                         PQgetisnull(res, i, i_initrnspacl))
4563                         nsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4564
4565                 if (strlen(nsinfo[i].rolname) == 0)
4566                         write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
4567                                           nsinfo[i].dobj.name);
4568         }
4569
4570         PQclear(res);
4571         destroyPQExpBuffer(query);
4572
4573         *numNamespaces = ntups;
4574
4575         return nsinfo;
4576 }
4577
4578 /*
4579  * findNamespace:
4580  *              given a namespace OID, look up the info read by getNamespaces
4581  */
4582 static NamespaceInfo *
4583 findNamespace(Archive *fout, Oid nsoid)
4584 {
4585         NamespaceInfo *nsinfo;
4586
4587         nsinfo = findNamespaceByOid(nsoid);
4588         if (nsinfo == NULL)
4589                 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
4590         return nsinfo;
4591 }
4592
4593 /*
4594  * getExtensions:
4595  *        read all extensions in the system catalogs and return them in the
4596  * ExtensionInfo* structure
4597  *
4598  *      numExtensions is set to the number of extensions read in
4599  */
4600 ExtensionInfo *
4601 getExtensions(Archive *fout, int *numExtensions)
4602 {
4603         DumpOptions *dopt = fout->dopt;
4604         PGresult   *res;
4605         int                     ntups;
4606         int                     i;
4607         PQExpBuffer query;
4608         ExtensionInfo *extinfo;
4609         int                     i_tableoid;
4610         int                     i_oid;
4611         int                     i_extname;
4612         int                     i_nspname;
4613         int                     i_extrelocatable;
4614         int                     i_extversion;
4615         int                     i_extconfig;
4616         int                     i_extcondition;
4617
4618         /*
4619          * Before 9.1, there are no extensions.
4620          */
4621         if (fout->remoteVersion < 90100)
4622         {
4623                 *numExtensions = 0;
4624                 return NULL;
4625         }
4626
4627         query = createPQExpBuffer();
4628
4629         appendPQExpBufferStr(query, "SELECT x.tableoid, x.oid, "
4630                                                  "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
4631                                                  "FROM pg_extension x "
4632                                                  "JOIN pg_namespace n ON n.oid = x.extnamespace");
4633
4634         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4635
4636         ntups = PQntuples(res);
4637
4638         extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
4639
4640         i_tableoid = PQfnumber(res, "tableoid");
4641         i_oid = PQfnumber(res, "oid");
4642         i_extname = PQfnumber(res, "extname");
4643         i_nspname = PQfnumber(res, "nspname");
4644         i_extrelocatable = PQfnumber(res, "extrelocatable");
4645         i_extversion = PQfnumber(res, "extversion");
4646         i_extconfig = PQfnumber(res, "extconfig");
4647         i_extcondition = PQfnumber(res, "extcondition");
4648
4649         for (i = 0; i < ntups; i++)
4650         {
4651                 extinfo[i].dobj.objType = DO_EXTENSION;
4652                 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4653                 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4654                 AssignDumpId(&extinfo[i].dobj);
4655                 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
4656                 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
4657                 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
4658                 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
4659                 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
4660                 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
4661
4662                 /* Decide whether we want to dump it */
4663                 selectDumpableExtension(&(extinfo[i]), dopt);
4664         }
4665
4666         PQclear(res);
4667         destroyPQExpBuffer(query);
4668
4669         *numExtensions = ntups;
4670
4671         return extinfo;
4672 }
4673
4674 /*
4675  * getTypes:
4676  *        read all types in the system catalogs and return them in the
4677  * TypeInfo* structure
4678  *
4679  *      numTypes is set to the number of types read in
4680  *
4681  * NB: this must run after getFuncs() because we assume we can do
4682  * findFuncByOid().
4683  */
4684 TypeInfo *
4685 getTypes(Archive *fout, int *numTypes)
4686 {
4687         DumpOptions *dopt = fout->dopt;
4688         PGresult   *res;
4689         int                     ntups;
4690         int                     i;
4691         PQExpBuffer query = createPQExpBuffer();
4692         TypeInfo   *tyinfo;
4693         ShellTypeInfo *stinfo;
4694         int                     i_tableoid;
4695         int                     i_oid;
4696         int                     i_typname;
4697         int                     i_typnamespace;
4698         int                     i_typacl;
4699         int                     i_rtypacl;
4700         int                     i_inittypacl;
4701         int                     i_initrtypacl;
4702         int                     i_rolname;
4703         int                     i_typelem;
4704         int                     i_typrelid;
4705         int                     i_typrelkind;
4706         int                     i_typtype;
4707         int                     i_typisdefined;
4708         int                     i_isarray;
4709
4710         /*
4711          * we include even the built-in types because those may be used as array
4712          * elements by user-defined types
4713          *
4714          * we filter out the built-in types when we dump out the types
4715          *
4716          * same approach for undefined (shell) types and array types
4717          *
4718          * Note: as of 8.3 we can reliably detect whether a type is an
4719          * auto-generated array type by checking the element type's typarray.
4720          * (Before that the test is capable of generating false positives.) We
4721          * still check for name beginning with '_', though, so as to avoid the
4722          * cost of the subselect probe for all standard types.  This would have to
4723          * be revisited if the backend ever allows renaming of array types.
4724          */
4725
4726         if (fout->remoteVersion >= 90600)
4727         {
4728                 PQExpBuffer acl_subquery = createPQExpBuffer();
4729                 PQExpBuffer racl_subquery = createPQExpBuffer();
4730                 PQExpBuffer initacl_subquery = createPQExpBuffer();
4731                 PQExpBuffer initracl_subquery = createPQExpBuffer();
4732
4733                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
4734                                                 initracl_subquery, "t.typacl", "t.typowner", "'T'",
4735                                                 dopt->binary_upgrade);
4736
4737                 appendPQExpBuffer(query, "SELECT t.tableoid, t.oid, t.typname, "
4738                                                   "t.typnamespace, "
4739                                                   "%s AS typacl, "
4740                                                   "%s AS rtypacl, "
4741                                                   "%s AS inittypacl, "
4742                                                   "%s AS initrtypacl, "
4743                                                   "(%s t.typowner) AS rolname, "
4744                                                   "t.typelem, t.typrelid, "
4745                                                   "CASE WHEN t.typrelid = 0 THEN ' '::\"char\" "
4746                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = t.typrelid) END AS typrelkind, "
4747                                                   "t.typtype, t.typisdefined, "
4748                                                   "t.typname[0] = '_' AND t.typelem != 0 AND "
4749                                                   "(SELECT typarray FROM pg_type te WHERE oid = t.typelem) = t.oid AS isarray "
4750                                                   "FROM pg_type t "
4751                                                   "LEFT JOIN pg_init_privs pip ON "
4752                                                   "(t.oid = pip.objoid "
4753                                                   "AND pip.classoid = 'pg_type'::regclass "
4754                                                   "AND pip.objsubid = 0) ",
4755                                                   acl_subquery->data,
4756                                                   racl_subquery->data,
4757                                                   initacl_subquery->data,
4758                                                   initracl_subquery->data,
4759                                                   username_subquery);
4760
4761                 destroyPQExpBuffer(acl_subquery);
4762                 destroyPQExpBuffer(racl_subquery);
4763                 destroyPQExpBuffer(initacl_subquery);
4764                 destroyPQExpBuffer(initracl_subquery);
4765         }
4766         else if (fout->remoteVersion >= 90200)
4767         {
4768                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4769                                                   "typnamespace, typacl, NULL as rtypacl, "
4770                                                   "NULL AS inittypacl, NULL AS initrtypacl, "
4771                                                   "(%s typowner) AS rolname, "
4772                                                   "typelem, typrelid, "
4773                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4774                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4775                                                   "typtype, typisdefined, "
4776                                                   "typname[0] = '_' AND typelem != 0 AND "
4777                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4778                                                   "FROM pg_type",
4779                                                   username_subquery);
4780         }
4781         else if (fout->remoteVersion >= 80300)
4782         {
4783                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4784                                                   "typnamespace, NULL AS typacl, NULL as rtypacl, "
4785                                                   "NULL AS inittypacl, NULL AS initrtypacl, "
4786                                                   "(%s typowner) AS rolname, "
4787                                                   "typelem, typrelid, "
4788                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4789                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4790                                                   "typtype, typisdefined, "
4791                                                   "typname[0] = '_' AND typelem != 0 AND "
4792                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4793                                                   "FROM pg_type",
4794                                                   username_subquery);
4795         }
4796         else
4797         {
4798                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4799                                                   "typnamespace, NULL AS typacl, NULL as rtypacl, "
4800                                                   "NULL AS inittypacl, NULL AS initrtypacl, "
4801                                                   "(%s typowner) AS rolname, "
4802                                                   "typelem, typrelid, "
4803                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4804                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4805                                                   "typtype, typisdefined, "
4806                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
4807                                                   "FROM pg_type",
4808                                                   username_subquery);
4809         }
4810
4811         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4812
4813         ntups = PQntuples(res);
4814
4815         tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
4816
4817         i_tableoid = PQfnumber(res, "tableoid");
4818         i_oid = PQfnumber(res, "oid");
4819         i_typname = PQfnumber(res, "typname");
4820         i_typnamespace = PQfnumber(res, "typnamespace");
4821         i_typacl = PQfnumber(res, "typacl");
4822         i_rtypacl = PQfnumber(res, "rtypacl");
4823         i_inittypacl = PQfnumber(res, "inittypacl");
4824         i_initrtypacl = PQfnumber(res, "initrtypacl");
4825         i_rolname = PQfnumber(res, "rolname");
4826         i_typelem = PQfnumber(res, "typelem");
4827         i_typrelid = PQfnumber(res, "typrelid");
4828         i_typrelkind = PQfnumber(res, "typrelkind");
4829         i_typtype = PQfnumber(res, "typtype");
4830         i_typisdefined = PQfnumber(res, "typisdefined");
4831         i_isarray = PQfnumber(res, "isarray");
4832
4833         for (i = 0; i < ntups; i++)
4834         {
4835                 tyinfo[i].dobj.objType = DO_TYPE;
4836                 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4837                 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4838                 AssignDumpId(&tyinfo[i].dobj);
4839                 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
4840                 tyinfo[i].dobj.namespace =
4841                         findNamespace(fout,
4842                                                   atooid(PQgetvalue(res, i, i_typnamespace)));
4843                 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4844                 tyinfo[i].typacl = pg_strdup(PQgetvalue(res, i, i_typacl));
4845                 tyinfo[i].rtypacl = pg_strdup(PQgetvalue(res, i, i_rtypacl));
4846                 tyinfo[i].inittypacl = pg_strdup(PQgetvalue(res, i, i_inittypacl));
4847                 tyinfo[i].initrtypacl = pg_strdup(PQgetvalue(res, i, i_initrtypacl));
4848                 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
4849                 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
4850                 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
4851                 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
4852                 tyinfo[i].shellType = NULL;
4853
4854                 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
4855                         tyinfo[i].isDefined = true;
4856                 else
4857                         tyinfo[i].isDefined = false;
4858
4859                 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
4860                         tyinfo[i].isArray = true;
4861                 else
4862                         tyinfo[i].isArray = false;
4863
4864                 /* Decide whether we want to dump it */
4865                 selectDumpableType(&tyinfo[i], fout);
4866
4867                 /* Do not try to dump ACL if no ACL exists. */
4868                 if (PQgetisnull(res, i, i_typacl) && PQgetisnull(res, i, i_rtypacl) &&
4869                         PQgetisnull(res, i, i_inittypacl) &&
4870                         PQgetisnull(res, i, i_initrtypacl))
4871                         tyinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4872
4873                 /*
4874                  * If it's a domain, fetch info about its constraints, if any
4875                  */
4876                 tyinfo[i].nDomChecks = 0;
4877                 tyinfo[i].domChecks = NULL;
4878                 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4879                         tyinfo[i].typtype == TYPTYPE_DOMAIN)
4880                         getDomainConstraints(fout, &(tyinfo[i]));
4881
4882                 /*
4883                  * If it's a base type, make a DumpableObject representing a shell
4884                  * definition of the type.  We will need to dump that ahead of the I/O
4885                  * functions for the type.  Similarly, range types need a shell
4886                  * definition in case they have a canonicalize function.
4887                  *
4888                  * Note: the shell type doesn't have a catId.  You might think it
4889                  * should copy the base type's catId, but then it might capture the
4890                  * pg_depend entries for the type, which we don't want.
4891                  */
4892                 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4893                         (tyinfo[i].typtype == TYPTYPE_BASE ||
4894                          tyinfo[i].typtype == TYPTYPE_RANGE))
4895                 {
4896                         stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
4897                         stinfo->dobj.objType = DO_SHELL_TYPE;
4898                         stinfo->dobj.catId = nilCatalogId;
4899                         AssignDumpId(&stinfo->dobj);
4900                         stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
4901                         stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
4902                         stinfo->baseType = &(tyinfo[i]);
4903                         tyinfo[i].shellType = stinfo;
4904
4905                         /*
4906                          * Initially mark the shell type as not to be dumped.  We'll only
4907                          * dump it if the I/O or canonicalize functions need to be dumped;
4908                          * this is taken care of while sorting dependencies.
4909                          */
4910                         stinfo->dobj.dump = DUMP_COMPONENT_NONE;
4911                 }
4912
4913                 if (strlen(tyinfo[i].rolname) == 0)
4914                         write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
4915                                           tyinfo[i].dobj.name);
4916         }
4917
4918         *numTypes = ntups;
4919
4920         PQclear(res);
4921
4922         destroyPQExpBuffer(query);
4923
4924         return tyinfo;
4925 }
4926
4927 /*
4928  * getOperators:
4929  *        read all operators in the system catalogs and return them in the
4930  * OprInfo* structure
4931  *
4932  *      numOprs is set to the number of operators read in
4933  */
4934 OprInfo *
4935 getOperators(Archive *fout, int *numOprs)
4936 {
4937         PGresult   *res;
4938         int                     ntups;
4939         int                     i;
4940         PQExpBuffer query = createPQExpBuffer();
4941         OprInfo    *oprinfo;
4942         int                     i_tableoid;
4943         int                     i_oid;
4944         int                     i_oprname;
4945         int                     i_oprnamespace;
4946         int                     i_rolname;
4947         int                     i_oprkind;
4948         int                     i_oprcode;
4949
4950         /*
4951          * find all operators, including builtin operators; we filter out
4952          * system-defined operators at dump-out time.
4953          */
4954
4955         appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
4956                                           "oprnamespace, "
4957                                           "(%s oprowner) AS rolname, "
4958                                           "oprkind, "
4959                                           "oprcode::oid AS oprcode "
4960                                           "FROM pg_operator",
4961                                           username_subquery);
4962
4963         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4964
4965         ntups = PQntuples(res);
4966         *numOprs = ntups;
4967
4968         oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
4969
4970         i_tableoid = PQfnumber(res, "tableoid");
4971         i_oid = PQfnumber(res, "oid");
4972         i_oprname = PQfnumber(res, "oprname");
4973         i_oprnamespace = PQfnumber(res, "oprnamespace");
4974         i_rolname = PQfnumber(res, "rolname");
4975         i_oprkind = PQfnumber(res, "oprkind");
4976         i_oprcode = PQfnumber(res, "oprcode");
4977
4978         for (i = 0; i < ntups; i++)
4979         {
4980                 oprinfo[i].dobj.objType = DO_OPERATOR;
4981                 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4982                 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4983                 AssignDumpId(&oprinfo[i].dobj);
4984                 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
4985                 oprinfo[i].dobj.namespace =
4986                         findNamespace(fout,
4987                                                   atooid(PQgetvalue(res, i, i_oprnamespace)));
4988                 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4989                 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
4990                 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
4991
4992                 /* Decide whether we want to dump it */
4993                 selectDumpableObject(&(oprinfo[i].dobj), fout);
4994
4995                 /* Operators do not currently have ACLs. */
4996                 oprinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4997
4998                 if (strlen(oprinfo[i].rolname) == 0)
4999                         write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
5000                                           oprinfo[i].dobj.name);
5001         }
5002
5003         PQclear(res);
5004
5005         destroyPQExpBuffer(query);
5006
5007         return oprinfo;
5008 }
5009
5010 /*
5011  * getCollations:
5012  *        read all collations in the system catalogs and return them in the
5013  * CollInfo* structure
5014  *
5015  *      numCollations is set to the number of collations read in
5016  */
5017 CollInfo *
5018 getCollations(Archive *fout, int *numCollations)
5019 {
5020         PGresult   *res;
5021         int                     ntups;
5022         int                     i;
5023         PQExpBuffer query;
5024         CollInfo   *collinfo;
5025         int                     i_tableoid;
5026         int                     i_oid;
5027         int                     i_collname;
5028         int                     i_collnamespace;
5029         int                     i_rolname;
5030
5031         /* Collations didn't exist pre-9.1 */
5032         if (fout->remoteVersion < 90100)
5033         {
5034                 *numCollations = 0;
5035                 return NULL;
5036         }
5037
5038         query = createPQExpBuffer();
5039
5040         /*
5041          * find all collations, including builtin collations; we filter out
5042          * system-defined collations at dump-out time.
5043          */
5044
5045         appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
5046                                           "collnamespace, "
5047                                           "(%s collowner) AS rolname "
5048                                           "FROM pg_collation",
5049                                           username_subquery);
5050
5051         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5052
5053         ntups = PQntuples(res);
5054         *numCollations = ntups;
5055
5056         collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
5057
5058         i_tableoid = PQfnumber(res, "tableoid");
5059         i_oid = PQfnumber(res, "oid");
5060         i_collname = PQfnumber(res, "collname");
5061         i_collnamespace = PQfnumber(res, "collnamespace");
5062         i_rolname = PQfnumber(res, "rolname");
5063
5064         for (i = 0; i < ntups; i++)
5065         {
5066                 collinfo[i].dobj.objType = DO_COLLATION;
5067                 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5068                 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5069                 AssignDumpId(&collinfo[i].dobj);
5070                 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
5071                 collinfo[i].dobj.namespace =
5072                         findNamespace(fout,
5073                                                   atooid(PQgetvalue(res, i, i_collnamespace)));
5074                 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5075
5076                 /* Decide whether we want to dump it */
5077                 selectDumpableObject(&(collinfo[i].dobj), fout);
5078
5079                 /* Collations do not currently have ACLs. */
5080                 collinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5081         }
5082
5083         PQclear(res);
5084
5085         destroyPQExpBuffer(query);
5086
5087         return collinfo;
5088 }
5089
5090 /*
5091  * getConversions:
5092  *        read all conversions in the system catalogs and return them in the
5093  * ConvInfo* structure
5094  *
5095  *      numConversions is set to the number of conversions read in
5096  */
5097 ConvInfo *
5098 getConversions(Archive *fout, int *numConversions)
5099 {
5100         PGresult   *res;
5101         int                     ntups;
5102         int                     i;
5103         PQExpBuffer query;
5104         ConvInfo   *convinfo;
5105         int                     i_tableoid;
5106         int                     i_oid;
5107         int                     i_conname;
5108         int                     i_connamespace;
5109         int                     i_rolname;
5110
5111         query = createPQExpBuffer();
5112
5113         /*
5114          * find all conversions, including builtin conversions; we filter out
5115          * system-defined conversions at dump-out time.
5116          */
5117
5118         appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5119                                           "connamespace, "
5120                                           "(%s conowner) AS rolname "
5121                                           "FROM pg_conversion",
5122                                           username_subquery);
5123
5124         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5125
5126         ntups = PQntuples(res);
5127         *numConversions = ntups;
5128
5129         convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
5130
5131         i_tableoid = PQfnumber(res, "tableoid");
5132         i_oid = PQfnumber(res, "oid");
5133         i_conname = PQfnumber(res, "conname");
5134         i_connamespace = PQfnumber(res, "connamespace");
5135         i_rolname = PQfnumber(res, "rolname");
5136
5137         for (i = 0; i < ntups; i++)
5138         {
5139                 convinfo[i].dobj.objType = DO_CONVERSION;
5140                 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5141                 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5142                 AssignDumpId(&convinfo[i].dobj);
5143                 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5144                 convinfo[i].dobj.namespace =
5145                         findNamespace(fout,
5146                                                   atooid(PQgetvalue(res, i, i_connamespace)));
5147                 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5148
5149                 /* Decide whether we want to dump it */
5150                 selectDumpableObject(&(convinfo[i].dobj), fout);
5151
5152                 /* Conversions do not currently have ACLs. */
5153                 convinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5154         }
5155
5156         PQclear(res);
5157
5158         destroyPQExpBuffer(query);
5159
5160         return convinfo;
5161 }
5162
5163 /*
5164  * getAccessMethods:
5165  *        read all user-defined access methods in the system catalogs and return
5166  *        them in the AccessMethodInfo* structure
5167  *
5168  *      numAccessMethods is set to the number of access methods read in
5169  */
5170 AccessMethodInfo *
5171 getAccessMethods(Archive *fout, int *numAccessMethods)
5172 {
5173         PGresult   *res;
5174         int                     ntups;
5175         int                     i;
5176         PQExpBuffer query;
5177         AccessMethodInfo *aminfo;
5178         int                     i_tableoid;
5179         int                     i_oid;
5180         int                     i_amname;
5181         int                     i_amhandler;
5182         int                     i_amtype;
5183
5184         /* Before 9.6, there are no user-defined access methods */
5185         if (fout->remoteVersion < 90600)
5186         {
5187                 *numAccessMethods = 0;
5188                 return NULL;
5189         }
5190
5191         query = createPQExpBuffer();
5192
5193         /* Select all access methods from pg_am table */
5194         appendPQExpBuffer(query, "SELECT tableoid, oid, amname, amtype, "
5195                                           "amhandler::pg_catalog.regproc AS amhandler "
5196                                           "FROM pg_am");
5197
5198         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5199
5200         ntups = PQntuples(res);
5201         *numAccessMethods = ntups;
5202
5203         aminfo = (AccessMethodInfo *) pg_malloc(ntups * sizeof(AccessMethodInfo));
5204
5205         i_tableoid = PQfnumber(res, "tableoid");
5206         i_oid = PQfnumber(res, "oid");
5207         i_amname = PQfnumber(res, "amname");
5208         i_amhandler = PQfnumber(res, "amhandler");
5209         i_amtype = PQfnumber(res, "amtype");
5210
5211         for (i = 0; i < ntups; i++)
5212         {
5213                 aminfo[i].dobj.objType = DO_ACCESS_METHOD;
5214                 aminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5215                 aminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5216                 AssignDumpId(&aminfo[i].dobj);
5217                 aminfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_amname));
5218                 aminfo[i].dobj.namespace = NULL;
5219                 aminfo[i].amhandler = pg_strdup(PQgetvalue(res, i, i_amhandler));
5220                 aminfo[i].amtype = *(PQgetvalue(res, i, i_amtype));
5221
5222                 /* Decide whether we want to dump it */
5223                 selectDumpableAccessMethod(&(aminfo[i]), fout);
5224
5225                 /* Access methods do not currently have ACLs. */
5226                 aminfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5227         }
5228
5229         PQclear(res);
5230
5231         destroyPQExpBuffer(query);
5232
5233         return aminfo;
5234 }
5235
5236
5237 /*
5238  * getOpclasses:
5239  *        read all opclasses in the system catalogs and return them in the
5240  * OpclassInfo* structure
5241  *
5242  *      numOpclasses is set to the number of opclasses read in
5243  */
5244 OpclassInfo *
5245 getOpclasses(Archive *fout, int *numOpclasses)
5246 {
5247         PGresult   *res;
5248         int                     ntups;
5249         int                     i;
5250         PQExpBuffer query = createPQExpBuffer();
5251         OpclassInfo *opcinfo;
5252         int                     i_tableoid;
5253         int                     i_oid;
5254         int                     i_opcname;
5255         int                     i_opcnamespace;
5256         int                     i_rolname;
5257
5258         /*
5259          * find all opclasses, including builtin opclasses; we filter out
5260          * system-defined opclasses at dump-out time.
5261          */
5262
5263         appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
5264                                           "opcnamespace, "
5265                                           "(%s opcowner) AS rolname "
5266                                           "FROM pg_opclass",
5267                                           username_subquery);
5268
5269         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5270
5271         ntups = PQntuples(res);
5272         *numOpclasses = ntups;
5273
5274         opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
5275
5276         i_tableoid = PQfnumber(res, "tableoid");
5277         i_oid = PQfnumber(res, "oid");
5278         i_opcname = PQfnumber(res, "opcname");
5279         i_opcnamespace = PQfnumber(res, "opcnamespace");
5280         i_rolname = PQfnumber(res, "rolname");
5281
5282         for (i = 0; i < ntups; i++)
5283         {
5284                 opcinfo[i].dobj.objType = DO_OPCLASS;
5285                 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5286                 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5287                 AssignDumpId(&opcinfo[i].dobj);
5288                 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
5289                 opcinfo[i].dobj.namespace =
5290                         findNamespace(fout,
5291                                                   atooid(PQgetvalue(res, i, i_opcnamespace)));
5292                 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5293
5294                 /* Decide whether we want to dump it */
5295                 selectDumpableObject(&(opcinfo[i].dobj), fout);
5296
5297                 /* Op Classes do not currently have ACLs. */
5298                 opcinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5299
5300                 if (strlen(opcinfo[i].rolname) == 0)
5301                         write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
5302                                           opcinfo[i].dobj.name);
5303         }
5304
5305         PQclear(res);
5306
5307         destroyPQExpBuffer(query);
5308
5309         return opcinfo;
5310 }
5311
5312 /*
5313  * getOpfamilies:
5314  *        read all opfamilies in the system catalogs and return them in the
5315  * OpfamilyInfo* structure
5316  *
5317  *      numOpfamilies is set to the number of opfamilies read in
5318  */
5319 OpfamilyInfo *
5320 getOpfamilies(Archive *fout, int *numOpfamilies)
5321 {
5322         PGresult   *res;
5323         int                     ntups;
5324         int                     i;
5325         PQExpBuffer query;
5326         OpfamilyInfo *opfinfo;
5327         int                     i_tableoid;
5328         int                     i_oid;
5329         int                     i_opfname;
5330         int                     i_opfnamespace;
5331         int                     i_rolname;
5332
5333         /* Before 8.3, there is no separate concept of opfamilies */
5334         if (fout->remoteVersion < 80300)
5335         {
5336                 *numOpfamilies = 0;
5337                 return NULL;
5338         }
5339
5340         query = createPQExpBuffer();
5341
5342         /*
5343          * find all opfamilies, including builtin opfamilies; we filter out
5344          * system-defined opfamilies at dump-out time.
5345          */
5346
5347         appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
5348                                           "opfnamespace, "
5349                                           "(%s opfowner) AS rolname "
5350                                           "FROM pg_opfamily",
5351                                           username_subquery);
5352
5353         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5354
5355         ntups = PQntuples(res);
5356         *numOpfamilies = ntups;
5357
5358         opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
5359
5360         i_tableoid = PQfnumber(res, "tableoid");
5361         i_oid = PQfnumber(res, "oid");
5362         i_opfname = PQfnumber(res, "opfname");
5363         i_opfnamespace = PQfnumber(res, "opfnamespace");
5364         i_rolname = PQfnumber(res, "rolname");
5365
5366         for (i = 0; i < ntups; i++)
5367         {
5368                 opfinfo[i].dobj.objType = DO_OPFAMILY;
5369                 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5370                 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5371                 AssignDumpId(&opfinfo[i].dobj);
5372                 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
5373                 opfinfo[i].dobj.namespace =
5374                         findNamespace(fout,
5375                                                   atooid(PQgetvalue(res, i, i_opfnamespace)));
5376                 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5377
5378                 /* Decide whether we want to dump it */
5379                 selectDumpableObject(&(opfinfo[i].dobj), fout);
5380
5381                 /* Extensions do not currently have ACLs. */
5382                 opfinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5383
5384                 if (strlen(opfinfo[i].rolname) == 0)
5385                         write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
5386                                           opfinfo[i].dobj.name);
5387         }
5388
5389         PQclear(res);
5390
5391         destroyPQExpBuffer(query);
5392
5393         return opfinfo;
5394 }
5395
5396 /*
5397  * getAggregates:
5398  *        read all the user-defined aggregates in the system catalogs and
5399  * return them in the AggInfo* structure
5400  *
5401  * numAggs is set to the number of aggregates read in
5402  */
5403 AggInfo *
5404 getAggregates(Archive *fout, int *numAggs)
5405 {
5406         DumpOptions *dopt = fout->dopt;
5407         PGresult   *res;
5408         int                     ntups;
5409         int                     i;
5410         PQExpBuffer query = createPQExpBuffer();
5411         AggInfo    *agginfo;
5412         int                     i_tableoid;
5413         int                     i_oid;
5414         int                     i_aggname;
5415         int                     i_aggnamespace;
5416         int                     i_pronargs;
5417         int                     i_proargtypes;
5418         int                     i_rolname;
5419         int                     i_aggacl;
5420         int                     i_raggacl;
5421         int                     i_initaggacl;
5422         int                     i_initraggacl;
5423
5424         /*
5425          * Find all interesting aggregates.  See comment in getFuncs() for the
5426          * rationale behind the filtering logic.
5427          */
5428         if (fout->remoteVersion >= 90600)
5429         {
5430                 PQExpBuffer acl_subquery = createPQExpBuffer();
5431                 PQExpBuffer racl_subquery = createPQExpBuffer();
5432                 PQExpBuffer initacl_subquery = createPQExpBuffer();
5433                 PQExpBuffer initracl_subquery = createPQExpBuffer();
5434                 const char *agg_check;
5435
5436                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5437                                                 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5438                                                 dopt->binary_upgrade);
5439
5440                 agg_check = (fout->remoteVersion >= 110000 ? "p.prokind = 'a'"
5441                                          : "p.proisagg");
5442
5443                 appendPQExpBuffer(query, "SELECT p.tableoid, p.oid, "
5444                                                   "p.proname AS aggname, "
5445                                                   "p.pronamespace AS aggnamespace, "
5446                                                   "p.pronargs, p.proargtypes, "
5447                                                   "(%s p.proowner) AS rolname, "
5448                                                   "%s AS aggacl, "
5449                                                   "%s AS raggacl, "
5450                                                   "%s AS initaggacl, "
5451                                                   "%s AS initraggacl "
5452                                                   "FROM pg_proc p "
5453                                                   "LEFT JOIN pg_init_privs pip ON "
5454                                                   "(p.oid = pip.objoid "
5455                                                   "AND pip.classoid = 'pg_proc'::regclass "
5456                                                   "AND pip.objsubid = 0) "
5457                                                   "WHERE %s AND ("
5458                                                   "p.pronamespace != "
5459                                                   "(SELECT oid FROM pg_namespace "
5460                                                   "WHERE nspname = 'pg_catalog') OR "
5461                                                   "p.proacl IS DISTINCT FROM pip.initprivs",
5462                                                   username_subquery,
5463                                                   acl_subquery->data,
5464                                                   racl_subquery->data,
5465                                                   initacl_subquery->data,
5466                                                   initracl_subquery->data,
5467                                                   agg_check);
5468                 if (dopt->binary_upgrade)
5469                         appendPQExpBufferStr(query,
5470                                                                  " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5471                                                                  "classid = 'pg_proc'::regclass AND "
5472                                                                  "objid = p.oid AND "
5473                                                                  "refclassid = 'pg_extension'::regclass AND "
5474                                                                  "deptype = 'e')");
5475                 appendPQExpBufferChar(query, ')');
5476
5477                 destroyPQExpBuffer(acl_subquery);
5478                 destroyPQExpBuffer(racl_subquery);
5479                 destroyPQExpBuffer(initacl_subquery);
5480                 destroyPQExpBuffer(initracl_subquery);
5481         }
5482         else if (fout->remoteVersion >= 80200)
5483         {
5484                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5485                                                   "pronamespace AS aggnamespace, "
5486                                                   "pronargs, proargtypes, "
5487                                                   "(%s proowner) AS rolname, "
5488                                                   "proacl AS aggacl, "
5489                                                   "NULL AS raggacl, "
5490                                                   "NULL AS initaggacl, NULL AS initraggacl "
5491                                                   "FROM pg_proc p "
5492                                                   "WHERE proisagg AND ("
5493                                                   "pronamespace != "
5494                                                   "(SELECT oid FROM pg_namespace "
5495                                                   "WHERE nspname = 'pg_catalog')",
5496                                                   username_subquery);
5497                 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5498                         appendPQExpBufferStr(query,
5499                                                                  " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5500                                                                  "classid = 'pg_proc'::regclass AND "
5501                                                                  "objid = p.oid AND "
5502                                                                  "refclassid = 'pg_extension'::regclass AND "
5503                                                                  "deptype = 'e')");
5504                 appendPQExpBufferChar(query, ')');
5505         }
5506         else
5507         {
5508                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5509                                                   "pronamespace AS aggnamespace, "
5510                                                   "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
5511                                                   "proargtypes, "
5512                                                   "(%s proowner) AS rolname, "
5513                                                   "proacl AS aggacl, "
5514                                                   "NULL AS raggacl, "
5515                                                   "NULL AS initaggacl, NULL AS initraggacl "
5516                                                   "FROM pg_proc "
5517                                                   "WHERE proisagg "
5518                                                   "AND pronamespace != "
5519                                                   "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
5520                                                   username_subquery);
5521         }
5522
5523         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5524
5525         ntups = PQntuples(res);
5526         *numAggs = ntups;
5527
5528         agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
5529
5530         i_tableoid = PQfnumber(res, "tableoid");
5531         i_oid = PQfnumber(res, "oid");
5532         i_aggname = PQfnumber(res, "aggname");
5533         i_aggnamespace = PQfnumber(res, "aggnamespace");
5534         i_pronargs = PQfnumber(res, "pronargs");
5535         i_proargtypes = PQfnumber(res, "proargtypes");
5536         i_rolname = PQfnumber(res, "rolname");
5537         i_aggacl = PQfnumber(res, "aggacl");
5538         i_raggacl = PQfnumber(res, "raggacl");
5539         i_initaggacl = PQfnumber(res, "initaggacl");
5540         i_initraggacl = PQfnumber(res, "initraggacl");
5541
5542         for (i = 0; i < ntups; i++)
5543         {
5544                 agginfo[i].aggfn.dobj.objType = DO_AGG;
5545                 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5546                 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5547                 AssignDumpId(&agginfo[i].aggfn.dobj);
5548                 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
5549                 agginfo[i].aggfn.dobj.namespace =
5550                         findNamespace(fout,
5551                                                   atooid(PQgetvalue(res, i, i_aggnamespace)));
5552                 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5553                 if (strlen(agginfo[i].aggfn.rolname) == 0)
5554                         write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
5555                                           agginfo[i].aggfn.dobj.name);
5556                 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
5557                 agginfo[i].aggfn.prorettype = InvalidOid;       /* not saved */
5558                 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
5559                 agginfo[i].aggfn.rproacl = pg_strdup(PQgetvalue(res, i, i_raggacl));
5560                 agginfo[i].aggfn.initproacl = pg_strdup(PQgetvalue(res, i, i_initaggacl));
5561                 agginfo[i].aggfn.initrproacl = pg_strdup(PQgetvalue(res, i, i_initraggacl));
5562                 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
5563                 if (agginfo[i].aggfn.nargs == 0)
5564                         agginfo[i].aggfn.argtypes = NULL;
5565                 else
5566                 {
5567                         agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
5568                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
5569                                                   agginfo[i].aggfn.argtypes,
5570                                                   agginfo[i].aggfn.nargs);
5571                 }
5572
5573                 /* Decide whether we want to dump it */
5574                 selectDumpableObject(&(agginfo[i].aggfn.dobj), fout);
5575
5576                 /* Do not try to dump ACL if no ACL exists. */
5577                 if (PQgetisnull(res, i, i_aggacl) && PQgetisnull(res, i, i_raggacl) &&
5578                         PQgetisnull(res, i, i_initaggacl) &&
5579                         PQgetisnull(res, i, i_initraggacl))
5580                         agginfo[i].aggfn.dobj.dump &= ~DUMP_COMPONENT_ACL;
5581         }
5582
5583         PQclear(res);
5584
5585         destroyPQExpBuffer(query);
5586
5587         return agginfo;
5588 }
5589
5590 /*
5591  * getFuncs:
5592  *        read all the user-defined functions in the system catalogs and
5593  * return them in the FuncInfo* structure
5594  *
5595  * numFuncs is set to the number of functions read in
5596  */
5597 FuncInfo *
5598 getFuncs(Archive *fout, int *numFuncs)
5599 {
5600         DumpOptions *dopt = fout->dopt;
5601         PGresult   *res;
5602         int                     ntups;
5603         int                     i;
5604         PQExpBuffer query = createPQExpBuffer();
5605         FuncInfo   *finfo;
5606         int                     i_tableoid;
5607         int                     i_oid;
5608         int                     i_proname;
5609         int                     i_pronamespace;
5610         int                     i_rolname;
5611         int                     i_prolang;
5612         int                     i_pronargs;
5613         int                     i_proargtypes;
5614         int                     i_prorettype;
5615         int                     i_proacl;
5616         int                     i_rproacl;
5617         int                     i_initproacl;
5618         int                     i_initrproacl;
5619
5620         /*
5621          * Find all interesting functions.  This is a bit complicated:
5622          *
5623          * 1. Always exclude aggregates; those are handled elsewhere.
5624          *
5625          * 2. Always exclude functions that are internally dependent on something
5626          * else, since presumably those will be created as a result of creating
5627          * the something else.  This currently acts only to suppress constructor
5628          * functions for range types (so we only need it in 9.2 and up).  Note
5629          * this is OK only because the constructors don't have any dependencies
5630          * the range type doesn't have; otherwise we might not get creation
5631          * ordering correct.
5632          *
5633          * 3. Otherwise, we normally exclude functions in pg_catalog.  However, if
5634          * they're members of extensions and we are in binary-upgrade mode then
5635          * include them, since we want to dump extension members individually in
5636          * that mode.  Also, if they are used by casts or transforms then we need
5637          * to gather the information about them, though they won't be dumped if
5638          * they are built-in.  Also, in 9.6 and up, include functions in
5639          * pg_catalog if they have an ACL different from what's shown in
5640          * pg_init_privs.
5641          */
5642         if (fout->remoteVersion >= 90600)
5643         {
5644                 PQExpBuffer acl_subquery = createPQExpBuffer();
5645                 PQExpBuffer racl_subquery = createPQExpBuffer();
5646                 PQExpBuffer initacl_subquery = createPQExpBuffer();
5647                 PQExpBuffer initracl_subquery = createPQExpBuffer();
5648                 const char *not_agg_check;
5649
5650                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5651                                                 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5652                                                 dopt->binary_upgrade);
5653
5654                 not_agg_check = (fout->remoteVersion >= 110000 ? "p.prokind <> 'a'"
5655                                                  : "NOT p.proisagg");
5656
5657                 appendPQExpBuffer(query,
5658                                                   "SELECT p.tableoid, p.oid, p.proname, p.prolang, "
5659                                                   "p.pronargs, p.proargtypes, p.prorettype, "
5660                                                   "%s AS proacl, "
5661                                                   "%s AS rproacl, "
5662                                                   "%s AS initproacl, "
5663                                                   "%s AS initrproacl, "
5664                                                   "p.pronamespace, "
5665                                                   "(%s p.proowner) AS rolname "
5666                                                   "FROM pg_proc p "
5667                                                   "LEFT JOIN pg_init_privs pip ON "
5668                                                   "(p.oid = pip.objoid "
5669                                                   "AND pip.classoid = 'pg_proc'::regclass "
5670                                                   "AND pip.objsubid = 0) "
5671                                                   "WHERE %s"
5672                                                   "\n  AND NOT EXISTS (SELECT 1 FROM pg_depend "
5673                                                   "WHERE classid = 'pg_proc'::regclass AND "
5674                                                   "objid = p.oid AND deptype = 'i')"
5675                                                   "\n  AND ("
5676                                                   "\n  pronamespace != "
5677                                                   "(SELECT oid FROM pg_namespace "
5678                                                   "WHERE nspname = 'pg_catalog')"
5679                                                   "\n  OR EXISTS (SELECT 1 FROM pg_cast"
5680                                                   "\n  WHERE pg_cast.oid > %u "
5681                                                   "\n  AND p.oid = pg_cast.castfunc)"
5682                                                   "\n  OR EXISTS (SELECT 1 FROM pg_transform"
5683                                                   "\n  WHERE pg_transform.oid > %u AND "
5684                                                   "\n  (p.oid = pg_transform.trffromsql"
5685                                                   "\n  OR p.oid = pg_transform.trftosql))",
5686                                                   acl_subquery->data,
5687                                                   racl_subquery->data,
5688                                                   initacl_subquery->data,
5689                                                   initracl_subquery->data,
5690                                                   username_subquery,
5691                                                   not_agg_check,
5692                                                   g_last_builtin_oid,
5693                                                   g_last_builtin_oid);
5694                 if (dopt->binary_upgrade)
5695                         appendPQExpBufferStr(query,
5696                                                                  "\n  OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5697                                                                  "classid = 'pg_proc'::regclass AND "
5698                                                                  "objid = p.oid AND "
5699                                                                  "refclassid = 'pg_extension'::regclass AND "
5700                                                                  "deptype = 'e')");
5701                 appendPQExpBufferStr(query,
5702                                                          "\n  OR p.proacl IS DISTINCT FROM pip.initprivs");
5703                 appendPQExpBufferChar(query, ')');
5704
5705                 destroyPQExpBuffer(acl_subquery);
5706                 destroyPQExpBuffer(racl_subquery);
5707                 destroyPQExpBuffer(initacl_subquery);
5708                 destroyPQExpBuffer(initracl_subquery);
5709         }
5710         else
5711         {
5712                 appendPQExpBuffer(query,
5713                                                   "SELECT tableoid, oid, proname, prolang, "
5714                                                   "pronargs, proargtypes, prorettype, proacl, "
5715                                                   "NULL as rproacl, "
5716                                                   "NULL as initproacl, NULL AS initrproacl, "
5717                                                   "pronamespace, "
5718                                                   "(%s proowner) AS rolname "
5719                                                   "FROM pg_proc p "
5720                                                   "WHERE NOT proisagg",
5721                                                   username_subquery);
5722                 if (fout->remoteVersion >= 90200)
5723                         appendPQExpBufferStr(query,
5724                                                                  "\n  AND NOT EXISTS (SELECT 1 FROM pg_depend "
5725                                                                  "WHERE classid = 'pg_proc'::regclass AND "
5726                                                                  "objid = p.oid AND deptype = 'i')");
5727                 appendPQExpBuffer(query,
5728                                                   "\n  AND ("
5729                                                   "\n  pronamespace != "
5730                                                   "(SELECT oid FROM pg_namespace "
5731                                                   "WHERE nspname = 'pg_catalog')"
5732                                                   "\n  OR EXISTS (SELECT 1 FROM pg_cast"
5733                                                   "\n  WHERE pg_cast.oid > '%u'::oid"
5734                                                   "\n  AND p.oid = pg_cast.castfunc)",
5735                                                   g_last_builtin_oid);
5736
5737                 if (fout->remoteVersion >= 90500)
5738                         appendPQExpBuffer(query,
5739                                                           "\n  OR EXISTS (SELECT 1 FROM pg_transform"
5740                                                           "\n  WHERE pg_transform.oid > '%u'::oid"
5741                                                           "\n  AND (p.oid = pg_transform.trffromsql"
5742                                                           "\n  OR p.oid = pg_transform.trftosql))",
5743                                                           g_last_builtin_oid);
5744
5745                 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5746                         appendPQExpBufferStr(query,
5747                                                                  "\n  OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5748                                                                  "classid = 'pg_proc'::regclass AND "
5749                                                                  "objid = p.oid AND "
5750                                                                  "refclassid = 'pg_extension'::regclass AND "
5751                                                                  "deptype = 'e')");
5752                 appendPQExpBufferChar(query, ')');
5753         }
5754
5755         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5756
5757         ntups = PQntuples(res);
5758
5759         *numFuncs = ntups;
5760
5761         finfo = (FuncInfo *) pg_malloc0(ntups * sizeof(FuncInfo));
5762
5763         i_tableoid = PQfnumber(res, "tableoid");
5764         i_oid = PQfnumber(res, "oid");
5765         i_proname = PQfnumber(res, "proname");
5766         i_pronamespace = PQfnumber(res, "pronamespace");
5767         i_rolname = PQfnumber(res, "rolname");
5768         i_prolang = PQfnumber(res, "prolang");
5769         i_pronargs = PQfnumber(res, "pronargs");
5770         i_proargtypes = PQfnumber(res, "proargtypes");
5771         i_prorettype = PQfnumber(res, "prorettype");
5772         i_proacl = PQfnumber(res, "proacl");
5773         i_rproacl = PQfnumber(res, "rproacl");
5774         i_initproacl = PQfnumber(res, "initproacl");
5775         i_initrproacl = PQfnumber(res, "initrproacl");
5776
5777         for (i = 0; i < ntups; i++)
5778         {
5779                 finfo[i].dobj.objType = DO_FUNC;
5780                 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5781                 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5782                 AssignDumpId(&finfo[i].dobj);
5783                 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
5784                 finfo[i].dobj.namespace =
5785                         findNamespace(fout,
5786                                                   atooid(PQgetvalue(res, i, i_pronamespace)));
5787                 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5788                 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
5789                 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
5790                 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
5791                 finfo[i].rproacl = pg_strdup(PQgetvalue(res, i, i_rproacl));
5792                 finfo[i].initproacl = pg_strdup(PQgetvalue(res, i, i_initproacl));
5793                 finfo[i].initrproacl = pg_strdup(PQgetvalue(res, i, i_initrproacl));
5794                 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
5795                 if (finfo[i].nargs == 0)
5796                         finfo[i].argtypes = NULL;
5797                 else
5798                 {
5799                         finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
5800                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
5801                                                   finfo[i].argtypes, finfo[i].nargs);
5802                 }
5803
5804                 /* Decide whether we want to dump it */
5805                 selectDumpableObject(&(finfo[i].dobj), fout);
5806
5807                 /* Do not try to dump ACL if no ACL exists. */
5808                 if (PQgetisnull(res, i, i_proacl) && PQgetisnull(res, i, i_rproacl) &&
5809                         PQgetisnull(res, i, i_initproacl) &&
5810                         PQgetisnull(res, i, i_initrproacl))
5811                         finfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5812
5813                 if (strlen(finfo[i].rolname) == 0)
5814                         write_msg(NULL,
5815                                           "WARNING: owner of function \"%s\" appears to be invalid\n",
5816                                           finfo[i].dobj.name);
5817         }
5818
5819         PQclear(res);
5820
5821         destroyPQExpBuffer(query);
5822
5823         return finfo;
5824 }
5825
5826 /*
5827  * getTables
5828  *        read all the tables (no indexes)
5829  * in the system catalogs return them in the TableInfo* structure
5830  *
5831  * numTables is set to the number of tables read in
5832  */
5833 TableInfo *
5834 getTables(Archive *fout, int *numTables)
5835 {
5836         DumpOptions *dopt = fout->dopt;
5837         PGresult   *res;
5838         int                     ntups;
5839         int                     i;
5840         PQExpBuffer query = createPQExpBuffer();
5841         TableInfo  *tblinfo;
5842         int                     i_reltableoid;
5843         int                     i_reloid;
5844         int                     i_relname;
5845         int                     i_relnamespace;
5846         int                     i_relkind;
5847         int                     i_relacl;
5848         int                     i_rrelacl;
5849         int                     i_initrelacl;
5850         int                     i_initrrelacl;
5851         int                     i_rolname;
5852         int                     i_relchecks;
5853         int                     i_relhastriggers;
5854         int                     i_relhasindex;
5855         int                     i_relhasrules;
5856         int                     i_relrowsec;
5857         int                     i_relforcerowsec;
5858         int                     i_relhasoids;
5859         int                     i_relfrozenxid;
5860         int                     i_relminmxid;
5861         int                     i_toastoid;
5862         int                     i_toastfrozenxid;
5863         int                     i_toastminmxid;
5864         int                     i_relpersistence;
5865         int                     i_relispopulated;
5866         int                     i_relreplident;
5867         int                     i_owning_tab;
5868         int                     i_owning_col;
5869         int                     i_reltablespace;
5870         int                     i_reloptions;
5871         int                     i_checkoption;
5872         int                     i_toastreloptions;
5873         int                     i_reloftype;
5874         int                     i_relpages;
5875         int                     i_is_identity_sequence;
5876         int                     i_changed_acl;
5877         int                     i_partkeydef;
5878         int                     i_ispartition;
5879         int                     i_partbound;
5880
5881         /*
5882          * Find all the tables and table-like objects.
5883          *
5884          * We include system catalogs, so that we can work if a user table is
5885          * defined to inherit from a system catalog (pretty weird, but...)
5886          *
5887          * We ignore relations that are not ordinary tables, sequences, views,
5888          * materialized views, composite types, or foreign tables.
5889          *
5890          * Composite-type table entries won't be dumped as such, but we have to
5891          * make a DumpableObject for them so that we can track dependencies of the
5892          * composite type (pg_depend entries for columns of the composite type
5893          * link to the pg_class entry not the pg_type entry).
5894          *
5895          * Note: in this phase we should collect only a minimal amount of
5896          * information about each table, basically just enough to decide if it is
5897          * interesting. We must fetch all tables in this phase because otherwise
5898          * we cannot correctly identify inherited columns, owned sequences, etc.
5899          */
5900
5901         if (fout->remoteVersion >= 90600)
5902         {
5903                 char       *partkeydef = "NULL";
5904                 char       *ispartition = "false";
5905                 char       *partbound = "NULL";
5906
5907                 PQExpBuffer acl_subquery = createPQExpBuffer();
5908                 PQExpBuffer racl_subquery = createPQExpBuffer();
5909                 PQExpBuffer initacl_subquery = createPQExpBuffer();
5910                 PQExpBuffer initracl_subquery = createPQExpBuffer();
5911
5912                 PQExpBuffer attacl_subquery = createPQExpBuffer();
5913                 PQExpBuffer attracl_subquery = createPQExpBuffer();
5914                 PQExpBuffer attinitacl_subquery = createPQExpBuffer();
5915                 PQExpBuffer attinitracl_subquery = createPQExpBuffer();
5916
5917                 /*
5918                  * Collect the information about any partitioned tables, which were
5919                  * added in PG10.
5920                  */
5921
5922                 if (fout->remoteVersion >= 100000)
5923                 {
5924                         partkeydef = "pg_get_partkeydef(c.oid)";
5925                         ispartition = "c.relispartition";
5926                         partbound = "pg_get_expr(c.relpartbound, c.oid)";
5927                 }
5928
5929                 /*
5930                  * Left join to pick up dependency info linking sequences to their
5931                  * owning column, if any (note this dependency is AUTO as of 8.2)
5932                  *
5933                  * Left join to detect if any privileges are still as-set-at-init, in
5934                  * which case we won't dump out ACL commands for those.
5935                  */
5936
5937                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5938                                                 initracl_subquery, "c.relacl", "c.relowner",
5939                                                 "CASE WHEN c.relkind = " CppAsString2(RELKIND_SEQUENCE)
5940                                                 " THEN 's' ELSE 'r' END::\"char\"",
5941                                                 dopt->binary_upgrade);
5942
5943                 buildACLQueries(attacl_subquery, attracl_subquery, attinitacl_subquery,
5944                                                 attinitracl_subquery, "at.attacl", "c.relowner", "'c'",
5945                                                 dopt->binary_upgrade);
5946
5947                 appendPQExpBuffer(query,
5948                                                   "SELECT c.tableoid, c.oid, c.relname, "
5949                                                   "%s AS relacl, %s as rrelacl, "
5950                                                   "%s AS initrelacl, %s as initrrelacl, "
5951                                                   "c.relkind, c.relnamespace, "
5952                                                   "(%s c.relowner) AS rolname, "
5953                                                   "c.relchecks, c.relhastriggers, "
5954                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
5955                                                   "c.relrowsecurity, c.relforcerowsecurity, "
5956                                                   "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
5957                                                   "tc.relfrozenxid AS tfrozenxid, "
5958                                                   "tc.relminmxid AS tminmxid, "
5959                                                   "c.relpersistence, c.relispopulated, "
5960                                                   "c.relreplident, c.relpages, "
5961                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
5962                                                   "d.refobjid AS owning_tab, "
5963                                                   "d.refobjsubid AS owning_col, "
5964                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5965                                                   "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
5966                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
5967                                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
5968                                                   "tc.reloptions AS toast_reloptions, "
5969                                                   "c.relkind = '%c' AND EXISTS (SELECT 1 FROM pg_depend WHERE classid = 'pg_class'::regclass AND objid = c.oid AND objsubid = 0 AND refclassid = 'pg_class'::regclass AND deptype = 'i') AS is_identity_sequence, "
5970                                                   "EXISTS (SELECT 1 FROM pg_attribute at LEFT JOIN pg_init_privs pip ON "
5971                                                   "(c.oid = pip.objoid "
5972                                                   "AND pip.classoid = 'pg_class'::regclass "
5973                                                   "AND pip.objsubid = at.attnum)"
5974                                                   "WHERE at.attrelid = c.oid AND ("
5975                                                   "%s IS NOT NULL "
5976                                                   "OR %s IS NOT NULL "
5977                                                   "OR %s IS NOT NULL "
5978                                                   "OR %s IS NOT NULL"
5979                                                   "))"
5980                                                   "AS changed_acl, "
5981                                                   "%s AS partkeydef, "
5982                                                   "%s AS ispartition, "
5983                                                   "%s AS partbound "
5984                                                   "FROM pg_class c "
5985                                                   "LEFT JOIN pg_depend d ON "
5986                                                   "(c.relkind = '%c' AND "
5987                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
5988                                                   "d.objsubid = 0 AND "
5989                                                   "d.refclassid = c.tableoid AND d.deptype IN ('a', 'i')) "
5990                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5991                                                   "LEFT JOIN pg_init_privs pip ON "
5992                                                   "(c.oid = pip.objoid "
5993                                                   "AND pip.classoid = 'pg_class'::regclass "
5994                                                   "AND pip.objsubid = 0) "
5995                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c', '%c') "
5996                                                   "ORDER BY c.oid",
5997                                                   acl_subquery->data,
5998                                                   racl_subquery->data,
5999                                                   initacl_subquery->data,
6000                                                   initracl_subquery->data,
6001                                                   username_subquery,
6002                                                   RELKIND_SEQUENCE,
6003                                                   attacl_subquery->data,
6004                                                   attracl_subquery->data,
6005                                                   attinitacl_subquery->data,
6006                                                   attinitracl_subquery->data,
6007                                                   partkeydef,
6008                                                   ispartition,
6009                                                   partbound,
6010                                                   RELKIND_SEQUENCE,
6011                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6012                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6013                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
6014                                                   RELKIND_PARTITIONED_TABLE);
6015
6016                 destroyPQExpBuffer(acl_subquery);
6017                 destroyPQExpBuffer(racl_subquery);
6018                 destroyPQExpBuffer(initacl_subquery);
6019                 destroyPQExpBuffer(initracl_subquery);
6020
6021                 destroyPQExpBuffer(attacl_subquery);
6022                 destroyPQExpBuffer(attracl_subquery);
6023                 destroyPQExpBuffer(attinitacl_subquery);
6024                 destroyPQExpBuffer(attinitracl_subquery);
6025         }
6026         else if (fout->remoteVersion >= 90500)
6027         {
6028                 /*
6029                  * Left join to pick up dependency info linking sequences to their
6030                  * owning column, if any (note this dependency is AUTO as of 8.2)
6031                  */
6032                 appendPQExpBuffer(query,
6033                                                   "SELECT c.tableoid, c.oid, c.relname, "
6034                                                   "c.relacl, NULL as rrelacl, "
6035                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6036                                                   "c.relkind, "
6037                                                   "c.relnamespace, "
6038                                                   "(%s c.relowner) AS rolname, "
6039                                                   "c.relchecks, c.relhastriggers, "
6040                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6041                                                   "c.relrowsecurity, c.relforcerowsecurity, "
6042                                                   "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6043                                                   "tc.relfrozenxid AS tfrozenxid, "
6044                                                   "tc.relminmxid AS tminmxid, "
6045                                                   "c.relpersistence, c.relispopulated, "
6046                                                   "c.relreplident, c.relpages, "
6047                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6048                                                   "d.refobjid AS owning_tab, "
6049                                                   "d.refobjsubid AS owning_col, "
6050                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6051                                                   "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6052                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6053                                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6054                                                   "tc.reloptions AS toast_reloptions, "
6055                                                   "NULL AS changed_acl, "
6056                                                   "NULL AS partkeydef, "
6057                                                   "false AS ispartition, "
6058                                                   "NULL AS partbound "
6059                                                   "FROM pg_class c "
6060                                                   "LEFT JOIN pg_depend d ON "
6061                                                   "(c.relkind = '%c' AND "
6062                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6063                                                   "d.objsubid = 0 AND "
6064                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6065                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6066                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6067                                                   "ORDER BY c.oid",
6068                                                   username_subquery,
6069                                                   RELKIND_SEQUENCE,
6070                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6071                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6072                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6073         }
6074         else if (fout->remoteVersion >= 90400)
6075         {
6076                 /*
6077                  * Left join to pick up dependency info linking sequences to their
6078                  * owning column, if any (note this dependency is AUTO as of 8.2)
6079                  */
6080                 appendPQExpBuffer(query,
6081                                                   "SELECT c.tableoid, c.oid, c.relname, "
6082                                                   "c.relacl, NULL as rrelacl, "
6083                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6084                                                   "c.relkind, "
6085                                                   "c.relnamespace, "
6086                                                   "(%s c.relowner) AS rolname, "
6087                                                   "c.relchecks, c.relhastriggers, "
6088                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6089                                                   "'f'::bool AS relrowsecurity, "
6090                                                   "'f'::bool AS relforcerowsecurity, "
6091                                                   "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6092                                                   "tc.relfrozenxid AS tfrozenxid, "
6093                                                   "tc.relminmxid AS tminmxid, "
6094                                                   "c.relpersistence, c.relispopulated, "
6095                                                   "c.relreplident, c.relpages, "
6096                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6097                                                   "d.refobjid AS owning_tab, "
6098                                                   "d.refobjsubid AS owning_col, "
6099                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6100                                                   "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6101                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6102                                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6103                                                   "tc.reloptions AS toast_reloptions, "
6104                                                   "NULL AS changed_acl, "
6105                                                   "NULL AS partkeydef, "
6106                                                   "false AS ispartition, "
6107                                                   "NULL AS partbound "
6108                                                   "FROM pg_class c "
6109                                                   "LEFT JOIN pg_depend d ON "
6110                                                   "(c.relkind = '%c' AND "
6111                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6112                                                   "d.objsubid = 0 AND "
6113                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6114                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6115                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6116                                                   "ORDER BY c.oid",
6117                                                   username_subquery,
6118                                                   RELKIND_SEQUENCE,
6119                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6120                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6121                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6122         }
6123         else if (fout->remoteVersion >= 90300)
6124         {
6125                 /*
6126                  * Left join to pick up dependency info linking sequences to their
6127                  * owning column, if any (note this dependency is AUTO as of 8.2)
6128                  */
6129                 appendPQExpBuffer(query,
6130                                                   "SELECT c.tableoid, c.oid, c.relname, "
6131                                                   "c.relacl, NULL as rrelacl, "
6132                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6133                                                   "c.relkind, "
6134                                                   "c.relnamespace, "
6135                                                   "(%s c.relowner) AS rolname, "
6136                                                   "c.relchecks, c.relhastriggers, "
6137                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6138                                                   "'f'::bool AS relrowsecurity, "
6139                                                   "'f'::bool AS relforcerowsecurity, "
6140                                                   "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6141                                                   "tc.relfrozenxid AS tfrozenxid, "
6142                                                   "tc.relminmxid AS tminmxid, "
6143                                                   "c.relpersistence, c.relispopulated, "
6144                                                   "'d' AS relreplident, c.relpages, "
6145                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6146                                                   "d.refobjid AS owning_tab, "
6147                                                   "d.refobjsubid AS owning_col, "
6148                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6149                                                   "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6150                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6151                                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6152                                                   "tc.reloptions AS toast_reloptions, "
6153                                                   "NULL AS changed_acl, "
6154                                                   "NULL AS partkeydef, "
6155                                                   "false AS ispartition, "
6156                                                   "NULL AS partbound "
6157                                                   "FROM pg_class c "
6158                                                   "LEFT JOIN pg_depend d ON "
6159                                                   "(c.relkind = '%c' AND "
6160                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6161                                                   "d.objsubid = 0 AND "
6162                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6163                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6164                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6165                                                   "ORDER BY c.oid",
6166                                                   username_subquery,
6167                                                   RELKIND_SEQUENCE,
6168                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6169                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6170                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6171         }
6172         else if (fout->remoteVersion >= 90100)
6173         {
6174                 /*
6175                  * Left join to pick up dependency info linking sequences to their
6176                  * owning column, if any (note this dependency is AUTO as of 8.2)
6177                  */
6178                 appendPQExpBuffer(query,
6179                                                   "SELECT c.tableoid, c.oid, c.relname, "
6180                                                   "c.relacl, NULL as rrelacl, "
6181                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6182                                                   "c.relkind, "
6183                                                   "c.relnamespace, "
6184                                                   "(%s c.relowner) AS rolname, "
6185                                                   "c.relchecks, c.relhastriggers, "
6186                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6187                                                   "'f'::bool AS relrowsecurity, "
6188                                                   "'f'::bool AS relforcerowsecurity, "
6189                                                   "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6190                                                   "tc.relfrozenxid AS tfrozenxid, "
6191                                                   "0 AS tminmxid, "
6192                                                   "c.relpersistence, 't' as relispopulated, "
6193                                                   "'d' AS relreplident, c.relpages, "
6194                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6195                                                   "d.refobjid AS owning_tab, "
6196                                                   "d.refobjsubid AS owning_col, "
6197                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6198                                                   "c.reloptions AS reloptions, "
6199                                                   "tc.reloptions AS toast_reloptions, "
6200                                                   "NULL AS changed_acl, "
6201                                                   "NULL AS partkeydef, "
6202                                                   "false AS ispartition, "
6203                                                   "NULL AS partbound "
6204                                                   "FROM pg_class c "
6205                                                   "LEFT JOIN pg_depend d ON "
6206                                                   "(c.relkind = '%c' AND "
6207                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6208                                                   "d.objsubid = 0 AND "
6209                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6210                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6211                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6212                                                   "ORDER BY c.oid",
6213                                                   username_subquery,
6214                                                   RELKIND_SEQUENCE,
6215                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6216                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
6217                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
6218         }
6219         else if (fout->remoteVersion >= 90000)
6220         {
6221                 /*
6222                  * Left join to pick up dependency info linking sequences to their
6223                  * owning column, if any (note this dependency is AUTO as of 8.2)
6224                  */
6225                 appendPQExpBuffer(query,
6226                                                   "SELECT c.tableoid, c.oid, c.relname, "
6227                                                   "c.relacl, NULL as rrelacl, "
6228                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6229                                                   "c.relkind, "
6230                                                   "c.relnamespace, "
6231                                                   "(%s c.relowner) AS rolname, "
6232                                                   "c.relchecks, c.relhastriggers, "
6233                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6234                                                   "'f'::bool AS relrowsecurity, "
6235                                                   "'f'::bool AS relforcerowsecurity, "
6236                                                   "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6237                                                   "tc.relfrozenxid AS tfrozenxid, "
6238                                                   "0 AS tminmxid, "
6239                                                   "'p' AS relpersistence, 't' as relispopulated, "
6240                                                   "'d' AS relreplident, c.relpages, "
6241                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
6242                                                   "d.refobjid AS owning_tab, "
6243                                                   "d.refobjsubid AS owning_col, "
6244                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6245                                                   "c.reloptions AS reloptions, "
6246                                                   "tc.reloptions AS toast_reloptions, "
6247                                                   "NULL AS changed_acl, "
6248                                                   "NULL AS partkeydef, "
6249                                                   "false AS ispartition, "
6250                                                   "NULL AS partbound "
6251                                                   "FROM pg_class c "
6252                                                   "LEFT JOIN pg_depend d ON "
6253                                                   "(c.relkind = '%c' AND "
6254                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6255                                                   "d.objsubid = 0 AND "
6256                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6257                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6258                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6259                                                   "ORDER BY c.oid",
6260                                                   username_subquery,
6261                                                   RELKIND_SEQUENCE,
6262                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6263                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6264         }
6265         else if (fout->remoteVersion >= 80400)
6266         {
6267                 /*
6268                  * Left join to pick up dependency info linking sequences to their
6269                  * owning column, if any (note this dependency is AUTO as of 8.2)
6270                  */
6271                 appendPQExpBuffer(query,
6272                                                   "SELECT c.tableoid, c.oid, c.relname, "
6273                                                   "c.relacl, NULL as rrelacl, "
6274                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6275                                                   "c.relkind, "
6276                                                   "c.relnamespace, "
6277                                                   "(%s c.relowner) AS rolname, "
6278                                                   "c.relchecks, c.relhastriggers, "
6279                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6280                                                   "'f'::bool AS relrowsecurity, "
6281                                                   "'f'::bool AS relforcerowsecurity, "
6282                                                   "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6283                                                   "tc.relfrozenxid AS tfrozenxid, "
6284                                                   "0 AS tminmxid, "
6285                                                   "'p' AS relpersistence, 't' as relispopulated, "
6286                                                   "'d' AS relreplident, c.relpages, "
6287                                                   "NULL AS reloftype, "
6288                                                   "d.refobjid AS owning_tab, "
6289                                                   "d.refobjsubid AS owning_col, "
6290                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6291                                                   "c.reloptions AS reloptions, "
6292                                                   "tc.reloptions AS toast_reloptions, "
6293                                                   "NULL AS changed_acl, "
6294                                                   "NULL AS partkeydef, "
6295                                                   "false AS ispartition, "
6296                                                   "NULL AS partbound "
6297                                                   "FROM pg_class c "
6298                                                   "LEFT JOIN pg_depend d ON "
6299                                                   "(c.relkind = '%c' AND "
6300                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6301                                                   "d.objsubid = 0 AND "
6302                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6303                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6304                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6305                                                   "ORDER BY c.oid",
6306                                                   username_subquery,
6307                                                   RELKIND_SEQUENCE,
6308                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6309                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6310         }
6311         else if (fout->remoteVersion >= 80200)
6312         {
6313                 /*
6314                  * Left join to pick up dependency info linking sequences to their
6315                  * owning column, if any (note this dependency is AUTO as of 8.2)
6316                  */
6317                 appendPQExpBuffer(query,
6318                                                   "SELECT c.tableoid, c.oid, c.relname, "
6319                                                   "c.relacl, NULL as rrelacl, "
6320                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6321                                                   "c.relkind, "
6322                                                   "c.relnamespace, "
6323                                                   "(%s c.relowner) AS rolname, "
6324                                                   "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
6325                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
6326                                                   "'f'::bool AS relrowsecurity, "
6327                                                   "'f'::bool AS relforcerowsecurity, "
6328                                                   "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6329                                                   "tc.relfrozenxid AS tfrozenxid, "
6330                                                   "0 AS tminmxid, "
6331                                                   "'p' AS relpersistence, 't' as relispopulated, "
6332                                                   "'d' AS relreplident, c.relpages, "
6333                                                   "NULL AS reloftype, "
6334                                                   "d.refobjid AS owning_tab, "
6335                                                   "d.refobjsubid AS owning_col, "
6336                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6337                                                   "c.reloptions AS reloptions, "
6338                                                   "NULL AS toast_reloptions, "
6339                                                   "NULL AS changed_acl, "
6340                                                   "NULL AS partkeydef, "
6341                                                   "false AS ispartition, "
6342                                                   "NULL AS partbound "
6343                                                   "FROM pg_class c "
6344                                                   "LEFT JOIN pg_depend d ON "
6345                                                   "(c.relkind = '%c' AND "
6346                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6347                                                   "d.objsubid = 0 AND "
6348                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6349                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6350                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6351                                                   "ORDER BY c.oid",
6352                                                   username_subquery,
6353                                                   RELKIND_SEQUENCE,
6354                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6355                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6356         }
6357         else
6358         {
6359                 /*
6360                  * Left join to pick up dependency info linking sequences to their
6361                  * owning column, if any
6362                  */
6363                 appendPQExpBuffer(query,
6364                                                   "SELECT c.tableoid, c.oid, relname, "
6365                                                   "relacl, NULL as rrelacl, "
6366                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6367                                                   "relkind, relnamespace, "
6368                                                   "(%s relowner) AS rolname, "
6369                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
6370                                                   "relhasindex, relhasrules, relhasoids, "
6371                                                   "'f'::bool AS relrowsecurity, "
6372                                                   "'f'::bool AS relforcerowsecurity, "
6373                                                   "0 AS relfrozenxid, 0 AS relminmxid,"
6374                                                   "0 AS toid, "
6375                                                   "0 AS tfrozenxid, 0 AS tminmxid,"
6376                                                   "'p' AS relpersistence, 't' as relispopulated, "
6377                                                   "'d' AS relreplident, relpages, "
6378                                                   "NULL AS reloftype, "
6379                                                   "d.refobjid AS owning_tab, "
6380                                                   "d.refobjsubid AS owning_col, "
6381                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6382                                                   "NULL AS reloptions, "
6383                                                   "NULL AS toast_reloptions, "
6384                                                   "NULL AS changed_acl, "
6385                                                   "NULL AS partkeydef, "
6386                                                   "false AS ispartition, "
6387                                                   "NULL AS partbound "
6388                                                   "FROM pg_class c "
6389                                                   "LEFT JOIN pg_depend d ON "
6390                                                   "(c.relkind = '%c' AND "
6391                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6392                                                   "d.objsubid = 0 AND "
6393                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
6394                                                   "WHERE relkind in ('%c', '%c', '%c', '%c') "
6395                                                   "ORDER BY c.oid",
6396                                                   username_subquery,
6397                                                   RELKIND_SEQUENCE,
6398                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6399                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6400         }
6401
6402         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6403
6404         ntups = PQntuples(res);
6405
6406         *numTables = ntups;
6407
6408         /*
6409          * Extract data from result and lock dumpable tables.  We do the locking
6410          * before anything else, to minimize the window wherein a table could
6411          * disappear under us.
6412          *
6413          * Note that we have to save info about all tables here, even when dumping
6414          * only one, because we don't yet know which tables might be inheritance
6415          * ancestors of the target table.
6416          */
6417         tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
6418
6419         i_reltableoid = PQfnumber(res, "tableoid");
6420         i_reloid = PQfnumber(res, "oid");
6421         i_relname = PQfnumber(res, "relname");
6422         i_relnamespace = PQfnumber(res, "relnamespace");
6423         i_relacl = PQfnumber(res, "relacl");
6424         i_rrelacl = PQfnumber(res, "rrelacl");
6425         i_initrelacl = PQfnumber(res, "initrelacl");
6426         i_initrrelacl = PQfnumber(res, "initrrelacl");
6427         i_relkind = PQfnumber(res, "relkind");
6428         i_rolname = PQfnumber(res, "rolname");
6429         i_relchecks = PQfnumber(res, "relchecks");
6430         i_relhastriggers = PQfnumber(res, "relhastriggers");
6431         i_relhasindex = PQfnumber(res, "relhasindex");
6432         i_relhasrules = PQfnumber(res, "relhasrules");
6433         i_relrowsec = PQfnumber(res, "relrowsecurity");
6434         i_relforcerowsec = PQfnumber(res, "relforcerowsecurity");
6435         i_relhasoids = PQfnumber(res, "relhasoids");
6436         i_relfrozenxid = PQfnumber(res, "relfrozenxid");
6437         i_relminmxid = PQfnumber(res, "relminmxid");
6438         i_toastoid = PQfnumber(res, "toid");
6439         i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
6440         i_toastminmxid = PQfnumber(res, "tminmxid");
6441         i_relpersistence = PQfnumber(res, "relpersistence");
6442         i_relispopulated = PQfnumber(res, "relispopulated");
6443         i_relreplident = PQfnumber(res, "relreplident");
6444         i_relpages = PQfnumber(res, "relpages");
6445         i_owning_tab = PQfnumber(res, "owning_tab");
6446         i_owning_col = PQfnumber(res, "owning_col");
6447         i_reltablespace = PQfnumber(res, "reltablespace");
6448         i_reloptions = PQfnumber(res, "reloptions");
6449         i_checkoption = PQfnumber(res, "checkoption");
6450         i_toastreloptions = PQfnumber(res, "toast_reloptions");
6451         i_reloftype = PQfnumber(res, "reloftype");
6452         i_is_identity_sequence = PQfnumber(res, "is_identity_sequence");
6453         i_changed_acl = PQfnumber(res, "changed_acl");
6454         i_partkeydef = PQfnumber(res, "partkeydef");
6455         i_ispartition = PQfnumber(res, "ispartition");
6456         i_partbound = PQfnumber(res, "partbound");
6457
6458         if (dopt->lockWaitTimeout)
6459         {
6460                 /*
6461                  * Arrange to fail instead of waiting forever for a table lock.
6462                  *
6463                  * NB: this coding assumes that the only queries issued within the
6464                  * following loop are LOCK TABLEs; else the timeout may be undesirably
6465                  * applied to other things too.
6466                  */
6467                 resetPQExpBuffer(query);
6468                 appendPQExpBufferStr(query, "SET statement_timeout = ");
6469                 appendStringLiteralConn(query, dopt->lockWaitTimeout, GetConnection(fout));
6470                 ExecuteSqlStatement(fout, query->data);
6471         }
6472
6473         for (i = 0; i < ntups; i++)
6474         {
6475                 tblinfo[i].dobj.objType = DO_TABLE;
6476                 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
6477                 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
6478                 AssignDumpId(&tblinfo[i].dobj);
6479                 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
6480                 tblinfo[i].dobj.namespace =
6481                         findNamespace(fout,
6482                                                   atooid(PQgetvalue(res, i, i_relnamespace)));
6483                 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6484                 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
6485                 tblinfo[i].rrelacl = pg_strdup(PQgetvalue(res, i, i_rrelacl));
6486                 tblinfo[i].initrelacl = pg_strdup(PQgetvalue(res, i, i_initrelacl));
6487                 tblinfo[i].initrrelacl = pg_strdup(PQgetvalue(res, i, i_initrrelacl));
6488                 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
6489                 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
6490                 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
6491                 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
6492                 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
6493                 tblinfo[i].rowsec = (strcmp(PQgetvalue(res, i, i_relrowsec), "t") == 0);
6494                 tblinfo[i].forcerowsec = (strcmp(PQgetvalue(res, i, i_relforcerowsec), "t") == 0);
6495                 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
6496                 tblinfo[i].relispopulated = (strcmp(PQgetvalue(res, i, i_relispopulated), "t") == 0);
6497                 tblinfo[i].relreplident = *(PQgetvalue(res, i, i_relreplident));
6498                 tblinfo[i].relpages = atoi(PQgetvalue(res, i, i_relpages));
6499                 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
6500                 tblinfo[i].minmxid = atooid(PQgetvalue(res, i, i_relminmxid));
6501                 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
6502                 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
6503                 tblinfo[i].toast_minmxid = atooid(PQgetvalue(res, i, i_toastminmxid));
6504                 if (PQgetisnull(res, i, i_reloftype))
6505                         tblinfo[i].reloftype = NULL;
6506                 else
6507                         tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
6508                 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
6509                 if (PQgetisnull(res, i, i_owning_tab))
6510                 {
6511                         tblinfo[i].owning_tab = InvalidOid;
6512                         tblinfo[i].owning_col = 0;
6513                 }
6514                 else
6515                 {
6516                         tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
6517                         tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
6518                 }
6519                 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
6520                 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
6521                 if (i_checkoption == -1 || PQgetisnull(res, i, i_checkoption))
6522                         tblinfo[i].checkoption = NULL;
6523                 else
6524                         tblinfo[i].checkoption = pg_strdup(PQgetvalue(res, i, i_checkoption));
6525                 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
6526
6527                 /* other fields were zeroed above */
6528
6529                 /*
6530                  * Decide whether we want to dump this table.
6531                  */
6532                 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
6533                         tblinfo[i].dobj.dump = DUMP_COMPONENT_NONE;
6534                 else
6535                         selectDumpableTable(&tblinfo[i], fout);
6536
6537                 /*
6538                  * If the table-level and all column-level ACLs for this table are
6539                  * unchanged, then we don't need to worry about including the ACLs for
6540                  * this table.  If any column-level ACLs have been changed, the
6541                  * 'changed_acl' column from the query will indicate that.
6542                  *
6543                  * This can result in a significant performance improvement in cases
6544                  * where we are only looking to dump out the ACL (eg: pg_catalog).
6545                  */
6546                 if (PQgetisnull(res, i, i_relacl) && PQgetisnull(res, i, i_rrelacl) &&
6547                         PQgetisnull(res, i, i_initrelacl) &&
6548                         PQgetisnull(res, i, i_initrrelacl) &&
6549                         strcmp(PQgetvalue(res, i, i_changed_acl), "f") == 0)
6550                         tblinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
6551
6552                 tblinfo[i].interesting = tblinfo[i].dobj.dump ? true : false;
6553                 tblinfo[i].dummy_view = false;  /* might get set during sort */
6554                 tblinfo[i].postponed_def = false;       /* might get set during sort */
6555
6556                 tblinfo[i].is_identity_sequence = (i_is_identity_sequence >= 0 &&
6557                                                                                    strcmp(PQgetvalue(res, i, i_is_identity_sequence), "t") == 0);
6558
6559                 /* Partition key string or NULL */
6560                 tblinfo[i].partkeydef = pg_strdup(PQgetvalue(res, i, i_partkeydef));
6561                 tblinfo[i].ispartition = (strcmp(PQgetvalue(res, i, i_ispartition), "t") == 0);
6562                 tblinfo[i].partbound = pg_strdup(PQgetvalue(res, i, i_partbound));
6563
6564                 /*
6565                  * Read-lock target tables to make sure they aren't DROPPED or altered
6566                  * in schema before we get around to dumping them.
6567                  *
6568                  * Note that we don't explicitly lock parents of the target tables; we
6569                  * assume our lock on the child is enough to prevent schema
6570                  * alterations to parent tables.
6571                  *
6572                  * NOTE: it'd be kinda nice to lock other relations too, not only
6573                  * plain or partitioned tables, but the backend doesn't presently
6574                  * allow that.
6575                  *
6576                  * We only need to lock the table for certain components; see
6577                  * pg_dump.h
6578                  */
6579                 if (tblinfo[i].dobj.dump &&
6580                         (tblinfo[i].relkind == RELKIND_RELATION ||
6581                          tblinfo->relkind == RELKIND_PARTITIONED_TABLE) &&
6582                         (tblinfo[i].dobj.dump & DUMP_COMPONENTS_REQUIRING_LOCK))
6583                 {
6584                         resetPQExpBuffer(query);
6585                         appendPQExpBuffer(query,
6586                                                           "LOCK TABLE %s IN ACCESS SHARE MODE",
6587                                                           fmtQualifiedDumpable(&tblinfo[i]));
6588                         ExecuteSqlStatement(fout, query->data);
6589                 }
6590
6591                 /* Emit notice if join for owner failed */
6592                 if (strlen(tblinfo[i].rolname) == 0)
6593                         write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
6594                                           tblinfo[i].dobj.name);
6595         }
6596
6597         if (dopt->lockWaitTimeout)
6598         {
6599                 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
6600         }
6601
6602         PQclear(res);
6603
6604         destroyPQExpBuffer(query);
6605
6606         return tblinfo;
6607 }
6608
6609 /*
6610  * getOwnedSeqs
6611  *        identify owned sequences and mark them as dumpable if owning table is
6612  *
6613  * We used to do this in getTables(), but it's better to do it after the
6614  * index used by findTableByOid() has been set up.
6615  */
6616 void
6617 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
6618 {
6619         int                     i;
6620
6621         /*
6622          * Force sequences that are "owned" by table columns to be dumped whenever
6623          * their owning table is being dumped.
6624          */
6625         for (i = 0; i < numTables; i++)
6626         {
6627                 TableInfo  *seqinfo = &tblinfo[i];
6628                 TableInfo  *owning_tab;
6629
6630                 if (!OidIsValid(seqinfo->owning_tab))
6631                         continue;                       /* not an owned sequence */
6632
6633                 owning_tab = findTableByOid(seqinfo->owning_tab);
6634                 if (owning_tab == NULL)
6635                         exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
6636                                                   seqinfo->owning_tab, seqinfo->dobj.catId.oid);
6637
6638                 /*
6639                  * Only dump identity sequences if we're going to dump the table that
6640                  * it belongs to.
6641                  */
6642                 if (owning_tab->dobj.dump == DUMP_COMPONENT_NONE &&
6643                         seqinfo->is_identity_sequence)
6644                 {
6645                         seqinfo->dobj.dump = DUMP_COMPONENT_NONE;
6646                         continue;
6647                 }
6648
6649                 /*
6650                  * Otherwise we need to dump the components that are being dumped for
6651                  * the table and any components which the sequence is explicitly
6652                  * marked with.
6653                  *
6654                  * We can't simply use the set of components which are being dumped
6655                  * for the table as the table might be in an extension (and only the
6656                  * non-extension components, eg: ACLs if changed, security labels, and
6657                  * policies, are being dumped) while the sequence is not (and
6658                  * therefore the definition and other components should also be
6659                  * dumped).
6660                  *
6661                  * If the sequence is part of the extension then it should be properly
6662                  * marked by checkExtensionMembership() and this will be a no-op as
6663                  * the table will be equivalently marked.
6664                  */
6665                 seqinfo->dobj.dump = seqinfo->dobj.dump | owning_tab->dobj.dump;
6666
6667                 if (seqinfo->dobj.dump != DUMP_COMPONENT_NONE)
6668                         seqinfo->interesting = true;
6669         }
6670 }
6671
6672 /*
6673  * getInherits
6674  *        read all the inheritance information
6675  * from the system catalogs return them in the InhInfo* structure
6676  *
6677  * numInherits is set to the number of pairs read in
6678  */
6679 InhInfo *
6680 getInherits(Archive *fout, int *numInherits)
6681 {
6682         PGresult   *res;
6683         int                     ntups;
6684         int                     i;
6685         PQExpBuffer query = createPQExpBuffer();
6686         InhInfo    *inhinfo;
6687
6688         int                     i_inhrelid;
6689         int                     i_inhparent;
6690
6691         /*
6692          * Find all the inheritance information, excluding implicit inheritance
6693          * via partitioning.  We handle that case using getPartitions(), because
6694          * we want more information about partitions than just the parent-child
6695          * relationship.
6696          */
6697         appendPQExpBufferStr(query, "SELECT inhrelid, inhparent FROM pg_inherits");
6698
6699         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6700
6701         ntups = PQntuples(res);
6702
6703         *numInherits = ntups;
6704
6705         inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
6706
6707         i_inhrelid = PQfnumber(res, "inhrelid");
6708         i_inhparent = PQfnumber(res, "inhparent");
6709
6710         for (i = 0; i < ntups; i++)
6711         {
6712                 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
6713                 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
6714         }
6715
6716         PQclear(res);
6717
6718         destroyPQExpBuffer(query);
6719
6720         return inhinfo;
6721 }
6722
6723 /*
6724  * getIndexes
6725  *        get information about every index on a dumpable table
6726  *
6727  * Note: index data is not returned directly to the caller, but it
6728  * does get entered into the DumpableObject tables.
6729  */
6730 void
6731 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
6732 {
6733         int                     i,
6734                                 j;
6735         PQExpBuffer query = createPQExpBuffer();
6736         PGresult   *res;
6737         IndxInfo   *indxinfo;
6738         ConstraintInfo *constrinfo;
6739         int                     i_tableoid,
6740                                 i_oid,
6741                                 i_indexname,
6742                                 i_parentidx,
6743                                 i_indexdef,
6744                                 i_indnkeyatts,
6745                                 i_indnatts,
6746                                 i_indkey,
6747                                 i_indisclustered,
6748                                 i_indisreplident,
6749                                 i_contype,
6750                                 i_conname,
6751                                 i_condeferrable,
6752                                 i_condeferred,
6753                                 i_contableoid,
6754                                 i_conoid,
6755                                 i_condef,
6756                                 i_tablespace,
6757                                 i_indreloptions,
6758                                 i_relpages;
6759         int                     ntups;
6760
6761         for (i = 0; i < numTables; i++)
6762         {
6763                 TableInfo  *tbinfo = &tblinfo[i];
6764
6765                 if (!tbinfo->hasindex)
6766                         continue;
6767
6768                 /*
6769                  * Ignore indexes of tables whose definitions are not to be dumped.
6770                  *
6771                  * We also need indexes on partitioned tables which have partitions to
6772                  * be dumped, in order to dump the indexes on the partitions.
6773                  */
6774                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION) &&
6775                         !tbinfo->interesting)
6776                         continue;
6777
6778                 if (g_verbose)
6779                         write_msg(NULL, "reading indexes for table \"%s.%s\"\n",
6780                                           tbinfo->dobj.namespace->dobj.name,
6781                                           tbinfo->dobj.name);
6782
6783                 /*
6784                  * The point of the messy-looking outer join is to find a constraint
6785                  * that is related by an internal dependency link to the index. If we
6786                  * find one, create a CONSTRAINT entry linked to the INDEX entry.  We
6787                  * assume an index won't have more than one internal dependency.
6788                  *
6789                  * As of 9.0 we don't need to look at pg_depend but can check for a
6790                  * match to pg_constraint.conindid.  The check on conrelid is
6791                  * redundant but useful because that column is indexed while conindid
6792                  * is not.
6793                  */
6794                 resetPQExpBuffer(query);
6795                 if (fout->remoteVersion >= 110000)
6796                 {
6797                         appendPQExpBuffer(query,
6798                                                           "SELECT t.tableoid, t.oid, "
6799                                                           "t.relname AS indexname, "
6800                                                           "inh.inhparent AS parentidx, "
6801                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6802                                                           "i.indnkeyatts AS indnkeyatts, "
6803                                                           "i.indnatts AS indnatts, "
6804                                                           "i.indkey, i.indisclustered, "
6805                                                           "i.indisreplident, t.relpages, "
6806                                                           "c.contype, c.conname, "
6807                                                           "c.condeferrable, c.condeferred, "
6808                                                           "c.tableoid AS contableoid, "
6809                                                           "c.oid AS conoid, "
6810                                                           "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6811                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6812                                                           "t.reloptions AS indreloptions "
6813                                                           "FROM pg_catalog.pg_index i "
6814                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6815                                                           "JOIN pg_catalog.pg_class t2 ON (t2.oid = i.indrelid) "
6816                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6817                                                           "ON (i.indrelid = c.conrelid AND "
6818                                                           "i.indexrelid = c.conindid AND "
6819                                                           "c.contype IN ('p','u','x')) "
6820                                                           "LEFT JOIN pg_catalog.pg_inherits inh "
6821                                                           "ON (inh.inhrelid = indexrelid) "
6822                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6823                                                           "AND (i.indisvalid OR t2.relkind = 'p') "
6824                                                           "AND i.indisready "
6825                                                           "ORDER BY indexname",
6826                                                           tbinfo->dobj.catId.oid);
6827                 }
6828                 else if (fout->remoteVersion >= 90400)
6829                 {
6830                         /*
6831                          * the test on indisready is necessary in 9.2, and harmless in
6832                          * earlier/later versions
6833                          */
6834                         appendPQExpBuffer(query,
6835                                                           "SELECT t.tableoid, t.oid, "
6836                                                           "t.relname AS indexname, "
6837                                                           "0 AS parentidx, "
6838                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6839                                                           "i.indnatts AS indnkeyatts, "
6840                                                           "i.indnatts AS indnatts, "
6841                                                           "i.indkey, i.indisclustered, "
6842                                                           "i.indisreplident, t.relpages, "
6843                                                           "c.contype, c.conname, "
6844                                                           "c.condeferrable, c.condeferred, "
6845                                                           "c.tableoid AS contableoid, "
6846                                                           "c.oid AS conoid, "
6847                                                           "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6848                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6849                                                           "t.reloptions AS indreloptions "
6850                                                           "FROM pg_catalog.pg_index i "
6851                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6852                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6853                                                           "ON (i.indrelid = c.conrelid AND "
6854                                                           "i.indexrelid = c.conindid AND "
6855                                                           "c.contype IN ('p','u','x')) "
6856                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6857                                                           "AND i.indisvalid AND i.indisready "
6858                                                           "ORDER BY indexname",
6859                                                           tbinfo->dobj.catId.oid);
6860                 }
6861                 else if (fout->remoteVersion >= 90000)
6862                 {
6863                         /*
6864                          * the test on indisready is necessary in 9.2, and harmless in
6865                          * earlier/later versions
6866                          */
6867                         appendPQExpBuffer(query,
6868                                                           "SELECT t.tableoid, t.oid, "
6869                                                           "t.relname AS indexname, "
6870                                                           "0 AS parentidx, "
6871                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6872                                                           "i.indnatts AS indnkeyatts, "
6873                                                           "i.indnatts AS indnatts, "
6874                                                           "i.indkey, i.indisclustered, "
6875                                                           "false AS indisreplident, t.relpages, "
6876                                                           "c.contype, c.conname, "
6877                                                           "c.condeferrable, c.condeferred, "
6878                                                           "c.tableoid AS contableoid, "
6879                                                           "c.oid AS conoid, "
6880                                                           "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6881                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6882                                                           "t.reloptions AS indreloptions "
6883                                                           "FROM pg_catalog.pg_index i "
6884                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6885                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6886                                                           "ON (i.indrelid = c.conrelid AND "
6887                                                           "i.indexrelid = c.conindid AND "
6888                                                           "c.contype IN ('p','u','x')) "
6889                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6890                                                           "AND i.indisvalid AND i.indisready "
6891                                                           "ORDER BY indexname",
6892                                                           tbinfo->dobj.catId.oid);
6893                 }
6894                 else if (fout->remoteVersion >= 80200)
6895                 {
6896                         appendPQExpBuffer(query,
6897                                                           "SELECT t.tableoid, t.oid, "
6898                                                           "t.relname AS indexname, "
6899                                                           "0 AS parentidx, "
6900                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6901                                                           "i.indnatts AS indnkeyatts, "
6902                                                           "i.indnatts AS indnatts, "
6903                                                           "i.indkey, i.indisclustered, "
6904                                                           "false AS indisreplident, t.relpages, "
6905                                                           "c.contype, c.conname, "
6906                                                           "c.condeferrable, c.condeferred, "
6907                                                           "c.tableoid AS contableoid, "
6908                                                           "c.oid AS conoid, "
6909                                                           "null AS condef, "
6910                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6911                                                           "t.reloptions AS indreloptions "
6912                                                           "FROM pg_catalog.pg_index i "
6913                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6914                                                           "LEFT JOIN pg_catalog.pg_depend d "
6915                                                           "ON (d.classid = t.tableoid "
6916                                                           "AND d.objid = t.oid "
6917                                                           "AND d.deptype = 'i') "
6918                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6919                                                           "ON (d.refclassid = c.tableoid "
6920                                                           "AND d.refobjid = c.oid) "
6921                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6922                                                           "AND i.indisvalid "
6923                                                           "ORDER BY indexname",
6924                                                           tbinfo->dobj.catId.oid);
6925                 }
6926                 else
6927                 {
6928                         appendPQExpBuffer(query,
6929                                                           "SELECT t.tableoid, t.oid, "
6930                                                           "t.relname AS indexname, "
6931                                                           "0 AS parentidx, "
6932                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6933                                                           "t.relnatts AS indnkeyatts, "
6934                                                           "t.relnatts AS indnatts, "
6935                                                           "i.indkey, i.indisclustered, "
6936                                                           "false AS indisreplident, t.relpages, "
6937                                                           "c.contype, c.conname, "
6938                                                           "c.condeferrable, c.condeferred, "
6939                                                           "c.tableoid AS contableoid, "
6940                                                           "c.oid AS conoid, "
6941                                                           "null AS condef, "
6942                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6943                                                           "null AS indreloptions "
6944                                                           "FROM pg_catalog.pg_index i "
6945                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6946                                                           "LEFT JOIN pg_catalog.pg_depend d "
6947                                                           "ON (d.classid = t.tableoid "
6948                                                           "AND d.objid = t.oid "
6949                                                           "AND d.deptype = 'i') "
6950                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6951                                                           "ON (d.refclassid = c.tableoid "
6952                                                           "AND d.refobjid = c.oid) "
6953                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6954                                                           "ORDER BY indexname",
6955                                                           tbinfo->dobj.catId.oid);
6956                 }
6957
6958                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6959
6960                 ntups = PQntuples(res);
6961
6962                 i_tableoid = PQfnumber(res, "tableoid");
6963                 i_oid = PQfnumber(res, "oid");
6964                 i_indexname = PQfnumber(res, "indexname");
6965                 i_parentidx = PQfnumber(res, "parentidx");
6966                 i_indexdef = PQfnumber(res, "indexdef");
6967                 i_indnkeyatts = PQfnumber(res, "indnkeyatts");
6968                 i_indnatts = PQfnumber(res, "indnatts");
6969                 i_indkey = PQfnumber(res, "indkey");
6970                 i_indisclustered = PQfnumber(res, "indisclustered");
6971                 i_indisreplident = PQfnumber(res, "indisreplident");
6972                 i_relpages = PQfnumber(res, "relpages");
6973                 i_contype = PQfnumber(res, "contype");
6974                 i_conname = PQfnumber(res, "conname");
6975                 i_condeferrable = PQfnumber(res, "condeferrable");
6976                 i_condeferred = PQfnumber(res, "condeferred");
6977                 i_contableoid = PQfnumber(res, "contableoid");
6978                 i_conoid = PQfnumber(res, "conoid");
6979                 i_condef = PQfnumber(res, "condef");
6980                 i_tablespace = PQfnumber(res, "tablespace");
6981                 i_indreloptions = PQfnumber(res, "indreloptions");
6982
6983                 tbinfo->indexes = indxinfo =
6984                         (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
6985                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
6986                 tbinfo->numIndexes = ntups;
6987
6988                 for (j = 0; j < ntups; j++)
6989                 {
6990                         char            contype;
6991
6992                         indxinfo[j].dobj.objType = DO_INDEX;
6993                         indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
6994                         indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
6995                         AssignDumpId(&indxinfo[j].dobj);
6996                         indxinfo[j].dobj.dump = tbinfo->dobj.dump;
6997                         indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
6998                         indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6999                         indxinfo[j].indextable = tbinfo;
7000                         indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
7001                         indxinfo[j].indnkeyattrs = atoi(PQgetvalue(res, j, i_indnkeyatts));
7002                         indxinfo[j].indnattrs = atoi(PQgetvalue(res, j, i_indnatts));
7003                         indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
7004                         indxinfo[j].indreloptions = pg_strdup(PQgetvalue(res, j, i_indreloptions));
7005                         indxinfo[j].indkeys = (Oid *) pg_malloc(indxinfo[j].indnattrs * sizeof(Oid));
7006                         parseOidArray(PQgetvalue(res, j, i_indkey),
7007                                                   indxinfo[j].indkeys, indxinfo[j].indnattrs);
7008                         indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
7009                         indxinfo[j].indisreplident = (PQgetvalue(res, j, i_indisreplident)[0] == 't');
7010                         indxinfo[j].parentidx = atooid(PQgetvalue(res, j, i_parentidx));
7011                         indxinfo[j].relpages = atoi(PQgetvalue(res, j, i_relpages));
7012                         contype = *(PQgetvalue(res, j, i_contype));
7013
7014                         if (contype == 'p' || contype == 'u' || contype == 'x')
7015                         {
7016                                 /*
7017                                  * If we found a constraint matching the index, create an
7018                                  * entry for it.
7019                                  */
7020                                 constrinfo[j].dobj.objType = DO_CONSTRAINT;
7021                                 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
7022                                 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7023                                 AssignDumpId(&constrinfo[j].dobj);
7024                                 constrinfo[j].dobj.dump = tbinfo->dobj.dump;
7025                                 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7026                                 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7027                                 constrinfo[j].contable = tbinfo;
7028                                 constrinfo[j].condomain = NULL;
7029                                 constrinfo[j].contype = contype;
7030                                 if (contype == 'x')
7031                                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
7032                                 else
7033                                         constrinfo[j].condef = NULL;
7034                                 constrinfo[j].confrelid = InvalidOid;
7035                                 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
7036                                 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
7037                                 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
7038                                 constrinfo[j].conislocal = true;
7039                                 constrinfo[j].separate = true;
7040
7041                                 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
7042                         }
7043                         else
7044                         {
7045                                 /* Plain secondary index */
7046                                 indxinfo[j].indexconstraint = 0;
7047                         }
7048                 }
7049
7050                 PQclear(res);
7051         }
7052
7053         destroyPQExpBuffer(query);
7054 }
7055
7056 /*
7057  * getExtendedStatistics
7058  *        get information about extended-statistics objects.
7059  *
7060  * Note: extended statistics data is not returned directly to the caller, but
7061  * it does get entered into the DumpableObject tables.
7062  */
7063 void
7064 getExtendedStatistics(Archive *fout)
7065 {
7066         PQExpBuffer query;
7067         PGresult   *res;
7068         StatsExtInfo *statsextinfo;
7069         int                     ntups;
7070         int                     i_tableoid;
7071         int                     i_oid;
7072         int                     i_stxname;
7073         int                     i_stxnamespace;
7074         int                     i_rolname;
7075         int                     i;
7076
7077         /* Extended statistics were new in v10 */
7078         if (fout->remoteVersion < 100000)
7079                 return;
7080
7081         query = createPQExpBuffer();
7082
7083         appendPQExpBuffer(query, "SELECT tableoid, oid, stxname, "
7084                                           "stxnamespace, (%s stxowner) AS rolname "
7085                                           "FROM pg_catalog.pg_statistic_ext",
7086                                           username_subquery);
7087
7088         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7089
7090         ntups = PQntuples(res);
7091
7092         i_tableoid = PQfnumber(res, "tableoid");
7093         i_oid = PQfnumber(res, "oid");
7094         i_stxname = PQfnumber(res, "stxname");
7095         i_stxnamespace = PQfnumber(res, "stxnamespace");
7096         i_rolname = PQfnumber(res, "rolname");
7097
7098         statsextinfo = (StatsExtInfo *) pg_malloc(ntups * sizeof(StatsExtInfo));
7099
7100         for (i = 0; i < ntups; i++)
7101         {
7102                 statsextinfo[i].dobj.objType = DO_STATSEXT;
7103                 statsextinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7104                 statsextinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7105                 AssignDumpId(&statsextinfo[i].dobj);
7106                 statsextinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_stxname));
7107                 statsextinfo[i].dobj.namespace =
7108                         findNamespace(fout,
7109                                                   atooid(PQgetvalue(res, i, i_stxnamespace)));
7110                 statsextinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7111
7112                 /* Decide whether we want to dump it */
7113                 selectDumpableObject(&(statsextinfo[i].dobj), fout);
7114
7115                 /* Stats objects do not currently have ACLs. */
7116                 statsextinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7117         }
7118
7119         PQclear(res);
7120         destroyPQExpBuffer(query);
7121 }
7122
7123 /*
7124  * getConstraints
7125  *
7126  * Get info about constraints on dumpable tables.
7127  *
7128  * Currently handles foreign keys only.
7129  * Unique and primary key constraints are handled with indexes,
7130  * while check constraints are processed in getTableAttrs().
7131  */
7132 void
7133 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
7134 {
7135         int                     i,
7136                                 j;
7137         ConstraintInfo *constrinfo;
7138         PQExpBuffer query;
7139         PGresult   *res;
7140         int                     i_contableoid,
7141                                 i_conoid,
7142                                 i_conname,
7143                                 i_confrelid,
7144                                 i_condef;
7145         int                     ntups;
7146
7147         query = createPQExpBuffer();
7148
7149         for (i = 0; i < numTables; i++)
7150         {
7151                 TableInfo  *tbinfo = &tblinfo[i];
7152
7153                 /*
7154                  * For partitioned tables, foreign keys have no triggers so they must
7155                  * be included anyway in case some foreign keys are defined.
7156                  */
7157                 if ((!tbinfo->hastriggers &&
7158                          tbinfo->relkind != RELKIND_PARTITIONED_TABLE) ||
7159                         !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7160                         continue;
7161
7162                 if (g_verbose)
7163                         write_msg(NULL, "reading foreign key constraints for table \"%s.%s\"\n",
7164                                           tbinfo->dobj.namespace->dobj.name,
7165                                           tbinfo->dobj.name);
7166
7167                 resetPQExpBuffer(query);
7168                 if (fout->remoteVersion >= 110000)
7169                         appendPQExpBuffer(query,
7170                                                           "SELECT tableoid, oid, conname, confrelid, "
7171                                                           "pg_catalog.pg_get_constraintdef(oid) AS condef "
7172                                                           "FROM pg_catalog.pg_constraint "
7173                                                           "WHERE conrelid = '%u'::pg_catalog.oid "
7174                                                           "AND conparentid = 0 "
7175                                                           "AND contype = 'f'",
7176                                                           tbinfo->dobj.catId.oid);
7177                 else
7178                         appendPQExpBuffer(query,
7179                                                           "SELECT tableoid, oid, conname, confrelid, "
7180                                                           "pg_catalog.pg_get_constraintdef(oid) AS condef "
7181                                                           "FROM pg_catalog.pg_constraint "
7182                                                           "WHERE conrelid = '%u'::pg_catalog.oid "
7183                                                           "AND contype = 'f'",
7184                                                           tbinfo->dobj.catId.oid);
7185                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7186
7187                 ntups = PQntuples(res);
7188
7189                 i_contableoid = PQfnumber(res, "tableoid");
7190                 i_conoid = PQfnumber(res, "oid");
7191                 i_conname = PQfnumber(res, "conname");
7192                 i_confrelid = PQfnumber(res, "confrelid");
7193                 i_condef = PQfnumber(res, "condef");
7194
7195                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7196
7197                 for (j = 0; j < ntups; j++)
7198                 {
7199                         constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
7200                         constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
7201                         constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7202                         AssignDumpId(&constrinfo[j].dobj);
7203                         constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7204                         constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7205                         constrinfo[j].contable = tbinfo;
7206                         constrinfo[j].condomain = NULL;
7207                         constrinfo[j].contype = 'f';
7208                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
7209                         constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
7210                         constrinfo[j].conindex = 0;
7211                         constrinfo[j].condeferrable = false;
7212                         constrinfo[j].condeferred = false;
7213                         constrinfo[j].conislocal = true;
7214                         constrinfo[j].separate = true;
7215                 }
7216
7217                 PQclear(res);
7218         }
7219
7220         destroyPQExpBuffer(query);
7221 }
7222
7223 /*
7224  * getDomainConstraints
7225  *
7226  * Get info about constraints on a domain.
7227  */
7228 static void
7229 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
7230 {
7231         int                     i;
7232         ConstraintInfo *constrinfo;
7233         PQExpBuffer query;
7234         PGresult   *res;
7235         int                     i_tableoid,
7236                                 i_oid,
7237                                 i_conname,
7238                                 i_consrc;
7239         int                     ntups;
7240
7241         query = createPQExpBuffer();
7242
7243         if (fout->remoteVersion >= 90100)
7244                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7245                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7246                                                   "convalidated "
7247                                                   "FROM pg_catalog.pg_constraint "
7248                                                   "WHERE contypid = '%u'::pg_catalog.oid "
7249                                                   "ORDER BY conname",
7250                                                   tyinfo->dobj.catId.oid);
7251
7252         else
7253                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
7254                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7255                                                   "true as convalidated "
7256                                                   "FROM pg_catalog.pg_constraint "
7257                                                   "WHERE contypid = '%u'::pg_catalog.oid "
7258                                                   "ORDER BY conname",
7259                                                   tyinfo->dobj.catId.oid);
7260
7261         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7262
7263         ntups = PQntuples(res);
7264
7265         i_tableoid = PQfnumber(res, "tableoid");
7266         i_oid = PQfnumber(res, "oid");
7267         i_conname = PQfnumber(res, "conname");
7268         i_consrc = PQfnumber(res, "consrc");
7269
7270         constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7271
7272         tyinfo->nDomChecks = ntups;
7273         tyinfo->domChecks = constrinfo;
7274
7275         for (i = 0; i < ntups; i++)
7276         {
7277                 bool            validated = PQgetvalue(res, i, 4)[0] == 't';
7278
7279                 constrinfo[i].dobj.objType = DO_CONSTRAINT;
7280                 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7281                 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7282                 AssignDumpId(&constrinfo[i].dobj);
7283                 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
7284                 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
7285                 constrinfo[i].contable = NULL;
7286                 constrinfo[i].condomain = tyinfo;
7287                 constrinfo[i].contype = 'c';
7288                 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
7289                 constrinfo[i].confrelid = InvalidOid;
7290                 constrinfo[i].conindex = 0;
7291                 constrinfo[i].condeferrable = false;
7292                 constrinfo[i].condeferred = false;
7293                 constrinfo[i].conislocal = true;
7294
7295                 constrinfo[i].separate = !validated;
7296
7297                 /*
7298                  * Make the domain depend on the constraint, ensuring it won't be
7299                  * output till any constraint dependencies are OK.  If the constraint
7300                  * has not been validated, it's going to be dumped after the domain
7301                  * anyway, so this doesn't matter.
7302                  */
7303                 if (validated)
7304                         addObjectDependency(&tyinfo->dobj,
7305                                                                 constrinfo[i].dobj.dumpId);
7306         }
7307
7308         PQclear(res);
7309
7310         destroyPQExpBuffer(query);
7311 }
7312
7313 /*
7314  * getRules
7315  *        get basic information about every rule in the system
7316  *
7317  * numRules is set to the number of rules read in
7318  */
7319 RuleInfo *
7320 getRules(Archive *fout, int *numRules)
7321 {
7322         PGresult   *res;
7323         int                     ntups;
7324         int                     i;
7325         PQExpBuffer query = createPQExpBuffer();
7326         RuleInfo   *ruleinfo;
7327         int                     i_tableoid;
7328         int                     i_oid;
7329         int                     i_rulename;
7330         int                     i_ruletable;
7331         int                     i_ev_type;
7332         int                     i_is_instead;
7333         int                     i_ev_enabled;
7334
7335         if (fout->remoteVersion >= 80300)
7336         {
7337                 appendPQExpBufferStr(query, "SELECT "
7338                                                          "tableoid, oid, rulename, "
7339                                                          "ev_class AS ruletable, ev_type, is_instead, "
7340                                                          "ev_enabled "
7341                                                          "FROM pg_rewrite "
7342                                                          "ORDER BY oid");
7343         }
7344         else
7345         {
7346                 appendPQExpBufferStr(query, "SELECT "
7347                                                          "tableoid, oid, rulename, "
7348                                                          "ev_class AS ruletable, ev_type, is_instead, "
7349                                                          "'O'::char AS ev_enabled "
7350                                                          "FROM pg_rewrite "
7351                                                          "ORDER BY oid");
7352         }
7353
7354         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7355
7356         ntups = PQntuples(res);
7357
7358         *numRules = ntups;
7359
7360         ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
7361
7362         i_tableoid = PQfnumber(res, "tableoid");
7363         i_oid = PQfnumber(res, "oid");
7364         i_rulename = PQfnumber(res, "rulename");
7365         i_ruletable = PQfnumber(res, "ruletable");
7366         i_ev_type = PQfnumber(res, "ev_type");
7367         i_is_instead = PQfnumber(res, "is_instead");
7368         i_ev_enabled = PQfnumber(res, "ev_enabled");
7369
7370         for (i = 0; i < ntups; i++)
7371         {
7372                 Oid                     ruletableoid;
7373
7374                 ruleinfo[i].dobj.objType = DO_RULE;
7375                 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7376                 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7377                 AssignDumpId(&ruleinfo[i].dobj);
7378                 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
7379                 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
7380                 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
7381                 if (ruleinfo[i].ruletable == NULL)
7382                         exit_horribly(NULL, "failed sanity check, parent table with OID %u of pg_rewrite entry with OID %u not found\n",
7383                                                   ruletableoid, ruleinfo[i].dobj.catId.oid);
7384                 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
7385                 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
7386                 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
7387                 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
7388                 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
7389                 if (ruleinfo[i].ruletable)
7390                 {
7391                         /*
7392                          * If the table is a view or materialized view, force its ON
7393                          * SELECT rule to be sorted before the view itself --- this
7394                          * ensures that any dependencies for the rule affect the table's
7395                          * positioning. Other rules are forced to appear after their
7396                          * table.
7397                          */
7398                         if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
7399                                  ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
7400                                 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
7401                         {
7402                                 addObjectDependency(&ruleinfo[i].ruletable->dobj,
7403                                                                         ruleinfo[i].dobj.dumpId);
7404                                 /* We'll merge the rule into CREATE VIEW, if possible */
7405                                 ruleinfo[i].separate = false;
7406                         }
7407                         else
7408                         {
7409                                 addObjectDependency(&ruleinfo[i].dobj,
7410                                                                         ruleinfo[i].ruletable->dobj.dumpId);
7411                                 ruleinfo[i].separate = true;
7412                         }
7413                 }
7414                 else
7415                         ruleinfo[i].separate = true;
7416         }
7417
7418         PQclear(res);
7419
7420         destroyPQExpBuffer(query);
7421
7422         return ruleinfo;
7423 }
7424
7425 /*
7426  * getTriggers
7427  *        get information about every trigger on a dumpable table
7428  *
7429  * Note: trigger data is not returned directly to the caller, but it
7430  * does get entered into the DumpableObject tables.
7431  */
7432 void
7433 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
7434 {
7435         int                     i,
7436                                 j;
7437         PQExpBuffer query = createPQExpBuffer();
7438         PGresult   *res;
7439         TriggerInfo *tginfo;
7440         int                     i_tableoid,
7441                                 i_oid,
7442                                 i_tgname,
7443                                 i_tgfname,
7444                                 i_tgtype,
7445                                 i_tgnargs,
7446                                 i_tgargs,
7447                                 i_tgisconstraint,
7448                                 i_tgconstrname,
7449                                 i_tgconstrrelid,
7450                                 i_tgconstrrelname,
7451                                 i_tgenabled,
7452                                 i_tgdeferrable,
7453                                 i_tginitdeferred,
7454                                 i_tgdef;
7455         int                     ntups;
7456
7457         for (i = 0; i < numTables; i++)
7458         {
7459                 TableInfo  *tbinfo = &tblinfo[i];
7460
7461                 if (!tbinfo->hastriggers ||
7462                         !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7463                         continue;
7464
7465                 if (g_verbose)
7466                         write_msg(NULL, "reading triggers for table \"%s.%s\"\n",
7467                                           tbinfo->dobj.namespace->dobj.name,
7468                                           tbinfo->dobj.name);
7469
7470                 resetPQExpBuffer(query);
7471                 if (fout->remoteVersion >= 90000)
7472                 {
7473                         /*
7474                          * NB: think not to use pretty=true in pg_get_triggerdef.  It
7475                          * could result in non-forward-compatible dumps of WHEN clauses
7476                          * due to under-parenthesization.
7477                          */
7478                         appendPQExpBuffer(query,
7479                                                           "SELECT tgname, "
7480                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
7481                                                           "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
7482                                                           "tgenabled, tableoid, oid "
7483                                                           "FROM pg_catalog.pg_trigger t "
7484                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
7485                                                           "AND NOT tgisinternal",
7486                                                           tbinfo->dobj.catId.oid);
7487                 }
7488                 else if (fout->remoteVersion >= 80300)
7489                 {
7490                         /*
7491                          * We ignore triggers that are tied to a foreign-key constraint
7492                          */
7493                         appendPQExpBuffer(query,
7494                                                           "SELECT tgname, "
7495                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
7496                                                           "tgtype, tgnargs, tgargs, tgenabled, "
7497                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
7498                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
7499                                                           "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7500                                                           "FROM pg_catalog.pg_trigger t "
7501                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
7502                                                           "AND tgconstraint = 0",
7503                                                           tbinfo->dobj.catId.oid);
7504                 }
7505                 else
7506                 {
7507                         /*
7508                          * We ignore triggers that are tied to a foreign-key constraint,
7509                          * but in these versions we have to grovel through pg_constraint
7510                          * to find out
7511                          */
7512                         appendPQExpBuffer(query,
7513                                                           "SELECT tgname, "
7514                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
7515                                                           "tgtype, tgnargs, tgargs, tgenabled, "
7516                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
7517                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
7518                                                           "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7519                                                           "FROM pg_catalog.pg_trigger t "
7520                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
7521                                                           "AND (NOT tgisconstraint "
7522                                                           " OR NOT EXISTS"
7523                                                           "  (SELECT 1 FROM pg_catalog.pg_depend d "
7524                                                           "   JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
7525                                                           "   WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
7526                                                           tbinfo->dobj.catId.oid);
7527                 }
7528
7529                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7530
7531                 ntups = PQntuples(res);
7532
7533                 i_tableoid = PQfnumber(res, "tableoid");
7534                 i_oid = PQfnumber(res, "oid");
7535                 i_tgname = PQfnumber(res, "tgname");
7536                 i_tgfname = PQfnumber(res, "tgfname");
7537                 i_tgtype = PQfnumber(res, "tgtype");
7538                 i_tgnargs = PQfnumber(res, "tgnargs");
7539                 i_tgargs = PQfnumber(res, "tgargs");
7540                 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
7541                 i_tgconstrname = PQfnumber(res, "tgconstrname");
7542                 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
7543                 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
7544                 i_tgenabled = PQfnumber(res, "tgenabled");
7545                 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
7546                 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
7547                 i_tgdef = PQfnumber(res, "tgdef");
7548
7549                 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
7550
7551                 tbinfo->numTriggers = ntups;
7552                 tbinfo->triggers = tginfo;
7553
7554                 for (j = 0; j < ntups; j++)
7555                 {
7556                         tginfo[j].dobj.objType = DO_TRIGGER;
7557                         tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
7558                         tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
7559                         AssignDumpId(&tginfo[j].dobj);
7560                         tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
7561                         tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
7562                         tginfo[j].tgtable = tbinfo;
7563                         tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
7564                         if (i_tgdef >= 0)
7565                         {
7566                                 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
7567
7568                                 /* remaining fields are not valid if we have tgdef */
7569                                 tginfo[j].tgfname = NULL;
7570                                 tginfo[j].tgtype = 0;
7571                                 tginfo[j].tgnargs = 0;
7572                                 tginfo[j].tgargs = NULL;
7573                                 tginfo[j].tgisconstraint = false;
7574                                 tginfo[j].tgdeferrable = false;
7575                                 tginfo[j].tginitdeferred = false;
7576                                 tginfo[j].tgconstrname = NULL;
7577                                 tginfo[j].tgconstrrelid = InvalidOid;
7578                                 tginfo[j].tgconstrrelname = NULL;
7579                         }
7580                         else
7581                         {
7582                                 tginfo[j].tgdef = NULL;
7583
7584                                 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
7585                                 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
7586                                 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
7587                                 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
7588                                 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
7589                                 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
7590                                 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
7591
7592                                 if (tginfo[j].tgisconstraint)
7593                                 {
7594                                         tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
7595                                         tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
7596                                         if (OidIsValid(tginfo[j].tgconstrrelid))
7597                                         {
7598                                                 if (PQgetisnull(res, j, i_tgconstrrelname))
7599                                                         exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
7600                                                                                   tginfo[j].dobj.name,
7601                                                                                   tbinfo->dobj.name,
7602                                                                                   tginfo[j].tgconstrrelid);
7603                                                 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
7604                                         }
7605                                         else
7606                                                 tginfo[j].tgconstrrelname = NULL;
7607                                 }
7608                                 else
7609                                 {
7610                                         tginfo[j].tgconstrname = NULL;
7611                                         tginfo[j].tgconstrrelid = InvalidOid;
7612                                         tginfo[j].tgconstrrelname = NULL;
7613                                 }
7614                         }
7615                 }
7616
7617                 PQclear(res);
7618         }
7619
7620         destroyPQExpBuffer(query);
7621 }
7622
7623 /*
7624  * getEventTriggers
7625  *        get information about event triggers
7626  */
7627 EventTriggerInfo *
7628 getEventTriggers(Archive *fout, int *numEventTriggers)
7629 {
7630         int                     i;
7631         PQExpBuffer query;
7632         PGresult   *res;
7633         EventTriggerInfo *evtinfo;
7634         int                     i_tableoid,
7635                                 i_oid,
7636                                 i_evtname,
7637                                 i_evtevent,
7638                                 i_evtowner,
7639                                 i_evttags,
7640                                 i_evtfname,
7641                                 i_evtenabled;
7642         int                     ntups;
7643
7644         /* Before 9.3, there are no event triggers */
7645         if (fout->remoteVersion < 90300)
7646         {
7647                 *numEventTriggers = 0;
7648                 return NULL;
7649         }
7650
7651         query = createPQExpBuffer();
7652
7653         appendPQExpBuffer(query,
7654                                           "SELECT e.tableoid, e.oid, evtname, evtenabled, "
7655                                           "evtevent, (%s evtowner) AS evtowner, "
7656                                           "array_to_string(array("
7657                                           "select quote_literal(x) "
7658                                           " from unnest(evttags) as t(x)), ', ') as evttags, "
7659                                           "e.evtfoid::regproc as evtfname "
7660                                           "FROM pg_event_trigger e "
7661                                           "ORDER BY e.oid",
7662                                           username_subquery);
7663
7664         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7665
7666         ntups = PQntuples(res);
7667
7668         *numEventTriggers = ntups;
7669
7670         evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
7671
7672         i_tableoid = PQfnumber(res, "tableoid");
7673         i_oid = PQfnumber(res, "oid");
7674         i_evtname = PQfnumber(res, "evtname");
7675         i_evtevent = PQfnumber(res, "evtevent");
7676         i_evtowner = PQfnumber(res, "evtowner");
7677         i_evttags = PQfnumber(res, "evttags");
7678         i_evtfname = PQfnumber(res, "evtfname");
7679         i_evtenabled = PQfnumber(res, "evtenabled");
7680
7681         for (i = 0; i < ntups; i++)
7682         {
7683                 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
7684                 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7685                 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7686                 AssignDumpId(&evtinfo[i].dobj);
7687                 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
7688                 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
7689                 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
7690                 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
7691                 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
7692                 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
7693                 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
7694
7695                 /* Decide whether we want to dump it */
7696                 selectDumpableObject(&(evtinfo[i].dobj), fout);
7697
7698                 /* Event Triggers do not currently have ACLs. */
7699                 evtinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7700         }
7701
7702         PQclear(res);
7703
7704         destroyPQExpBuffer(query);
7705
7706         return evtinfo;
7707 }
7708
7709 /*
7710  * getProcLangs
7711  *        get basic information about every procedural language in the system
7712  *
7713  * numProcLangs is set to the number of langs read in
7714  *
7715  * NB: this must run after getFuncs() because we assume we can do
7716  * findFuncByOid().
7717  */
7718 ProcLangInfo *
7719 getProcLangs(Archive *fout, int *numProcLangs)
7720 {
7721         DumpOptions *dopt = fout->dopt;
7722         PGresult   *res;
7723         int                     ntups;
7724         int                     i;
7725         PQExpBuffer query = createPQExpBuffer();
7726         ProcLangInfo *planginfo;
7727         int                     i_tableoid;
7728         int                     i_oid;
7729         int                     i_lanname;
7730         int                     i_lanpltrusted;
7731         int                     i_lanplcallfoid;
7732         int                     i_laninline;
7733         int                     i_lanvalidator;
7734         int                     i_lanacl;
7735         int                     i_rlanacl;
7736         int                     i_initlanacl;
7737         int                     i_initrlanacl;
7738         int                     i_lanowner;
7739
7740         if (fout->remoteVersion >= 90600)
7741         {
7742                 PQExpBuffer acl_subquery = createPQExpBuffer();
7743                 PQExpBuffer racl_subquery = createPQExpBuffer();
7744                 PQExpBuffer initacl_subquery = createPQExpBuffer();
7745                 PQExpBuffer initracl_subquery = createPQExpBuffer();
7746
7747                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
7748                                                 initracl_subquery, "l.lanacl", "l.lanowner", "'l'",
7749                                                 dopt->binary_upgrade);
7750
7751                 /* pg_language has a laninline column */
7752                 appendPQExpBuffer(query, "SELECT l.tableoid, l.oid, "
7753                                                   "l.lanname, l.lanpltrusted, l.lanplcallfoid, "
7754                                                   "l.laninline, l.lanvalidator, "
7755                                                   "%s AS lanacl, "
7756                                                   "%s AS rlanacl, "
7757                                                   "%s AS initlanacl, "
7758                                                   "%s AS initrlanacl, "
7759                                                   "(%s l.lanowner) AS lanowner "
7760                                                   "FROM pg_language l "
7761                                                   "LEFT JOIN pg_init_privs pip ON "
7762                                                   "(l.oid = pip.objoid "
7763                                                   "AND pip.classoid = 'pg_language'::regclass "
7764                                                   "AND pip.objsubid = 0) "
7765                                                   "WHERE l.lanispl "
7766                                                   "ORDER BY l.oid",
7767                                                   acl_subquery->data,
7768                                                   racl_subquery->data,
7769                                                   initacl_subquery->data,
7770                                                   initracl_subquery->data,
7771                                                   username_subquery);
7772
7773                 destroyPQExpBuffer(acl_subquery);
7774                 destroyPQExpBuffer(racl_subquery);
7775                 destroyPQExpBuffer(initacl_subquery);
7776                 destroyPQExpBuffer(initracl_subquery);
7777         }
7778         else if (fout->remoteVersion >= 90000)
7779         {
7780                 /* pg_language has a laninline column */
7781                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7782                                                   "lanname, lanpltrusted, lanplcallfoid, "
7783                                                   "laninline, lanvalidator, lanacl, NULL AS rlanacl, "
7784                                                   "NULL AS initlanacl, NULL AS initrlanacl, "
7785                                                   "(%s lanowner) AS lanowner "
7786                                                   "FROM pg_language "
7787                                                   "WHERE lanispl "
7788                                                   "ORDER BY oid",
7789                                                   username_subquery);
7790         }
7791         else if (fout->remoteVersion >= 80300)
7792         {
7793                 /* pg_language has a lanowner column */
7794                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7795                                                   "lanname, lanpltrusted, lanplcallfoid, "
7796                                                   "0 AS laninline, lanvalidator, lanacl, "
7797                                                   "NULL AS rlanacl, "
7798                                                   "NULL AS initlanacl, NULL AS initrlanacl, "
7799                                                   "(%s lanowner) AS lanowner "
7800                                                   "FROM pg_language "
7801                                                   "WHERE lanispl "
7802                                                   "ORDER BY oid",
7803                                                   username_subquery);
7804         }
7805         else if (fout->remoteVersion >= 80100)
7806         {
7807                 /* Languages are owned by the bootstrap superuser, OID 10 */
7808                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7809                                                   "lanname, lanpltrusted, lanplcallfoid, "
7810                                                   "0 AS laninline, lanvalidator, lanacl, "
7811                                                   "NULL AS rlanacl, "
7812                                                   "NULL AS initlanacl, NULL AS initrlanacl, "
7813                                                   "(%s '10') AS lanowner "
7814                                                   "FROM pg_language "
7815                                                   "WHERE lanispl "
7816                                                   "ORDER BY oid",
7817                                                   username_subquery);
7818         }
7819         else
7820         {
7821                 /* Languages are owned by the bootstrap superuser, sysid 1 */
7822                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7823                                                   "lanname, lanpltrusted, lanplcallfoid, "
7824                                                   "0 AS laninline, lanvalidator, lanacl, "
7825                                                   "NULL AS rlanacl, "
7826                                                   "NULL AS initlanacl, NULL AS initrlanacl, "
7827                                                   "(%s '1') AS lanowner "
7828                                                   "FROM pg_language "
7829                                                   "WHERE lanispl "
7830                                                   "ORDER BY oid",
7831                                                   username_subquery);
7832         }
7833
7834         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7835
7836         ntups = PQntuples(res);
7837
7838         *numProcLangs = ntups;
7839
7840         planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
7841
7842         i_tableoid = PQfnumber(res, "tableoid");
7843         i_oid = PQfnumber(res, "oid");
7844         i_lanname = PQfnumber(res, "lanname");
7845         i_lanpltrusted = PQfnumber(res, "lanpltrusted");
7846         i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
7847         i_laninline = PQfnumber(res, "laninline");
7848         i_lanvalidator = PQfnumber(res, "lanvalidator");
7849         i_lanacl = PQfnumber(res, "lanacl");
7850         i_rlanacl = PQfnumber(res, "rlanacl");
7851         i_initlanacl = PQfnumber(res, "initlanacl");
7852         i_initrlanacl = PQfnumber(res, "initrlanacl");
7853         i_lanowner = PQfnumber(res, "lanowner");
7854
7855         for (i = 0; i < ntups; i++)
7856         {
7857                 planginfo[i].dobj.objType = DO_PROCLANG;
7858                 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7859                 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7860                 AssignDumpId(&planginfo[i].dobj);
7861
7862                 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
7863                 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
7864                 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
7865                 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
7866                 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
7867                 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
7868                 planginfo[i].rlanacl = pg_strdup(PQgetvalue(res, i, i_rlanacl));
7869                 planginfo[i].initlanacl = pg_strdup(PQgetvalue(res, i, i_initlanacl));
7870                 planginfo[i].initrlanacl = pg_strdup(PQgetvalue(res, i, i_initrlanacl));
7871                 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
7872
7873                 /* Decide whether we want to dump it */
7874                 selectDumpableProcLang(&(planginfo[i]), fout);
7875
7876                 /* Do not try to dump ACL if no ACL exists. */
7877                 if (PQgetisnull(res, i, i_lanacl) && PQgetisnull(res, i, i_rlanacl) &&
7878                         PQgetisnull(res, i, i_initlanacl) &&
7879                         PQgetisnull(res, i, i_initrlanacl))
7880                         planginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7881         }
7882
7883         PQclear(res);
7884
7885         destroyPQExpBuffer(query);
7886
7887         return planginfo;
7888 }
7889
7890 /*
7891  * getCasts
7892  *        get basic information about every cast in the system
7893  *
7894  * numCasts is set to the number of casts read in
7895  */
7896 CastInfo *
7897 getCasts(Archive *fout, int *numCasts)
7898 {
7899         PGresult   *res;
7900         int                     ntups;
7901         int                     i;
7902         PQExpBuffer query = createPQExpBuffer();
7903         CastInfo   *castinfo;
7904         int                     i_tableoid;
7905         int                     i_oid;
7906         int                     i_castsource;
7907         int                     i_casttarget;
7908         int                     i_castfunc;
7909         int                     i_castcontext;
7910         int                     i_castmethod;
7911
7912         if (fout->remoteVersion >= 80400)
7913         {
7914                 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7915                                                          "castsource, casttarget, castfunc, castcontext, "
7916                                                          "castmethod "
7917                                                          "FROM pg_cast ORDER BY 3,4");
7918         }
7919         else
7920         {
7921                 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7922                                                          "castsource, casttarget, castfunc, castcontext, "
7923                                                          "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
7924                                                          "FROM pg_cast ORDER BY 3,4");
7925         }
7926
7927         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7928
7929         ntups = PQntuples(res);
7930
7931         *numCasts = ntups;
7932
7933         castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
7934
7935         i_tableoid = PQfnumber(res, "tableoid");
7936         i_oid = PQfnumber(res, "oid");
7937         i_castsource = PQfnumber(res, "castsource");
7938         i_casttarget = PQfnumber(res, "casttarget");
7939         i_castfunc = PQfnumber(res, "castfunc");
7940         i_castcontext = PQfnumber(res, "castcontext");
7941         i_castmethod = PQfnumber(res, "castmethod");
7942
7943         for (i = 0; i < ntups; i++)
7944         {
7945                 PQExpBufferData namebuf;
7946                 TypeInfo   *sTypeInfo;
7947                 TypeInfo   *tTypeInfo;
7948
7949                 castinfo[i].dobj.objType = DO_CAST;
7950                 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7951                 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7952                 AssignDumpId(&castinfo[i].dobj);
7953                 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
7954                 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
7955                 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
7956                 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
7957                 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
7958
7959                 /*
7960                  * Try to name cast as concatenation of typnames.  This is only used
7961                  * for purposes of sorting.  If we fail to find either type, the name
7962                  * will be an empty string.
7963                  */
7964                 initPQExpBuffer(&namebuf);
7965                 sTypeInfo = findTypeByOid(castinfo[i].castsource);
7966                 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
7967                 if (sTypeInfo && tTypeInfo)
7968                         appendPQExpBuffer(&namebuf, "%s %s",
7969                                                           sTypeInfo->dobj.name, tTypeInfo->dobj.name);
7970                 castinfo[i].dobj.name = namebuf.data;
7971
7972                 /* Decide whether we want to dump it */
7973                 selectDumpableCast(&(castinfo[i]), fout);
7974
7975                 /* Casts do not currently have ACLs. */
7976                 castinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7977         }
7978
7979         PQclear(res);
7980
7981         destroyPQExpBuffer(query);
7982
7983         return castinfo;
7984 }
7985
7986 static char *
7987 get_language_name(Archive *fout, Oid langid)
7988 {
7989         PQExpBuffer query;
7990         PGresult   *res;
7991         char       *lanname;
7992
7993         query = createPQExpBuffer();
7994         appendPQExpBuffer(query, "SELECT lanname FROM pg_language WHERE oid = %u", langid);
7995         res = ExecuteSqlQueryForSingleRow(fout, query->data);
7996         lanname = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
7997         destroyPQExpBuffer(query);
7998         PQclear(res);
7999
8000         return lanname;
8001 }
8002
8003 /*
8004  * getTransforms
8005  *        get basic information about every transform in the system
8006  *
8007  * numTransforms is set to the number of transforms read in
8008  */
8009 TransformInfo *
8010 getTransforms(Archive *fout, int *numTransforms)
8011 {
8012         PGresult   *res;
8013         int                     ntups;
8014         int                     i;
8015         PQExpBuffer query;
8016         TransformInfo *transforminfo;
8017         int                     i_tableoid;
8018         int                     i_oid;
8019         int                     i_trftype;
8020         int                     i_trflang;
8021         int                     i_trffromsql;
8022         int                     i_trftosql;
8023
8024         /* Transforms didn't exist pre-9.5 */
8025         if (fout->remoteVersion < 90500)
8026         {
8027                 *numTransforms = 0;
8028                 return NULL;
8029         }
8030
8031         query = createPQExpBuffer();
8032
8033         appendPQExpBuffer(query, "SELECT tableoid, oid, "
8034                                           "trftype, trflang, trffromsql::oid, trftosql::oid "
8035                                           "FROM pg_transform "
8036                                           "ORDER BY 3,4");
8037
8038         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8039
8040         ntups = PQntuples(res);
8041
8042         *numTransforms = ntups;
8043
8044         transforminfo = (TransformInfo *) pg_malloc(ntups * sizeof(TransformInfo));
8045
8046         i_tableoid = PQfnumber(res, "tableoid");
8047         i_oid = PQfnumber(res, "oid");
8048         i_trftype = PQfnumber(res, "trftype");
8049         i_trflang = PQfnumber(res, "trflang");
8050         i_trffromsql = PQfnumber(res, "trffromsql");
8051         i_trftosql = PQfnumber(res, "trftosql");
8052
8053         for (i = 0; i < ntups; i++)
8054         {
8055                 PQExpBufferData namebuf;
8056                 TypeInfo   *typeInfo;
8057                 char       *lanname;
8058
8059                 transforminfo[i].dobj.objType = DO_TRANSFORM;
8060                 transforminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8061                 transforminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8062                 AssignDumpId(&transforminfo[i].dobj);
8063                 transforminfo[i].trftype = atooid(PQgetvalue(res, i, i_trftype));
8064                 transforminfo[i].trflang = atooid(PQgetvalue(res, i, i_trflang));
8065                 transforminfo[i].trffromsql = atooid(PQgetvalue(res, i, i_trffromsql));
8066                 transforminfo[i].trftosql = atooid(PQgetvalue(res, i, i_trftosql));
8067
8068                 /*
8069                  * Try to name transform as concatenation of type and language name.
8070                  * This is only used for purposes of sorting.  If we fail to find
8071                  * either, the name will be an empty string.
8072                  */
8073                 initPQExpBuffer(&namebuf);
8074                 typeInfo = findTypeByOid(transforminfo[i].trftype);
8075                 lanname = get_language_name(fout, transforminfo[i].trflang);
8076                 if (typeInfo && lanname)
8077                         appendPQExpBuffer(&namebuf, "%s %s",
8078                                                           typeInfo->dobj.name, lanname);
8079                 transforminfo[i].dobj.name = namebuf.data;
8080                 free(lanname);
8081
8082                 /* Decide whether we want to dump it */
8083                 selectDumpableObject(&(transforminfo[i].dobj), fout);
8084         }
8085
8086         PQclear(res);
8087
8088         destroyPQExpBuffer(query);
8089
8090         return transforminfo;
8091 }
8092
8093 /*
8094  * getTableAttrs -
8095  *        for each interesting table, read info about its attributes
8096  *        (names, types, default values, CHECK constraints, etc)
8097  *
8098  * This is implemented in a very inefficient way right now, looping
8099  * through the tblinfo and doing a join per table to find the attrs and their
8100  * types.  However, because we want type names and so forth to be named
8101  * relative to the schema of each table, we couldn't do it in just one
8102  * query.  (Maybe one query per schema?)
8103  *
8104  *      modifies tblinfo
8105  */
8106 void
8107 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
8108 {
8109         DumpOptions *dopt = fout->dopt;
8110         int                     i,
8111                                 j;
8112         PQExpBuffer q = createPQExpBuffer();
8113         int                     i_attnum;
8114         int                     i_attname;
8115         int                     i_atttypname;
8116         int                     i_atttypmod;
8117         int                     i_attstattarget;
8118         int                     i_attstorage;
8119         int                     i_typstorage;
8120         int                     i_attnotnull;
8121         int                     i_atthasdef;
8122         int                     i_attidentity;
8123         int                     i_attisdropped;
8124         int                     i_attlen;
8125         int                     i_attalign;
8126         int                     i_attislocal;
8127         int                     i_attoptions;
8128         int                     i_attcollation;
8129         int                     i_attfdwoptions;
8130         int                     i_attmissingval;
8131         PGresult   *res;
8132         int                     ntups;
8133         bool            hasdefaults;
8134
8135         for (i = 0; i < numTables; i++)
8136         {
8137                 TableInfo  *tbinfo = &tblinfo[i];
8138
8139                 /* Don't bother to collect info for sequences */
8140                 if (tbinfo->relkind == RELKIND_SEQUENCE)
8141                         continue;
8142
8143                 /* Don't bother with uninteresting tables, either */
8144                 if (!tbinfo->interesting)
8145                         continue;
8146
8147                 /* find all the user attributes and their types */
8148
8149                 /*
8150                  * we must read the attribute names in attribute number order! because
8151                  * we will use the attnum to index into the attnames array later.
8152                  */
8153                 if (g_verbose)
8154                         write_msg(NULL, "finding the columns and types of table \"%s.%s\"\n",
8155                                           tbinfo->dobj.namespace->dobj.name,
8156                                           tbinfo->dobj.name);
8157
8158                 resetPQExpBuffer(q);
8159
8160                 if (fout->remoteVersion >= 110000)
8161                 {
8162                         /* atthasmissing and attmissingval are new in 11 */
8163                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8164                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8165                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8166                                                           "a.attlen, a.attalign, a.attislocal, "
8167                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8168                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
8169                                                           "CASE WHEN a.attcollation <> t.typcollation "
8170                                                           "THEN a.attcollation ELSE 0 END AS attcollation, "
8171                                                           "a.attidentity, "
8172                                                           "pg_catalog.array_to_string(ARRAY("
8173                                                           "SELECT pg_catalog.quote_ident(option_name) || "
8174                                                           "' ' || pg_catalog.quote_literal(option_value) "
8175                                                           "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8176                                                           "ORDER BY option_name"
8177                                                           "), E',\n    ') AS attfdwoptions ,"
8178                                                           "CASE WHEN a.atthasmissing AND NOT a.attisdropped "
8179                                                           "THEN a.attmissingval ELSE null END AS attmissingval "
8180                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8181                                                           "ON a.atttypid = t.oid "
8182                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8183                                                           "AND a.attnum > 0::pg_catalog.int2 "
8184                                                           "ORDER BY a.attnum",
8185                                                           tbinfo->dobj.catId.oid);
8186                 }
8187                 else if (fout->remoteVersion >= 100000)
8188                 {
8189                         /*
8190                          * attidentity is new in version 10.
8191                          */
8192                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8193                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8194                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8195                                                           "a.attlen, a.attalign, a.attislocal, "
8196                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8197                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
8198                                                           "CASE WHEN a.attcollation <> t.typcollation "
8199                                                           "THEN a.attcollation ELSE 0 END AS attcollation, "
8200                                                           "a.attidentity, "
8201                                                           "pg_catalog.array_to_string(ARRAY("
8202                                                           "SELECT pg_catalog.quote_ident(option_name) || "
8203                                                           "' ' || pg_catalog.quote_literal(option_value) "
8204                                                           "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8205                                                           "ORDER BY option_name"
8206                                                           "), E',\n    ') AS attfdwoptions ,"
8207                                                           "NULL as attmissingval "
8208                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8209                                                           "ON a.atttypid = t.oid "
8210                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8211                                                           "AND a.attnum > 0::pg_catalog.int2 "
8212                                                           "ORDER BY a.attnum",
8213                                                           tbinfo->dobj.catId.oid);
8214                 }
8215                 else if (fout->remoteVersion >= 90200)
8216                 {
8217                         /*
8218                          * attfdwoptions is new in 9.2.
8219                          */
8220                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8221                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8222                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8223                                                           "a.attlen, a.attalign, a.attislocal, "
8224                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8225                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
8226                                                           "CASE WHEN a.attcollation <> t.typcollation "
8227                                                           "THEN a.attcollation ELSE 0 END AS attcollation, "
8228                                                           "pg_catalog.array_to_string(ARRAY("
8229                                                           "SELECT pg_catalog.quote_ident(option_name) || "
8230                                                           "' ' || pg_catalog.quote_literal(option_value) "
8231                                                           "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8232                                                           "ORDER BY option_name"
8233                                                           "), E',\n    ') AS attfdwoptions, "
8234                                                           "NULL as attmissingval "
8235                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8236                                                           "ON a.atttypid = t.oid "
8237                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8238                                                           "AND a.attnum > 0::pg_catalog.int2 "
8239                                                           "ORDER BY a.attnum",
8240                                                           tbinfo->dobj.catId.oid);
8241                 }
8242                 else if (fout->remoteVersion >= 90100)
8243                 {
8244                         /*
8245                          * attcollation is new in 9.1.  Since we only want to dump COLLATE
8246                          * clauses for attributes whose collation is different from their
8247                          * type's default, we use a CASE here to suppress uninteresting
8248                          * attcollations cheaply.
8249                          */
8250                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8251                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8252                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8253                                                           "a.attlen, a.attalign, a.attislocal, "
8254                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8255                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
8256                                                           "CASE WHEN a.attcollation <> t.typcollation "
8257                                                           "THEN a.attcollation ELSE 0 END AS attcollation, "
8258                                                           "NULL AS attfdwoptions, "
8259                                                           "NULL as attmissingval "
8260                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8261                                                           "ON a.atttypid = t.oid "
8262                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8263                                                           "AND a.attnum > 0::pg_catalog.int2 "
8264                                                           "ORDER BY a.attnum",
8265                                                           tbinfo->dobj.catId.oid);
8266                 }
8267                 else if (fout->remoteVersion >= 90000)
8268                 {
8269                         /* attoptions is new in 9.0 */
8270                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8271                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8272                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8273                                                           "a.attlen, a.attalign, a.attislocal, "
8274                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8275                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
8276                                                           "0 AS attcollation, "
8277                                                           "NULL AS attfdwoptions, "
8278                                                           "NULL as attmissingval "
8279                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8280                                                           "ON a.atttypid = t.oid "
8281                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8282                                                           "AND a.attnum > 0::pg_catalog.int2 "
8283                                                           "ORDER BY a.attnum",
8284                                                           tbinfo->dobj.catId.oid);
8285                 }
8286                 else
8287                 {
8288                         /* need left join here to not fail on dropped columns ... */
8289                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
8290                                                           "a.attstattarget, a.attstorage, t.typstorage, "
8291                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
8292                                                           "a.attlen, a.attalign, a.attislocal, "
8293                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
8294                                                           "'' AS attoptions, 0 AS attcollation, "
8295                                                           "NULL AS attfdwoptions, "
8296                                                           "NULL as attmissingval "
8297                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8298                                                           "ON a.atttypid = t.oid "
8299                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
8300                                                           "AND a.attnum > 0::pg_catalog.int2 "
8301                                                           "ORDER BY a.attnum",
8302                                                           tbinfo->dobj.catId.oid);
8303                 }
8304
8305                 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8306
8307                 ntups = PQntuples(res);
8308
8309                 i_attnum = PQfnumber(res, "attnum");
8310                 i_attname = PQfnumber(res, "attname");
8311                 i_atttypname = PQfnumber(res, "atttypname");
8312                 i_atttypmod = PQfnumber(res, "atttypmod");
8313                 i_attstattarget = PQfnumber(res, "attstattarget");
8314                 i_attstorage = PQfnumber(res, "attstorage");
8315                 i_typstorage = PQfnumber(res, "typstorage");
8316                 i_attnotnull = PQfnumber(res, "attnotnull");
8317                 i_atthasdef = PQfnumber(res, "atthasdef");
8318                 i_attidentity = PQfnumber(res, "attidentity");
8319                 i_attisdropped = PQfnumber(res, "attisdropped");
8320                 i_attlen = PQfnumber(res, "attlen");
8321                 i_attalign = PQfnumber(res, "attalign");
8322                 i_attislocal = PQfnumber(res, "attislocal");
8323                 i_attoptions = PQfnumber(res, "attoptions");
8324                 i_attcollation = PQfnumber(res, "attcollation");
8325                 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
8326                 i_attmissingval = PQfnumber(res, "attmissingval");
8327
8328                 tbinfo->numatts = ntups;
8329                 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
8330                 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
8331                 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
8332                 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
8333                 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
8334                 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
8335                 tbinfo->attidentity = (char *) pg_malloc(ntups * sizeof(char));
8336                 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
8337                 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
8338                 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
8339                 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
8340                 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
8341                 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
8342                 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
8343                 tbinfo->attmissingval = (char **) pg_malloc(ntups * sizeof(char *));
8344                 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
8345                 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
8346                 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
8347                 hasdefaults = false;
8348
8349                 for (j = 0; j < ntups; j++)
8350                 {
8351                         if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
8352                                 exit_horribly(NULL,
8353                                                           "invalid column numbering in table \"%s\"\n",
8354                                                           tbinfo->dobj.name);
8355                         tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
8356                         tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
8357                         tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
8358                         tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
8359                         tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
8360                         tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
8361                         tbinfo->attidentity[j] = (i_attidentity >= 0 ? *(PQgetvalue(res, j, i_attidentity)) : '\0');
8362                         tbinfo->needs_override = tbinfo->needs_override || (tbinfo->attidentity[j] == ATTRIBUTE_IDENTITY_ALWAYS);
8363                         tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
8364                         tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
8365                         tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
8366                         tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
8367                         tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
8368                         tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
8369                         tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
8370                         tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
8371                         tbinfo->attmissingval[j] = pg_strdup(PQgetvalue(res, j, i_attmissingval));
8372                         tbinfo->attrdefs[j] = NULL; /* fix below */
8373                         if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
8374                                 hasdefaults = true;
8375                         /* these flags will be set in flagInhAttrs() */
8376                         tbinfo->inhNotNull[j] = false;
8377                 }
8378
8379                 PQclear(res);
8380
8381                 /*
8382                  * Get info about column defaults
8383                  */
8384                 if (hasdefaults)
8385                 {
8386                         AttrDefInfo *attrdefs;
8387                         int                     numDefaults;
8388
8389                         if (g_verbose)
8390                                 write_msg(NULL, "finding default expressions of table \"%s.%s\"\n",
8391                                                   tbinfo->dobj.namespace->dobj.name,
8392                                                   tbinfo->dobj.name);
8393
8394                         printfPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
8395                                                           "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
8396                                                           "FROM pg_catalog.pg_attrdef "
8397                                                           "WHERE adrelid = '%u'::pg_catalog.oid",
8398                                                           tbinfo->dobj.catId.oid);
8399
8400                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8401
8402                         numDefaults = PQntuples(res);
8403                         attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
8404
8405                         for (j = 0; j < numDefaults; j++)
8406                         {
8407                                 int                     adnum;
8408
8409                                 adnum = atoi(PQgetvalue(res, j, 2));
8410
8411                                 if (adnum <= 0 || adnum > ntups)
8412                                         exit_horribly(NULL,
8413                                                                   "invalid adnum value %d for table \"%s\"\n",
8414                                                                   adnum, tbinfo->dobj.name);
8415
8416                                 /*
8417                                  * dropped columns shouldn't have defaults, but just in case,
8418                                  * ignore 'em
8419                                  */
8420                                 if (tbinfo->attisdropped[adnum - 1])
8421                                         continue;
8422
8423                                 attrdefs[j].dobj.objType = DO_ATTRDEF;
8424                                 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8425                                 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8426                                 AssignDumpId(&attrdefs[j].dobj);
8427                                 attrdefs[j].adtable = tbinfo;
8428                                 attrdefs[j].adnum = adnum;
8429                                 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
8430
8431                                 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
8432                                 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
8433
8434                                 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
8435
8436                                 /*
8437                                  * Defaults on a VIEW must always be dumped as separate ALTER
8438                                  * TABLE commands.  Defaults on regular tables are dumped as
8439                                  * part of the CREATE TABLE if possible, which it won't be if
8440                                  * the column is not going to be emitted explicitly.
8441                                  */
8442                                 if (tbinfo->relkind == RELKIND_VIEW)
8443                                 {
8444                                         attrdefs[j].separate = true;
8445                                 }
8446                                 else if (!shouldPrintColumn(dopt, tbinfo, adnum - 1))
8447                                 {
8448                                         /* column will be suppressed, print default separately */
8449                                         attrdefs[j].separate = true;
8450                                 }
8451                                 else
8452                                 {
8453                                         attrdefs[j].separate = false;
8454
8455                                         /*
8456                                          * Mark the default as needing to appear before the table,
8457                                          * so that any dependencies it has must be emitted before
8458                                          * the CREATE TABLE.  If this is not possible, we'll
8459                                          * change to "separate" mode while sorting dependencies.
8460                                          */
8461                                         addObjectDependency(&tbinfo->dobj,
8462                                                                                 attrdefs[j].dobj.dumpId);
8463                                 }
8464
8465                                 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
8466                         }
8467                         PQclear(res);
8468                 }
8469
8470                 /*
8471                  * Get info about table CHECK constraints
8472                  */
8473                 if (tbinfo->ncheck > 0)
8474                 {
8475                         ConstraintInfo *constrs;
8476                         int                     numConstrs;
8477
8478                         if (g_verbose)
8479                                 write_msg(NULL, "finding check constraints for table \"%s.%s\"\n",
8480                                                   tbinfo->dobj.namespace->dobj.name,
8481                                                   tbinfo->dobj.name);
8482
8483                         resetPQExpBuffer(q);
8484                         if (fout->remoteVersion >= 90200)
8485                         {
8486                                 /*
8487                                  * convalidated is new in 9.2 (actually, it is there in 9.1,
8488                                  * but it wasn't ever false for check constraints until 9.2).
8489                                  */
8490                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8491                                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8492                                                                   "conislocal, convalidated "
8493                                                                   "FROM pg_catalog.pg_constraint "
8494                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
8495                                                                   "   AND contype = 'c' "
8496                                                                   "ORDER BY conname",
8497                                                                   tbinfo->dobj.catId.oid);
8498                         }
8499                         else if (fout->remoteVersion >= 80400)
8500                         {
8501                                 /* conislocal is new in 8.4 */
8502                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8503                                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8504                                                                   "conislocal, true AS convalidated "
8505                                                                   "FROM pg_catalog.pg_constraint "
8506                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
8507                                                                   "   AND contype = 'c' "
8508                                                                   "ORDER BY conname",
8509                                                                   tbinfo->dobj.catId.oid);
8510                         }
8511                         else
8512                         {
8513                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8514                                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8515                                                                   "true AS conislocal, true AS convalidated "
8516                                                                   "FROM pg_catalog.pg_constraint "
8517                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
8518                                                                   "   AND contype = 'c' "
8519                                                                   "ORDER BY conname",
8520                                                                   tbinfo->dobj.catId.oid);
8521                         }
8522
8523                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8524
8525                         numConstrs = PQntuples(res);
8526                         if (numConstrs != tbinfo->ncheck)
8527                         {
8528                                 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
8529                                                                                  "expected %d check constraints on table \"%s\" but found %d\n",
8530                                                                                  tbinfo->ncheck),
8531                                                   tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
8532                                 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
8533                                 exit_nicely(1);
8534                         }
8535
8536                         constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
8537                         tbinfo->checkexprs = constrs;
8538
8539                         for (j = 0; j < numConstrs; j++)
8540                         {
8541                                 bool            validated = PQgetvalue(res, j, 5)[0] == 't';
8542
8543                                 constrs[j].dobj.objType = DO_CONSTRAINT;
8544                                 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8545                                 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8546                                 AssignDumpId(&constrs[j].dobj);
8547                                 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
8548                                 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
8549                                 constrs[j].contable = tbinfo;
8550                                 constrs[j].condomain = NULL;
8551                                 constrs[j].contype = 'c';
8552                                 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
8553                                 constrs[j].confrelid = InvalidOid;
8554                                 constrs[j].conindex = 0;
8555                                 constrs[j].condeferrable = false;
8556                                 constrs[j].condeferred = false;
8557                                 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
8558
8559                                 /*
8560                                  * An unvalidated constraint needs to be dumped separately, so
8561                                  * that potentially-violating existing data is loaded before
8562                                  * the constraint.
8563                                  */
8564                                 constrs[j].separate = !validated;
8565
8566                                 constrs[j].dobj.dump = tbinfo->dobj.dump;
8567
8568                                 /*
8569                                  * Mark the constraint as needing to appear before the table
8570                                  * --- this is so that any other dependencies of the
8571                                  * constraint will be emitted before we try to create the
8572                                  * table.  If the constraint is to be dumped separately, it
8573                                  * will be dumped after data is loaded anyway, so don't do it.
8574                                  * (There's an automatic dependency in the opposite direction
8575                                  * anyway, so don't need to add one manually here.)
8576                                  */
8577                                 if (!constrs[j].separate)
8578                                         addObjectDependency(&tbinfo->dobj,
8579                                                                                 constrs[j].dobj.dumpId);
8580
8581                                 /*
8582                                  * If the constraint is inherited, this will be detected later
8583                                  * (in pre-8.4 databases).  We also detect later if the
8584                                  * constraint must be split out from the table definition.
8585                                  */
8586                         }
8587                         PQclear(res);
8588                 }
8589         }
8590
8591         destroyPQExpBuffer(q);
8592 }
8593
8594 /*
8595  * Test whether a column should be printed as part of table's CREATE TABLE.
8596  * Column number is zero-based.
8597  *
8598  * Normally this is always true, but it's false for dropped columns, as well
8599  * as those that were inherited without any local definition.  (If we print
8600  * such a column it will mistakenly get pg_attribute.attislocal set to true.)
8601  * However, in binary_upgrade mode, we must print all such columns anyway and
8602  * fix the attislocal/attisdropped state later, so as to keep control of the
8603  * physical column order.
8604  *
8605  * This function exists because there are scattered nonobvious places that
8606  * must be kept in sync with this decision.
8607  */
8608 bool
8609 shouldPrintColumn(DumpOptions *dopt, TableInfo *tbinfo, int colno)
8610 {
8611         if (dopt->binary_upgrade)
8612                 return true;
8613         return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
8614 }
8615
8616
8617 /*
8618  * getTSParsers:
8619  *        read all text search parsers in the system catalogs and return them
8620  *        in the TSParserInfo* structure
8621  *
8622  *      numTSParsers is set to the number of parsers read in
8623  */
8624 TSParserInfo *
8625 getTSParsers(Archive *fout, int *numTSParsers)
8626 {
8627         PGresult   *res;
8628         int                     ntups;
8629         int                     i;
8630         PQExpBuffer query;
8631         TSParserInfo *prsinfo;
8632         int                     i_tableoid;
8633         int                     i_oid;
8634         int                     i_prsname;
8635         int                     i_prsnamespace;
8636         int                     i_prsstart;
8637         int                     i_prstoken;
8638         int                     i_prsend;
8639         int                     i_prsheadline;
8640         int                     i_prslextype;
8641
8642         /* Before 8.3, there is no built-in text search support */
8643         if (fout->remoteVersion < 80300)
8644         {
8645                 *numTSParsers = 0;
8646                 return NULL;
8647         }
8648
8649         query = createPQExpBuffer();
8650
8651         /*
8652          * find all text search objects, including builtin ones; we filter out
8653          * system-defined objects at dump-out time.
8654          */
8655
8656         appendPQExpBufferStr(query, "SELECT tableoid, oid, prsname, prsnamespace, "
8657                                                  "prsstart::oid, prstoken::oid, "
8658                                                  "prsend::oid, prsheadline::oid, prslextype::oid "
8659                                                  "FROM pg_ts_parser");
8660
8661         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8662
8663         ntups = PQntuples(res);
8664         *numTSParsers = ntups;
8665
8666         prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
8667
8668         i_tableoid = PQfnumber(res, "tableoid");
8669         i_oid = PQfnumber(res, "oid");
8670         i_prsname = PQfnumber(res, "prsname");
8671         i_prsnamespace = PQfnumber(res, "prsnamespace");
8672         i_prsstart = PQfnumber(res, "prsstart");
8673         i_prstoken = PQfnumber(res, "prstoken");
8674         i_prsend = PQfnumber(res, "prsend");
8675         i_prsheadline = PQfnumber(res, "prsheadline");
8676         i_prslextype = PQfnumber(res, "prslextype");
8677
8678         for (i = 0; i < ntups; i++)
8679         {
8680                 prsinfo[i].dobj.objType = DO_TSPARSER;
8681                 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8682                 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8683                 AssignDumpId(&prsinfo[i].dobj);
8684                 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
8685                 prsinfo[i].dobj.namespace =
8686                         findNamespace(fout,
8687                                                   atooid(PQgetvalue(res, i, i_prsnamespace)));
8688                 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
8689                 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
8690                 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
8691                 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
8692                 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
8693
8694                 /* Decide whether we want to dump it */
8695                 selectDumpableObject(&(prsinfo[i].dobj), fout);
8696
8697                 /* Text Search Parsers do not currently have ACLs. */
8698                 prsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8699         }
8700
8701         PQclear(res);
8702
8703         destroyPQExpBuffer(query);
8704
8705         return prsinfo;
8706 }
8707
8708 /*
8709  * getTSDictionaries:
8710  *        read all text search dictionaries in the system catalogs and return them
8711  *        in the TSDictInfo* structure
8712  *
8713  *      numTSDicts is set to the number of dictionaries read in
8714  */
8715 TSDictInfo *
8716 getTSDictionaries(Archive *fout, int *numTSDicts)
8717 {
8718         PGresult   *res;
8719         int                     ntups;
8720         int                     i;
8721         PQExpBuffer query;
8722         TSDictInfo *dictinfo;
8723         int                     i_tableoid;
8724         int                     i_oid;
8725         int                     i_dictname;
8726         int                     i_dictnamespace;
8727         int                     i_rolname;
8728         int                     i_dicttemplate;
8729         int                     i_dictinitoption;
8730
8731         /* Before 8.3, there is no built-in text search support */
8732         if (fout->remoteVersion < 80300)
8733         {
8734                 *numTSDicts = 0;
8735                 return NULL;
8736         }
8737
8738         query = createPQExpBuffer();
8739
8740         appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
8741                                           "dictnamespace, (%s dictowner) AS rolname, "
8742                                           "dicttemplate, dictinitoption "
8743                                           "FROM pg_ts_dict",
8744                                           username_subquery);
8745
8746         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8747
8748         ntups = PQntuples(res);
8749         *numTSDicts = ntups;
8750
8751         dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
8752
8753         i_tableoid = PQfnumber(res, "tableoid");
8754         i_oid = PQfnumber(res, "oid");
8755         i_dictname = PQfnumber(res, "dictname");
8756         i_dictnamespace = PQfnumber(res, "dictnamespace");
8757         i_rolname = PQfnumber(res, "rolname");
8758         i_dictinitoption = PQfnumber(res, "dictinitoption");
8759         i_dicttemplate = PQfnumber(res, "dicttemplate");
8760
8761         for (i = 0; i < ntups; i++)
8762         {
8763                 dictinfo[i].dobj.objType = DO_TSDICT;
8764                 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8765                 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8766                 AssignDumpId(&dictinfo[i].dobj);
8767                 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
8768                 dictinfo[i].dobj.namespace =
8769                         findNamespace(fout,
8770                                                   atooid(PQgetvalue(res, i, i_dictnamespace)));
8771                 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8772                 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
8773                 if (PQgetisnull(res, i, i_dictinitoption))
8774                         dictinfo[i].dictinitoption = NULL;
8775                 else
8776                         dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
8777
8778                 /* Decide whether we want to dump it */
8779                 selectDumpableObject(&(dictinfo[i].dobj), fout);
8780
8781                 /* Text Search Dictionaries do not currently have ACLs. */
8782                 dictinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8783         }
8784
8785         PQclear(res);
8786
8787         destroyPQExpBuffer(query);
8788
8789         return dictinfo;
8790 }
8791
8792 /*
8793  * getTSTemplates:
8794  *        read all text search templates in the system catalogs and return them
8795  *        in the TSTemplateInfo* structure
8796  *
8797  *      numTSTemplates is set to the number of templates read in
8798  */
8799 TSTemplateInfo *
8800 getTSTemplates(Archive *fout, int *numTSTemplates)
8801 {
8802         PGresult   *res;
8803         int                     ntups;
8804         int                     i;
8805         PQExpBuffer query;
8806         TSTemplateInfo *tmplinfo;
8807         int                     i_tableoid;
8808         int                     i_oid;
8809         int                     i_tmplname;
8810         int                     i_tmplnamespace;
8811         int                     i_tmplinit;
8812         int                     i_tmpllexize;
8813
8814         /* Before 8.3, there is no built-in text search support */
8815         if (fout->remoteVersion < 80300)
8816         {
8817                 *numTSTemplates = 0;
8818                 return NULL;
8819         }
8820
8821         query = createPQExpBuffer();
8822
8823         appendPQExpBufferStr(query, "SELECT tableoid, oid, tmplname, "
8824                                                  "tmplnamespace, tmplinit::oid, tmpllexize::oid "
8825                                                  "FROM pg_ts_template");
8826
8827         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8828
8829         ntups = PQntuples(res);
8830         *numTSTemplates = ntups;
8831
8832         tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
8833
8834         i_tableoid = PQfnumber(res, "tableoid");
8835         i_oid = PQfnumber(res, "oid");
8836         i_tmplname = PQfnumber(res, "tmplname");
8837         i_tmplnamespace = PQfnumber(res, "tmplnamespace");
8838         i_tmplinit = PQfnumber(res, "tmplinit");
8839         i_tmpllexize = PQfnumber(res, "tmpllexize");
8840
8841         for (i = 0; i < ntups; i++)
8842         {
8843                 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
8844                 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8845                 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8846                 AssignDumpId(&tmplinfo[i].dobj);
8847                 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
8848                 tmplinfo[i].dobj.namespace =
8849                         findNamespace(fout,
8850                                                   atooid(PQgetvalue(res, i, i_tmplnamespace)));
8851                 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
8852                 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
8853
8854                 /* Decide whether we want to dump it */
8855                 selectDumpableObject(&(tmplinfo[i].dobj), fout);
8856
8857                 /* Text Search Templates do not currently have ACLs. */
8858                 tmplinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8859         }
8860
8861         PQclear(res);
8862
8863         destroyPQExpBuffer(query);
8864
8865         return tmplinfo;
8866 }
8867
8868 /*
8869  * getTSConfigurations:
8870  *        read all text search configurations in the system catalogs and return
8871  *        them in the TSConfigInfo* structure
8872  *
8873  *      numTSConfigs is set to the number of configurations read in
8874  */
8875 TSConfigInfo *
8876 getTSConfigurations(Archive *fout, int *numTSConfigs)
8877 {
8878         PGresult   *res;
8879         int                     ntups;
8880         int                     i;
8881         PQExpBuffer query;
8882         TSConfigInfo *cfginfo;
8883         int                     i_tableoid;
8884         int                     i_oid;
8885         int                     i_cfgname;
8886         int                     i_cfgnamespace;
8887         int                     i_rolname;
8888         int                     i_cfgparser;
8889
8890         /* Before 8.3, there is no built-in text search support */
8891         if (fout->remoteVersion < 80300)
8892         {
8893                 *numTSConfigs = 0;
8894                 return NULL;
8895         }
8896
8897         query = createPQExpBuffer();
8898
8899         appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
8900                                           "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
8901                                           "FROM pg_ts_config",
8902                                           username_subquery);
8903
8904         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8905
8906         ntups = PQntuples(res);
8907         *numTSConfigs = ntups;
8908
8909         cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
8910
8911         i_tableoid = PQfnumber(res, "tableoid");
8912         i_oid = PQfnumber(res, "oid");
8913         i_cfgname = PQfnumber(res, "cfgname");
8914         i_cfgnamespace = PQfnumber(res, "cfgnamespace");
8915         i_rolname = PQfnumber(res, "rolname");
8916         i_cfgparser = PQfnumber(res, "cfgparser");
8917
8918         for (i = 0; i < ntups; i++)
8919         {
8920                 cfginfo[i].dobj.objType = DO_TSCONFIG;
8921                 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8922                 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8923                 AssignDumpId(&cfginfo[i].dobj);
8924                 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
8925                 cfginfo[i].dobj.namespace =
8926                         findNamespace(fout,
8927                                                   atooid(PQgetvalue(res, i, i_cfgnamespace)));
8928                 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8929                 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
8930
8931                 /* Decide whether we want to dump it */
8932                 selectDumpableObject(&(cfginfo[i].dobj), fout);
8933
8934                 /* Text Search Configurations do not currently have ACLs. */
8935                 cfginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8936         }
8937
8938         PQclear(res);
8939
8940         destroyPQExpBuffer(query);
8941
8942         return cfginfo;
8943 }
8944
8945 /*
8946  * getForeignDataWrappers:
8947  *        read all foreign-data wrappers in the system catalogs and return
8948  *        them in the FdwInfo* structure
8949  *
8950  *      numForeignDataWrappers is set to the number of fdws read in
8951  */
8952 FdwInfo *
8953 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
8954 {
8955         DumpOptions *dopt = fout->dopt;
8956         PGresult   *res;
8957         int                     ntups;
8958         int                     i;
8959         PQExpBuffer query;
8960         FdwInfo    *fdwinfo;
8961         int                     i_tableoid;
8962         int                     i_oid;
8963         int                     i_fdwname;
8964         int                     i_rolname;
8965         int                     i_fdwhandler;
8966         int                     i_fdwvalidator;
8967         int                     i_fdwacl;
8968         int                     i_rfdwacl;
8969         int                     i_initfdwacl;
8970         int                     i_initrfdwacl;
8971         int                     i_fdwoptions;
8972
8973         /* Before 8.4, there are no foreign-data wrappers */
8974         if (fout->remoteVersion < 80400)
8975         {
8976                 *numForeignDataWrappers = 0;
8977                 return NULL;
8978         }
8979
8980         query = createPQExpBuffer();
8981
8982         if (fout->remoteVersion >= 90600)
8983         {
8984                 PQExpBuffer acl_subquery = createPQExpBuffer();
8985                 PQExpBuffer racl_subquery = createPQExpBuffer();
8986                 PQExpBuffer initacl_subquery = createPQExpBuffer();
8987                 PQExpBuffer initracl_subquery = createPQExpBuffer();
8988
8989                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
8990                                                 initracl_subquery, "f.fdwacl", "f.fdwowner", "'F'",
8991                                                 dopt->binary_upgrade);
8992
8993                 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.fdwname, "
8994                                                   "(%s f.fdwowner) AS rolname, "
8995                                                   "f.fdwhandler::pg_catalog.regproc, "
8996                                                   "f.fdwvalidator::pg_catalog.regproc, "
8997                                                   "%s AS fdwacl, "
8998                                                   "%s AS rfdwacl, "
8999                                                   "%s AS initfdwacl, "
9000                                                   "%s AS initrfdwacl, "
9001                                                   "array_to_string(ARRAY("
9002                                                   "SELECT quote_ident(option_name) || ' ' || "
9003                                                   "quote_literal(option_value) "
9004                                                   "FROM pg_options_to_table(f.fdwoptions) "
9005                                                   "ORDER BY option_name"
9006                                                   "), E',\n    ') AS fdwoptions "
9007                                                   "FROM pg_foreign_data_wrapper f "
9008                                                   "LEFT JOIN pg_init_privs pip ON "
9009                                                   "(f.oid = pip.objoid "
9010                                                   "AND pip.classoid = 'pg_foreign_data_wrapper'::regclass "
9011                                                   "AND pip.objsubid = 0) ",
9012                                                   username_subquery,
9013                                                   acl_subquery->data,
9014                                                   racl_subquery->data,
9015                                                   initacl_subquery->data,
9016                                                   initracl_subquery->data);
9017
9018                 destroyPQExpBuffer(acl_subquery);
9019                 destroyPQExpBuffer(racl_subquery);
9020                 destroyPQExpBuffer(initacl_subquery);
9021                 destroyPQExpBuffer(initracl_subquery);
9022         }
9023         else if (fout->remoteVersion >= 90100)
9024         {
9025                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
9026                                                   "(%s fdwowner) AS rolname, "
9027                                                   "fdwhandler::pg_catalog.regproc, "
9028                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
9029                                                   "NULL as rfdwacl, "
9030                                                   "NULL as initfdwacl, NULL AS initrfdwacl, "
9031                                                   "array_to_string(ARRAY("
9032                                                   "SELECT quote_ident(option_name) || ' ' || "
9033                                                   "quote_literal(option_value) "
9034                                                   "FROM pg_options_to_table(fdwoptions) "
9035                                                   "ORDER BY option_name"
9036                                                   "), E',\n    ') AS fdwoptions "
9037                                                   "FROM pg_foreign_data_wrapper",
9038                                                   username_subquery);
9039         }
9040         else
9041         {
9042                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
9043                                                   "(%s fdwowner) AS rolname, "
9044                                                   "'-' AS fdwhandler, "
9045                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
9046                                                   "NULL as rfdwacl, "
9047                                                   "NULL as initfdwacl, NULL AS initrfdwacl, "
9048                                                   "array_to_string(ARRAY("
9049                                                   "SELECT quote_ident(option_name) || ' ' || "
9050                                                   "quote_literal(option_value) "
9051                                                   "FROM pg_options_to_table(fdwoptions) "
9052                                                   "ORDER BY option_name"
9053                                                   "), E',\n    ') AS fdwoptions "
9054                                                   "FROM pg_foreign_data_wrapper",
9055                                                   username_subquery);
9056         }
9057
9058         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9059
9060         ntups = PQntuples(res);
9061         *numForeignDataWrappers = ntups;
9062
9063         fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
9064
9065         i_tableoid = PQfnumber(res, "tableoid");
9066         i_oid = PQfnumber(res, "oid");
9067         i_fdwname = PQfnumber(res, "fdwname");
9068         i_rolname = PQfnumber(res, "rolname");
9069         i_fdwhandler = PQfnumber(res, "fdwhandler");
9070         i_fdwvalidator = PQfnumber(res, "fdwvalidator");
9071         i_fdwacl = PQfnumber(res, "fdwacl");
9072         i_rfdwacl = PQfnumber(res, "rfdwacl");
9073         i_initfdwacl = PQfnumber(res, "initfdwacl");
9074         i_initrfdwacl = PQfnumber(res, "initrfdwacl");
9075         i_fdwoptions = PQfnumber(res, "fdwoptions");
9076
9077         for (i = 0; i < ntups; i++)
9078         {
9079                 fdwinfo[i].dobj.objType = DO_FDW;
9080                 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9081                 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9082                 AssignDumpId(&fdwinfo[i].dobj);
9083                 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
9084                 fdwinfo[i].dobj.namespace = NULL;
9085                 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
9086                 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
9087                 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
9088                 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
9089                 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
9090                 fdwinfo[i].rfdwacl = pg_strdup(PQgetvalue(res, i, i_rfdwacl));
9091                 fdwinfo[i].initfdwacl = pg_strdup(PQgetvalue(res, i, i_initfdwacl));
9092                 fdwinfo[i].initrfdwacl = pg_strdup(PQgetvalue(res, i, i_initrfdwacl));
9093
9094                 /* Decide whether we want to dump it */
9095                 selectDumpableObject(&(fdwinfo[i].dobj), fout);
9096
9097                 /* Do not try to dump ACL if no ACL exists. */
9098                 if (PQgetisnull(res, i, i_fdwacl) && PQgetisnull(res, i, i_rfdwacl) &&
9099                         PQgetisnull(res, i, i_initfdwacl) &&
9100                         PQgetisnull(res, i, i_initrfdwacl))
9101                         fdwinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9102         }
9103
9104         PQclear(res);
9105
9106         destroyPQExpBuffer(query);
9107
9108         return fdwinfo;
9109 }
9110
9111 /*
9112  * getForeignServers:
9113  *        read all foreign servers in the system catalogs and return
9114  *        them in the ForeignServerInfo * structure
9115  *
9116  *      numForeignServers is set to the number of servers read in
9117  */
9118 ForeignServerInfo *
9119 getForeignServers(Archive *fout, int *numForeignServers)
9120 {
9121         DumpOptions *dopt = fout->dopt;
9122         PGresult   *res;
9123         int                     ntups;
9124         int                     i;
9125         PQExpBuffer query;
9126         ForeignServerInfo *srvinfo;
9127         int                     i_tableoid;
9128         int                     i_oid;
9129         int                     i_srvname;
9130         int                     i_rolname;
9131         int                     i_srvfdw;
9132         int                     i_srvtype;
9133         int                     i_srvversion;
9134         int                     i_srvacl;
9135         int                     i_rsrvacl;
9136         int                     i_initsrvacl;
9137         int                     i_initrsrvacl;
9138         int                     i_srvoptions;
9139
9140         /* Before 8.4, there are no foreign servers */
9141         if (fout->remoteVersion < 80400)
9142         {
9143                 *numForeignServers = 0;
9144                 return NULL;
9145         }
9146
9147         query = createPQExpBuffer();
9148
9149         if (fout->remoteVersion >= 90600)
9150         {
9151                 PQExpBuffer acl_subquery = createPQExpBuffer();
9152                 PQExpBuffer racl_subquery = createPQExpBuffer();
9153                 PQExpBuffer initacl_subquery = createPQExpBuffer();
9154                 PQExpBuffer initracl_subquery = createPQExpBuffer();
9155
9156                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9157                                                 initracl_subquery, "f.srvacl", "f.srvowner", "'S'",
9158                                                 dopt->binary_upgrade);
9159
9160                 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.srvname, "
9161                                                   "(%s f.srvowner) AS rolname, "
9162                                                   "f.srvfdw, f.srvtype, f.srvversion, "
9163                                                   "%s AS srvacl, "
9164                                                   "%s AS rsrvacl, "
9165                                                   "%s AS initsrvacl, "
9166                                                   "%s AS initrsrvacl, "
9167                                                   "array_to_string(ARRAY("
9168                                                   "SELECT quote_ident(option_name) || ' ' || "
9169                                                   "quote_literal(option_value) "
9170                                                   "FROM pg_options_to_table(f.srvoptions) "
9171                                                   "ORDER BY option_name"
9172                                                   "), E',\n    ') AS srvoptions "
9173                                                   "FROM pg_foreign_server f "
9174                                                   "LEFT JOIN pg_init_privs pip "
9175                                                   "ON (f.oid = pip.objoid "
9176                                                   "AND pip.classoid = 'pg_foreign_server'::regclass "
9177                                                   "AND pip.objsubid = 0) ",
9178                                                   username_subquery,
9179                                                   acl_subquery->data,
9180                                                   racl_subquery->data,
9181                                                   initacl_subquery->data,
9182                                                   initracl_subquery->data);
9183
9184                 destroyPQExpBuffer(acl_subquery);
9185                 destroyPQExpBuffer(racl_subquery);
9186                 destroyPQExpBuffer(initacl_subquery);
9187                 destroyPQExpBuffer(initracl_subquery);
9188         }
9189         else
9190         {
9191                 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
9192                                                   "(%s srvowner) AS rolname, "
9193                                                   "srvfdw, srvtype, srvversion, srvacl, "
9194                                                   "NULL AS rsrvacl, "
9195                                                   "NULL AS initsrvacl, NULL AS initrsrvacl, "
9196                                                   "array_to_string(ARRAY("
9197                                                   "SELECT quote_ident(option_name) || ' ' || "
9198                                                   "quote_literal(option_value) "
9199                                                   "FROM pg_options_to_table(srvoptions) "
9200                                                   "ORDER BY option_name"
9201                                                   "), E',\n    ') AS srvoptions "
9202                                                   "FROM pg_foreign_server",
9203                                                   username_subquery);
9204         }
9205
9206         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9207
9208         ntups = PQntuples(res);
9209         *numForeignServers = ntups;
9210
9211         srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
9212
9213         i_tableoid = PQfnumber(res, "tableoid");
9214         i_oid = PQfnumber(res, "oid");
9215         i_srvname = PQfnumber(res, "srvname");
9216         i_rolname = PQfnumber(res, "rolname");
9217         i_srvfdw = PQfnumber(res, "srvfdw");
9218         i_srvtype = PQfnumber(res, "srvtype");
9219         i_srvversion = PQfnumber(res, "srvversion");
9220         i_srvacl = PQfnumber(res, "srvacl");
9221         i_rsrvacl = PQfnumber(res, "rsrvacl");
9222         i_initsrvacl = PQfnumber(res, "initsrvacl");
9223         i_initrsrvacl = PQfnumber(res, "initrsrvacl");
9224         i_srvoptions = PQfnumber(res, "srvoptions");
9225
9226         for (i = 0; i < ntups; i++)
9227         {
9228                 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
9229                 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9230                 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9231                 AssignDumpId(&srvinfo[i].dobj);
9232                 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
9233                 srvinfo[i].dobj.namespace = NULL;
9234                 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
9235                 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
9236                 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
9237                 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
9238                 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
9239                 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
9240                 srvinfo[i].rsrvacl = pg_strdup(PQgetvalue(res, i, i_rsrvacl));
9241                 srvinfo[i].initsrvacl = pg_strdup(PQgetvalue(res, i, i_initsrvacl));
9242                 srvinfo[i].initrsrvacl = pg_strdup(PQgetvalue(res, i, i_initrsrvacl));
9243
9244                 /* Decide whether we want to dump it */
9245                 selectDumpableObject(&(srvinfo[i].dobj), fout);
9246
9247                 /* Do not try to dump ACL if no ACL exists. */
9248                 if (PQgetisnull(res, i, i_srvacl) && PQgetisnull(res, i, i_rsrvacl) &&
9249                         PQgetisnull(res, i, i_initsrvacl) &&
9250                         PQgetisnull(res, i, i_initrsrvacl))
9251                         srvinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
9252         }
9253
9254         PQclear(res);
9255
9256         destroyPQExpBuffer(query);
9257
9258         return srvinfo;
9259 }
9260
9261 /*
9262  * getDefaultACLs:
9263  *        read all default ACL information in the system catalogs and return
9264  *        them in the DefaultACLInfo structure
9265  *
9266  *      numDefaultACLs is set to the number of ACLs read in
9267  */
9268 DefaultACLInfo *
9269 getDefaultACLs(Archive *fout, int *numDefaultACLs)
9270 {
9271         DumpOptions *dopt = fout->dopt;
9272         DefaultACLInfo *daclinfo;
9273         PQExpBuffer query;
9274         PGresult   *res;
9275         int                     i_oid;
9276         int                     i_tableoid;
9277         int                     i_defaclrole;
9278         int                     i_defaclnamespace;
9279         int                     i_defaclobjtype;
9280         int                     i_defaclacl;
9281         int                     i_rdefaclacl;
9282         int                     i_initdefaclacl;
9283         int                     i_initrdefaclacl;
9284         int                     i,
9285                                 ntups;
9286
9287         if (fout->remoteVersion < 90000)
9288         {
9289                 *numDefaultACLs = 0;
9290                 return NULL;
9291         }
9292
9293         query = createPQExpBuffer();
9294
9295         if (fout->remoteVersion >= 90600)
9296         {
9297                 PQExpBuffer acl_subquery = createPQExpBuffer();
9298                 PQExpBuffer racl_subquery = createPQExpBuffer();
9299                 PQExpBuffer initacl_subquery = createPQExpBuffer();
9300                 PQExpBuffer initracl_subquery = createPQExpBuffer();
9301
9302                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
9303                                                 initracl_subquery, "defaclacl", "defaclrole",
9304                                                 "CASE WHEN defaclobjtype = 'S' THEN 's' ELSE defaclobjtype END::\"char\"",
9305                                                 dopt->binary_upgrade);
9306
9307                 appendPQExpBuffer(query, "SELECT d.oid, d.tableoid, "
9308                                                   "(%s d.defaclrole) AS defaclrole, "
9309                                                   "d.defaclnamespace, "
9310                                                   "d.defaclobjtype, "
9311                                                   "%s AS defaclacl, "
9312                                                   "%s AS rdefaclacl, "
9313                                                   "%s AS initdefaclacl, "
9314                                                   "%s AS initrdefaclacl "
9315                                                   "FROM pg_default_acl d "
9316                                                   "LEFT JOIN pg_init_privs pip ON "
9317                                                   "(d.oid = pip.objoid "
9318                                                   "AND pip.classoid = 'pg_default_acl'::regclass "
9319                                                   "AND pip.objsubid = 0) ",
9320                                                   username_subquery,
9321                                                   acl_subquery->data,
9322                                                   racl_subquery->data,
9323                                                   initacl_subquery->data,
9324                                                   initracl_subquery->data);
9325         }
9326         else
9327         {
9328                 appendPQExpBuffer(query, "SELECT oid, tableoid, "
9329                                                   "(%s defaclrole) AS defaclrole, "
9330                                                   "defaclnamespace, "
9331                                                   "defaclobjtype, "
9332                                                   "defaclacl, "
9333                                                   "NULL AS rdefaclacl, "
9334                                                   "NULL AS initdefaclacl, "
9335                                                   "NULL AS initrdefaclacl "
9336                                                   "FROM pg_default_acl",
9337                                                   username_subquery);
9338         }
9339
9340         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9341
9342         ntups = PQntuples(res);
9343         *numDefaultACLs = ntups;
9344
9345         daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
9346
9347         i_oid = PQfnumber(res, "oid");
9348         i_tableoid = PQfnumber(res, "tableoid");
9349         i_defaclrole = PQfnumber(res, "defaclrole");
9350         i_defaclnamespace = PQfnumber(res, "defaclnamespace");
9351         i_defaclobjtype = PQfnumber(res, "defaclobjtype");
9352         i_defaclacl = PQfnumber(res, "defaclacl");
9353         i_rdefaclacl = PQfnumber(res, "rdefaclacl");
9354         i_initdefaclacl = PQfnumber(res, "initdefaclacl");
9355         i_initrdefaclacl = PQfnumber(res, "initrdefaclacl");
9356
9357         for (i = 0; i < ntups; i++)
9358         {
9359                 Oid                     nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
9360
9361                 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
9362                 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9363                 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9364                 AssignDumpId(&daclinfo[i].dobj);
9365                 /* cheesy ... is it worth coming up with a better object name? */
9366                 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
9367
9368                 if (nspid != InvalidOid)
9369                         daclinfo[i].dobj.namespace = findNamespace(fout, nspid);
9370                 else
9371                         daclinfo[i].dobj.namespace = NULL;
9372
9373                 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
9374                 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
9375                 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
9376                 daclinfo[i].rdefaclacl = pg_strdup(PQgetvalue(res, i, i_rdefaclacl));
9377                 daclinfo[i].initdefaclacl = pg_strdup(PQgetvalue(res, i, i_initdefaclacl));
9378                 daclinfo[i].initrdefaclacl = pg_strdup(PQgetvalue(res, i, i_initrdefaclacl));
9379
9380                 /* Decide whether we want to dump it */
9381                 selectDumpableDefaultACL(&(daclinfo[i]), dopt);
9382         }
9383
9384         PQclear(res);
9385
9386         destroyPQExpBuffer(query);
9387
9388         return daclinfo;
9389 }
9390
9391 /*
9392  * dumpComment --
9393  *
9394  * This routine is used to dump any comments associated with the
9395  * object handed to this routine. The routine takes the object type
9396  * and object name (ready to print, except for schema decoration), plus
9397  * the namespace and owner of the object (for labeling the ArchiveEntry),
9398  * plus catalog ID and subid which are the lookup key for pg_description,
9399  * plus the dump ID for the object (for setting a dependency).
9400  * If a matching pg_description entry is found, it is dumped.
9401  *
9402  * Note: in some cases, such as comments for triggers and rules, the "type"
9403  * string really looks like, e.g., "TRIGGER name ON".  This is a bit of a hack
9404  * but it doesn't seem worth complicating the API for all callers to make
9405  * it cleaner.
9406  *
9407  * Note: although this routine takes a dumpId for dependency purposes,
9408  * that purpose is just to mark the dependency in the emitted dump file
9409  * for possible future use by pg_restore.  We do NOT use it for determining
9410  * ordering of the comment in the dump file, because this routine is called
9411  * after dependency sorting occurs.  This routine should be called just after
9412  * calling ArchiveEntry() for the specified object.
9413  */
9414 static void
9415 dumpComment(Archive *fout, const char *type, const char *name,
9416                         const char *namespace, const char *owner,
9417                         CatalogId catalogId, int subid, DumpId dumpId)
9418 {
9419         DumpOptions *dopt = fout->dopt;
9420         CommentItem *comments;
9421         int                     ncomments;
9422
9423         /* do nothing, if --no-comments is supplied */
9424         if (dopt->no_comments)
9425                 return;
9426
9427         /* Comments are schema not data ... except blob comments are data */
9428         if (strcmp(type, "LARGE OBJECT") != 0)
9429         {
9430                 if (dopt->dataOnly)
9431                         return;
9432         }
9433         else
9434         {
9435                 /* We do dump blob comments in binary-upgrade mode */
9436                 if (dopt->schemaOnly && !dopt->binary_upgrade)
9437                         return;
9438         }
9439
9440         /* Search for comments associated with catalogId, using table */
9441         ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
9442                                                          &comments);
9443
9444         /* Is there one matching the subid? */
9445         while (ncomments > 0)
9446         {
9447                 if (comments->objsubid == subid)
9448                         break;
9449                 comments++;
9450                 ncomments--;
9451         }
9452
9453         /* If a comment exists, build COMMENT ON statement */
9454         if (ncomments > 0)
9455         {
9456                 PQExpBuffer query = createPQExpBuffer();
9457                 PQExpBuffer tag = createPQExpBuffer();
9458
9459                 appendPQExpBuffer(query, "COMMENT ON %s ", type);
9460                 if (namespace && *namespace)
9461                         appendPQExpBuffer(query, "%s.", fmtId(namespace));
9462                 appendPQExpBuffer(query, "%s IS ", name);
9463                 appendStringLiteralAH(query, comments->descr, fout);
9464                 appendPQExpBufferStr(query, ";\n");
9465
9466                 appendPQExpBuffer(tag, "%s %s", type, name);
9467
9468                 /*
9469                  * We mark comments as SECTION_NONE because they really belong in the
9470                  * same section as their parent, whether that is pre-data or
9471                  * post-data.
9472                  */
9473                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9474                                          tag->data, namespace, NULL, owner,
9475                                          false, "COMMENT", SECTION_NONE,
9476                                          query->data, "", NULL,
9477                                          &(dumpId), 1,
9478                                          NULL, NULL);
9479
9480                 destroyPQExpBuffer(query);
9481                 destroyPQExpBuffer(tag);
9482         }
9483 }
9484
9485 /*
9486  * dumpTableComment --
9487  *
9488  * As above, but dump comments for both the specified table (or view)
9489  * and its columns.
9490  */
9491 static void
9492 dumpTableComment(Archive *fout, TableInfo *tbinfo,
9493                                  const char *reltypename)
9494 {
9495         DumpOptions *dopt = fout->dopt;
9496         CommentItem *comments;
9497         int                     ncomments;
9498         PQExpBuffer query;
9499         PQExpBuffer tag;
9500
9501         /* do nothing, if --no-comments is supplied */
9502         if (dopt->no_comments)
9503                 return;
9504
9505         /* Comments are SCHEMA not data */
9506         if (dopt->dataOnly)
9507                 return;
9508
9509         /* Search for comments associated with relation, using table */
9510         ncomments = findComments(fout,
9511                                                          tbinfo->dobj.catId.tableoid,
9512                                                          tbinfo->dobj.catId.oid,
9513                                                          &comments);
9514
9515         /* If comments exist, build COMMENT ON statements */
9516         if (ncomments <= 0)
9517                 return;
9518
9519         query = createPQExpBuffer();
9520         tag = createPQExpBuffer();
9521
9522         while (ncomments > 0)
9523         {
9524                 const char *descr = comments->descr;
9525                 int                     objsubid = comments->objsubid;
9526
9527                 if (objsubid == 0)
9528                 {
9529                         resetPQExpBuffer(tag);
9530                         appendPQExpBuffer(tag, "%s %s", reltypename,
9531                                                           fmtId(tbinfo->dobj.name));
9532
9533                         resetPQExpBuffer(query);
9534                         appendPQExpBuffer(query, "COMMENT ON %s %s IS ", reltypename,
9535                                                           fmtQualifiedDumpable(tbinfo));
9536                         appendStringLiteralAH(query, descr, fout);
9537                         appendPQExpBufferStr(query, ";\n");
9538
9539                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
9540                                                  tag->data,
9541                                                  tbinfo->dobj.namespace->dobj.name,
9542                                                  NULL, tbinfo->rolname,
9543                                                  false, "COMMENT", SECTION_NONE,
9544                                                  query->data, "", NULL,
9545                                                  &(tbinfo->dobj.dumpId), 1,
9546                                                  NULL, NULL);
9547                 }
9548                 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
9549                 {
9550                         resetPQExpBuffer(tag);
9551                         appendPQExpBuffer(tag, "COLUMN %s.",
9552                                                           fmtId(tbinfo->dobj.name));
9553                         appendPQExpBufferStr(tag, fmtId(tbinfo->attnames[objsubid - 1]));
9554
9555                         resetPQExpBuffer(query);
9556                         appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
9557                                                           fmtQualifiedDumpable(tbinfo));
9558                         appendPQExpBuffer(query, "%s IS ",
9559                                                           fmtId(tbinfo->attnames[objsubid - 1]));
9560                         appendStringLiteralAH(query, descr, fout);
9561                         appendPQExpBufferStr(query, ";\n");
9562
9563                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
9564                                                  tag->data,
9565                                                  tbinfo->dobj.namespace->dobj.name,
9566                                                  NULL, tbinfo->rolname,
9567                                                  false, "COMMENT", SECTION_NONE,
9568                                                  query->data, "", NULL,
9569                                                  &(tbinfo->dobj.dumpId), 1,
9570                                                  NULL, NULL);
9571                 }
9572
9573                 comments++;
9574                 ncomments--;
9575         }
9576
9577         destroyPQExpBuffer(query);
9578         destroyPQExpBuffer(tag);
9579 }
9580
9581 /*
9582  * findComments --
9583  *
9584  * Find the comment(s), if any, associated with the given object.  All the
9585  * objsubid values associated with the given classoid/objoid are found with
9586  * one search.
9587  */
9588 static int
9589 findComments(Archive *fout, Oid classoid, Oid objoid,
9590                          CommentItem **items)
9591 {
9592         /* static storage for table of comments */
9593         static CommentItem *comments = NULL;
9594         static int      ncomments = -1;
9595
9596         CommentItem *middle = NULL;
9597         CommentItem *low;
9598         CommentItem *high;
9599         int                     nmatch;
9600
9601         /* Get comments if we didn't already */
9602         if (ncomments < 0)
9603                 ncomments = collectComments(fout, &comments);
9604
9605         /*
9606          * Do binary search to find some item matching the object.
9607          */
9608         low = &comments[0];
9609         high = &comments[ncomments - 1];
9610         while (low <= high)
9611         {
9612                 middle = low + (high - low) / 2;
9613
9614                 if (classoid < middle->classoid)
9615                         high = middle - 1;
9616                 else if (classoid > middle->classoid)
9617                         low = middle + 1;
9618                 else if (objoid < middle->objoid)
9619                         high = middle - 1;
9620                 else if (objoid > middle->objoid)
9621                         low = middle + 1;
9622                 else
9623                         break;                          /* found a match */
9624         }
9625
9626         if (low > high)                         /* no matches */
9627         {
9628                 *items = NULL;
9629                 return 0;
9630         }
9631
9632         /*
9633          * Now determine how many items match the object.  The search loop
9634          * invariant still holds: only items between low and high inclusive could
9635          * match.
9636          */
9637         nmatch = 1;
9638         while (middle > low)
9639         {
9640                 if (classoid != middle[-1].classoid ||
9641                         objoid != middle[-1].objoid)
9642                         break;
9643                 middle--;
9644                 nmatch++;
9645         }
9646
9647         *items = middle;
9648
9649         middle += nmatch;
9650         while (middle <= high)
9651         {
9652                 if (classoid != middle->classoid ||
9653                         objoid != middle->objoid)
9654                         break;
9655                 middle++;
9656                 nmatch++;
9657         }
9658
9659         return nmatch;
9660 }
9661
9662 /*
9663  * collectComments --
9664  *
9665  * Construct a table of all comments available for database objects.
9666  * We used to do per-object queries for the comments, but it's much faster
9667  * to pull them all over at once, and on most databases the memory cost
9668  * isn't high.
9669  *
9670  * The table is sorted by classoid/objid/objsubid for speed in lookup.
9671  */
9672 static int
9673 collectComments(Archive *fout, CommentItem **items)
9674 {
9675         PGresult   *res;
9676         PQExpBuffer query;
9677         int                     i_description;
9678         int                     i_classoid;
9679         int                     i_objoid;
9680         int                     i_objsubid;
9681         int                     ntups;
9682         int                     i;
9683         CommentItem *comments;
9684
9685         query = createPQExpBuffer();
9686
9687         appendPQExpBufferStr(query, "SELECT description, classoid, objoid, objsubid "
9688                                                  "FROM pg_catalog.pg_description "
9689                                                  "ORDER BY classoid, objoid, objsubid");
9690
9691         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9692
9693         /* Construct lookup table containing OIDs in numeric form */
9694
9695         i_description = PQfnumber(res, "description");
9696         i_classoid = PQfnumber(res, "classoid");
9697         i_objoid = PQfnumber(res, "objoid");
9698         i_objsubid = PQfnumber(res, "objsubid");
9699
9700         ntups = PQntuples(res);
9701
9702         comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
9703
9704         for (i = 0; i < ntups; i++)
9705         {
9706                 comments[i].descr = PQgetvalue(res, i, i_description);
9707                 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
9708                 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
9709                 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
9710         }
9711
9712         /* Do NOT free the PGresult since we are keeping pointers into it */
9713         destroyPQExpBuffer(query);
9714
9715         *items = comments;
9716         return ntups;
9717 }
9718
9719 /*
9720  * dumpDumpableObject
9721  *
9722  * This routine and its subsidiaries are responsible for creating
9723  * ArchiveEntries (TOC objects) for each object to be dumped.
9724  */
9725 static void
9726 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
9727 {
9728         switch (dobj->objType)
9729         {
9730                 case DO_NAMESPACE:
9731                         dumpNamespace(fout, (NamespaceInfo *) dobj);
9732                         break;
9733                 case DO_EXTENSION:
9734                         dumpExtension(fout, (ExtensionInfo *) dobj);
9735                         break;
9736                 case DO_TYPE:
9737                         dumpType(fout, (TypeInfo *) dobj);
9738                         break;
9739                 case DO_SHELL_TYPE:
9740                         dumpShellType(fout, (ShellTypeInfo *) dobj);
9741                         break;
9742                 case DO_FUNC:
9743                         dumpFunc(fout, (FuncInfo *) dobj);
9744                         break;
9745                 case DO_AGG:
9746                         dumpAgg(fout, (AggInfo *) dobj);
9747                         break;
9748                 case DO_OPERATOR:
9749                         dumpOpr(fout, (OprInfo *) dobj);
9750                         break;
9751                 case DO_ACCESS_METHOD:
9752                         dumpAccessMethod(fout, (AccessMethodInfo *) dobj);
9753                         break;
9754                 case DO_OPCLASS:
9755                         dumpOpclass(fout, (OpclassInfo *) dobj);
9756                         break;
9757                 case DO_OPFAMILY:
9758                         dumpOpfamily(fout, (OpfamilyInfo *) dobj);
9759                         break;
9760                 case DO_COLLATION:
9761                         dumpCollation(fout, (CollInfo *) dobj);
9762                         break;
9763                 case DO_CONVERSION:
9764                         dumpConversion(fout, (ConvInfo *) dobj);
9765                         break;
9766                 case DO_TABLE:
9767                         dumpTable(fout, (TableInfo *) dobj);
9768                         break;
9769                 case DO_ATTRDEF:
9770                         dumpAttrDef(fout, (AttrDefInfo *) dobj);
9771                         break;
9772                 case DO_INDEX:
9773                         dumpIndex(fout, (IndxInfo *) dobj);
9774                         break;
9775                 case DO_INDEX_ATTACH:
9776                         dumpIndexAttach(fout, (IndexAttachInfo *) dobj);
9777                         break;
9778                 case DO_STATSEXT:
9779                         dumpStatisticsExt(fout, (StatsExtInfo *) dobj);
9780                         break;
9781                 case DO_REFRESH_MATVIEW:
9782                         refreshMatViewData(fout, (TableDataInfo *) dobj);
9783                         break;
9784                 case DO_RULE:
9785                         dumpRule(fout, (RuleInfo *) dobj);
9786                         break;
9787                 case DO_TRIGGER:
9788                         dumpTrigger(fout, (TriggerInfo *) dobj);
9789                         break;
9790                 case DO_EVENT_TRIGGER:
9791                         dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
9792                         break;
9793                 case DO_CONSTRAINT:
9794                         dumpConstraint(fout, (ConstraintInfo *) dobj);
9795                         break;
9796                 case DO_FK_CONSTRAINT:
9797                         dumpConstraint(fout, (ConstraintInfo *) dobj);
9798                         break;
9799                 case DO_PROCLANG:
9800                         dumpProcLang(fout, (ProcLangInfo *) dobj);
9801                         break;
9802                 case DO_CAST:
9803                         dumpCast(fout, (CastInfo *) dobj);
9804                         break;
9805                 case DO_TRANSFORM:
9806                         dumpTransform(fout, (TransformInfo *) dobj);
9807                         break;
9808                 case DO_SEQUENCE_SET:
9809                         dumpSequenceData(fout, (TableDataInfo *) dobj);
9810                         break;
9811                 case DO_TABLE_DATA:
9812                         dumpTableData(fout, (TableDataInfo *) dobj);
9813                         break;
9814                 case DO_DUMMY_TYPE:
9815                         /* table rowtypes and array types are never dumped separately */
9816                         break;
9817                 case DO_TSPARSER:
9818                         dumpTSParser(fout, (TSParserInfo *) dobj);
9819                         break;
9820                 case DO_TSDICT:
9821                         dumpTSDictionary(fout, (TSDictInfo *) dobj);
9822                         break;
9823                 case DO_TSTEMPLATE:
9824                         dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
9825                         break;
9826                 case DO_TSCONFIG:
9827                         dumpTSConfig(fout, (TSConfigInfo *) dobj);
9828                         break;
9829                 case DO_FDW:
9830                         dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
9831                         break;
9832                 case DO_FOREIGN_SERVER:
9833                         dumpForeignServer(fout, (ForeignServerInfo *) dobj);
9834                         break;
9835                 case DO_DEFAULT_ACL:
9836                         dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
9837                         break;
9838                 case DO_BLOB:
9839                         dumpBlob(fout, (BlobInfo *) dobj);
9840                         break;
9841                 case DO_BLOB_DATA:
9842                         if (dobj->dump & DUMP_COMPONENT_DATA)
9843                                 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
9844                                                          dobj->name, NULL, NULL, "",
9845                                                          false, "BLOBS", SECTION_DATA,
9846                                                          "", "", NULL,
9847                                                          NULL, 0,
9848                                                          dumpBlobs, NULL);
9849                         break;
9850                 case DO_POLICY:
9851                         dumpPolicy(fout, (PolicyInfo *) dobj);
9852                         break;
9853                 case DO_PUBLICATION:
9854                         dumpPublication(fout, (PublicationInfo *) dobj);
9855                         break;
9856                 case DO_PUBLICATION_REL:
9857                         dumpPublicationTable(fout, (PublicationRelInfo *) dobj);
9858                         break;
9859                 case DO_SUBSCRIPTION:
9860                         dumpSubscription(fout, (SubscriptionInfo *) dobj);
9861                         break;
9862                 case DO_PRE_DATA_BOUNDARY:
9863                 case DO_POST_DATA_BOUNDARY:
9864                         /* never dumped, nothing to do */
9865                         break;
9866         }
9867 }
9868
9869 /*
9870  * dumpNamespace
9871  *        writes out to fout the queries to recreate a user-defined namespace
9872  */
9873 static void
9874 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
9875 {
9876         DumpOptions *dopt = fout->dopt;
9877         PQExpBuffer q;
9878         PQExpBuffer delq;
9879         char       *qnspname;
9880
9881         /* Skip if not to be dumped */
9882         if (!nspinfo->dobj.dump || dopt->dataOnly)
9883                 return;
9884
9885         q = createPQExpBuffer();
9886         delq = createPQExpBuffer();
9887
9888         qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
9889
9890         appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
9891
9892         appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
9893
9894         if (dopt->binary_upgrade)
9895                 binary_upgrade_extension_member(q, &nspinfo->dobj,
9896                                                                                 "SCHEMA", qnspname, NULL);
9897
9898         if (nspinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9899                 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
9900                                          nspinfo->dobj.name,
9901                                          NULL, NULL,
9902                                          nspinfo->rolname,
9903                                          false, "SCHEMA", SECTION_PRE_DATA,
9904                                          q->data, delq->data, NULL,
9905                                          NULL, 0,
9906                                          NULL, NULL);
9907
9908         /* Dump Schema Comments and Security Labels */
9909         if (nspinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9910                 dumpComment(fout, "SCHEMA", qnspname,
9911                                         NULL, nspinfo->rolname,
9912                                         nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9913
9914         if (nspinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9915                 dumpSecLabel(fout, "SCHEMA", qnspname,
9916                                          NULL, nspinfo->rolname,
9917                                          nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9918
9919         if (nspinfo->dobj.dump & DUMP_COMPONENT_ACL)
9920                 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
9921                                 qnspname, NULL, NULL,
9922                                 nspinfo->rolname, nspinfo->nspacl, nspinfo->rnspacl,
9923                                 nspinfo->initnspacl, nspinfo->initrnspacl);
9924
9925         free(qnspname);
9926
9927         destroyPQExpBuffer(q);
9928         destroyPQExpBuffer(delq);
9929 }
9930
9931 /*
9932  * dumpExtension
9933  *        writes out to fout the queries to recreate an extension
9934  */
9935 static void
9936 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
9937 {
9938         DumpOptions *dopt = fout->dopt;
9939         PQExpBuffer q;
9940         PQExpBuffer delq;
9941         char       *qextname;
9942
9943         /* Skip if not to be dumped */
9944         if (!extinfo->dobj.dump || dopt->dataOnly)
9945                 return;
9946
9947         q = createPQExpBuffer();
9948         delq = createPQExpBuffer();
9949
9950         qextname = pg_strdup(fmtId(extinfo->dobj.name));
9951
9952         appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
9953
9954         if (!dopt->binary_upgrade)
9955         {
9956                 /*
9957                  * In a regular dump, we simply create the extension, intentionally
9958                  * not specifying a version, so that the destination installation's
9959                  * default version is used.
9960                  *
9961                  * Use of IF NOT EXISTS here is unlike our behavior for other object
9962                  * types; but there are various scenarios in which it's convenient to
9963                  * manually create the desired extension before restoring, so we
9964                  * prefer to allow it to exist already.
9965                  */
9966                 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
9967                                                   qextname, fmtId(extinfo->namespace));
9968         }
9969         else
9970         {
9971                 /*
9972                  * In binary-upgrade mode, it's critical to reproduce the state of the
9973                  * database exactly, so our procedure is to create an empty extension,
9974                  * restore all the contained objects normally, and add them to the
9975                  * extension one by one.  This function performs just the first of
9976                  * those steps.  binary_upgrade_extension_member() takes care of
9977                  * adding member objects as they're created.
9978                  */
9979                 int                     i;
9980                 int                     n;
9981
9982                 appendPQExpBufferStr(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
9983
9984                 /*
9985                  * We unconditionally create the extension, so we must drop it if it
9986                  * exists.  This could happen if the user deleted 'plpgsql' and then
9987                  * readded it, causing its oid to be greater than g_last_builtin_oid.
9988                  */
9989                 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
9990
9991                 appendPQExpBufferStr(q,
9992                                                          "SELECT pg_catalog.binary_upgrade_create_empty_extension(");
9993                 appendStringLiteralAH(q, extinfo->dobj.name, fout);
9994                 appendPQExpBufferStr(q, ", ");
9995                 appendStringLiteralAH(q, extinfo->namespace, fout);
9996                 appendPQExpBufferStr(q, ", ");
9997                 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
9998                 appendStringLiteralAH(q, extinfo->extversion, fout);
9999                 appendPQExpBufferStr(q, ", ");
10000
10001                 /*
10002                  * Note that we're pushing extconfig (an OID array) back into
10003                  * pg_extension exactly as-is.  This is OK because pg_class OIDs are
10004                  * preserved in binary upgrade.
10005                  */
10006                 if (strlen(extinfo->extconfig) > 2)
10007                         appendStringLiteralAH(q, extinfo->extconfig, fout);
10008                 else
10009                         appendPQExpBufferStr(q, "NULL");
10010                 appendPQExpBufferStr(q, ", ");
10011                 if (strlen(extinfo->extcondition) > 2)
10012                         appendStringLiteralAH(q, extinfo->extcondition, fout);
10013                 else
10014                         appendPQExpBufferStr(q, "NULL");
10015                 appendPQExpBufferStr(q, ", ");
10016                 appendPQExpBufferStr(q, "ARRAY[");
10017                 n = 0;
10018                 for (i = 0; i < extinfo->dobj.nDeps; i++)
10019                 {
10020                         DumpableObject *extobj;
10021
10022                         extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
10023                         if (extobj && extobj->objType == DO_EXTENSION)
10024                         {
10025                                 if (n++ > 0)
10026                                         appendPQExpBufferChar(q, ',');
10027                                 appendStringLiteralAH(q, extobj->name, fout);
10028                         }
10029                 }
10030                 appendPQExpBufferStr(q, "]::pg_catalog.text[]");
10031                 appendPQExpBufferStr(q, ");\n");
10032         }
10033
10034         if (extinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10035                 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
10036                                          extinfo->dobj.name,
10037                                          NULL, NULL,
10038                                          "",
10039                                          false, "EXTENSION", SECTION_PRE_DATA,
10040                                          q->data, delq->data, NULL,
10041                                          NULL, 0,
10042                                          NULL, NULL);
10043
10044         /* Dump Extension Comments and Security Labels */
10045         if (extinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10046                 dumpComment(fout, "EXTENSION", qextname,
10047                                         NULL, "",
10048                                         extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
10049
10050         if (extinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10051                 dumpSecLabel(fout, "EXTENSION", qextname,
10052                                          NULL, "",
10053                                          extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
10054
10055         free(qextname);
10056
10057         destroyPQExpBuffer(q);
10058         destroyPQExpBuffer(delq);
10059 }
10060
10061 /*
10062  * dumpType
10063  *        writes out to fout the queries to recreate a user-defined type
10064  */
10065 static void
10066 dumpType(Archive *fout, TypeInfo *tyinfo)
10067 {
10068         DumpOptions *dopt = fout->dopt;
10069
10070         /* Skip if not to be dumped */
10071         if (!tyinfo->dobj.dump || dopt->dataOnly)
10072                 return;
10073
10074         /* Dump out in proper style */
10075         if (tyinfo->typtype == TYPTYPE_BASE)
10076                 dumpBaseType(fout, tyinfo);
10077         else if (tyinfo->typtype == TYPTYPE_DOMAIN)
10078                 dumpDomain(fout, tyinfo);
10079         else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
10080                 dumpCompositeType(fout, tyinfo);
10081         else if (tyinfo->typtype == TYPTYPE_ENUM)
10082                 dumpEnumType(fout, tyinfo);
10083         else if (tyinfo->typtype == TYPTYPE_RANGE)
10084                 dumpRangeType(fout, tyinfo);
10085         else if (tyinfo->typtype == TYPTYPE_PSEUDO && !tyinfo->isDefined)
10086                 dumpUndefinedType(fout, tyinfo);
10087         else
10088                 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
10089                                   tyinfo->dobj.name);
10090 }
10091
10092 /*
10093  * dumpEnumType
10094  *        writes out to fout the queries to recreate a user-defined enum type
10095  */
10096 static void
10097 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
10098 {
10099         DumpOptions *dopt = fout->dopt;
10100         PQExpBuffer q = createPQExpBuffer();
10101         PQExpBuffer delq = createPQExpBuffer();
10102         PQExpBuffer query = createPQExpBuffer();
10103         PGresult   *res;
10104         int                     num,
10105                                 i;
10106         Oid                     enum_oid;
10107         char       *qtypname;
10108         char       *qualtypname;
10109         char       *label;
10110
10111         if (fout->remoteVersion >= 90100)
10112                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10113                                                   "FROM pg_catalog.pg_enum "
10114                                                   "WHERE enumtypid = '%u'"
10115                                                   "ORDER BY enumsortorder",
10116                                                   tyinfo->dobj.catId.oid);
10117         else
10118                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
10119                                                   "FROM pg_catalog.pg_enum "
10120                                                   "WHERE enumtypid = '%u'"
10121                                                   "ORDER BY oid",
10122                                                   tyinfo->dobj.catId.oid);
10123
10124         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10125
10126         num = PQntuples(res);
10127
10128         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10129         qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10130
10131         /*
10132          * CASCADE shouldn't be required here as for normal types since the I/O
10133          * functions are generic and do not get dropped.
10134          */
10135         appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10136
10137         if (dopt->binary_upgrade)
10138                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10139                                                                                                  tyinfo->dobj.catId.oid,
10140                                                                                                  false);
10141
10142         appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
10143                                           qualtypname);
10144
10145         if (!dopt->binary_upgrade)
10146         {
10147                 /* Labels with server-assigned oids */
10148                 for (i = 0; i < num; i++)
10149                 {
10150                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10151                         if (i > 0)
10152                                 appendPQExpBufferChar(q, ',');
10153                         appendPQExpBufferStr(q, "\n    ");
10154                         appendStringLiteralAH(q, label, fout);
10155                 }
10156         }
10157
10158         appendPQExpBufferStr(q, "\n);\n");
10159
10160         if (dopt->binary_upgrade)
10161         {
10162                 /* Labels with dump-assigned (preserved) oids */
10163                 for (i = 0; i < num; i++)
10164                 {
10165                         enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
10166                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
10167
10168                         if (i == 0)
10169                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
10170                         appendPQExpBuffer(q,
10171                                                           "SELECT pg_catalog.binary_upgrade_set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
10172                                                           enum_oid);
10173                         appendPQExpBuffer(q, "ALTER TYPE %s ADD VALUE ", qualtypname);
10174                         appendStringLiteralAH(q, label, fout);
10175                         appendPQExpBufferStr(q, ";\n\n");
10176                 }
10177         }
10178
10179         if (dopt->binary_upgrade)
10180                 binary_upgrade_extension_member(q, &tyinfo->dobj,
10181                                                                                 "TYPE", qtypname,
10182                                                                                 tyinfo->dobj.namespace->dobj.name);
10183
10184         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10185                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10186                                          tyinfo->dobj.name,
10187                                          tyinfo->dobj.namespace->dobj.name,
10188                                          NULL,
10189                                          tyinfo->rolname, false,
10190                                          "TYPE", SECTION_PRE_DATA,
10191                                          q->data, delq->data, NULL,
10192                                          NULL, 0,
10193                                          NULL, NULL);
10194
10195         /* Dump Type Comments and Security Labels */
10196         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10197                 dumpComment(fout, "TYPE", qtypname,
10198                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10199                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10200
10201         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10202                 dumpSecLabel(fout, "TYPE", qtypname,
10203                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10204                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10205
10206         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10207                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10208                                 qtypname, NULL,
10209                                 tyinfo->dobj.namespace->dobj.name,
10210                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10211                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10212
10213         PQclear(res);
10214         destroyPQExpBuffer(q);
10215         destroyPQExpBuffer(delq);
10216         destroyPQExpBuffer(query);
10217         free(qtypname);
10218         free(qualtypname);
10219 }
10220
10221 /*
10222  * dumpRangeType
10223  *        writes out to fout the queries to recreate a user-defined range type
10224  */
10225 static void
10226 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
10227 {
10228         DumpOptions *dopt = fout->dopt;
10229         PQExpBuffer q = createPQExpBuffer();
10230         PQExpBuffer delq = createPQExpBuffer();
10231         PQExpBuffer query = createPQExpBuffer();
10232         PGresult   *res;
10233         Oid                     collationOid;
10234         char       *qtypname;
10235         char       *qualtypname;
10236         char       *procname;
10237
10238         appendPQExpBuffer(query,
10239                                           "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
10240                                           "opc.opcname AS opcname, "
10241                                           "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
10242                                           "  WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
10243                                           "opc.opcdefault, "
10244                                           "CASE WHEN rngcollation = st.typcollation THEN 0 "
10245                                           "     ELSE rngcollation END AS collation, "
10246                                           "rngcanonical, rngsubdiff "
10247                                           "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
10248                                           "     pg_catalog.pg_opclass opc "
10249                                           "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
10250                                           "rngtypid = '%u'",
10251                                           tyinfo->dobj.catId.oid);
10252
10253         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10254
10255         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10256         qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10257
10258         /*
10259          * CASCADE shouldn't be required here as for normal types since the I/O
10260          * functions are generic and do not get dropped.
10261          */
10262         appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10263
10264         if (dopt->binary_upgrade)
10265                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10266                                                                                                  tyinfo->dobj.catId.oid,
10267                                                                                                  false);
10268
10269         appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
10270                                           qualtypname);
10271
10272         appendPQExpBuffer(q, "\n    subtype = %s",
10273                                           PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
10274
10275         /* print subtype_opclass only if not default for subtype */
10276         if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
10277         {
10278                 char       *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
10279                 char       *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
10280
10281                 appendPQExpBuffer(q, ",\n    subtype_opclass = %s.",
10282                                                   fmtId(nspname));
10283                 appendPQExpBufferStr(q, fmtId(opcname));
10284         }
10285
10286         collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
10287         if (OidIsValid(collationOid))
10288         {
10289                 CollInfo   *coll = findCollationByOid(collationOid);
10290
10291                 if (coll)
10292                         appendPQExpBuffer(q, ",\n    collation = %s",
10293                                                           fmtQualifiedDumpable(coll));
10294         }
10295
10296         procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
10297         if (strcmp(procname, "-") != 0)
10298                 appendPQExpBuffer(q, ",\n    canonical = %s", procname);
10299
10300         procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
10301         if (strcmp(procname, "-") != 0)
10302                 appendPQExpBuffer(q, ",\n    subtype_diff = %s", procname);
10303
10304         appendPQExpBufferStr(q, "\n);\n");
10305
10306         if (dopt->binary_upgrade)
10307                 binary_upgrade_extension_member(q, &tyinfo->dobj,
10308                                                                                 "TYPE", qtypname,
10309                                                                                 tyinfo->dobj.namespace->dobj.name);
10310
10311         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10312                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10313                                          tyinfo->dobj.name,
10314                                          tyinfo->dobj.namespace->dobj.name,
10315                                          NULL,
10316                                          tyinfo->rolname, false,
10317                                          "TYPE", SECTION_PRE_DATA,
10318                                          q->data, delq->data, NULL,
10319                                          NULL, 0,
10320                                          NULL, NULL);
10321
10322         /* Dump Type Comments and Security Labels */
10323         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10324                 dumpComment(fout, "TYPE", qtypname,
10325                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10326                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10327
10328         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10329                 dumpSecLabel(fout, "TYPE", qtypname,
10330                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10331                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10332
10333         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10334                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10335                                 qtypname, NULL,
10336                                 tyinfo->dobj.namespace->dobj.name,
10337                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10338                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10339
10340         PQclear(res);
10341         destroyPQExpBuffer(q);
10342         destroyPQExpBuffer(delq);
10343         destroyPQExpBuffer(query);
10344         free(qtypname);
10345         free(qualtypname);
10346 }
10347
10348 /*
10349  * dumpUndefinedType
10350  *        writes out to fout the queries to recreate a !typisdefined type
10351  *
10352  * This is a shell type, but we use different terminology to distinguish
10353  * this case from where we have to emit a shell type definition to break
10354  * circular dependencies.  An undefined type shouldn't ever have anything
10355  * depending on it.
10356  */
10357 static void
10358 dumpUndefinedType(Archive *fout, TypeInfo *tyinfo)
10359 {
10360         DumpOptions *dopt = fout->dopt;
10361         PQExpBuffer q = createPQExpBuffer();
10362         PQExpBuffer delq = createPQExpBuffer();
10363         char       *qtypname;
10364         char       *qualtypname;
10365
10366         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10367         qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10368
10369         appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
10370
10371         if (dopt->binary_upgrade)
10372                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10373                                                                                                  tyinfo->dobj.catId.oid,
10374                                                                                                  false);
10375
10376         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
10377                                           qualtypname);
10378
10379         if (dopt->binary_upgrade)
10380                 binary_upgrade_extension_member(q, &tyinfo->dobj,
10381                                                                                 "TYPE", qtypname,
10382                                                                                 tyinfo->dobj.namespace->dobj.name);
10383
10384         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10385                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10386                                          tyinfo->dobj.name,
10387                                          tyinfo->dobj.namespace->dobj.name,
10388                                          NULL,
10389                                          tyinfo->rolname, false,
10390                                          "TYPE", SECTION_PRE_DATA,
10391                                          q->data, delq->data, NULL,
10392                                          NULL, 0,
10393                                          NULL, NULL);
10394
10395         /* Dump Type Comments and Security Labels */
10396         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10397                 dumpComment(fout, "TYPE", qtypname,
10398                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10399                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10400
10401         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10402                 dumpSecLabel(fout, "TYPE", qtypname,
10403                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10404                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10405
10406         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10407                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10408                                 qtypname, NULL,
10409                                 tyinfo->dobj.namespace->dobj.name,
10410                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10411                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10412
10413         destroyPQExpBuffer(q);
10414         destroyPQExpBuffer(delq);
10415         free(qtypname);
10416         free(qualtypname);
10417 }
10418
10419 /*
10420  * dumpBaseType
10421  *        writes out to fout the queries to recreate a user-defined base type
10422  */
10423 static void
10424 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
10425 {
10426         DumpOptions *dopt = fout->dopt;
10427         PQExpBuffer q = createPQExpBuffer();
10428         PQExpBuffer delq = createPQExpBuffer();
10429         PQExpBuffer query = createPQExpBuffer();
10430         PGresult   *res;
10431         char       *qtypname;
10432         char       *qualtypname;
10433         char       *typlen;
10434         char       *typinput;
10435         char       *typoutput;
10436         char       *typreceive;
10437         char       *typsend;
10438         char       *typmodin;
10439         char       *typmodout;
10440         char       *typanalyze;
10441         Oid                     typreceiveoid;
10442         Oid                     typsendoid;
10443         Oid                     typmodinoid;
10444         Oid                     typmodoutoid;
10445         Oid                     typanalyzeoid;
10446         char       *typcategory;
10447         char       *typispreferred;
10448         char       *typdelim;
10449         char       *typbyval;
10450         char       *typalign;
10451         char       *typstorage;
10452         char       *typcollatable;
10453         char       *typdefault;
10454         bool            typdefault_is_literal = false;
10455
10456         /* Fetch type-specific details */
10457         if (fout->remoteVersion >= 90100)
10458         {
10459                 appendPQExpBuffer(query, "SELECT typlen, "
10460                                                   "typinput, typoutput, typreceive, typsend, "
10461                                                   "typmodin, typmodout, typanalyze, "
10462                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
10463                                                   "typsend::pg_catalog.oid AS typsendoid, "
10464                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
10465                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
10466                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10467                                                   "typcategory, typispreferred, "
10468                                                   "typdelim, typbyval, typalign, typstorage, "
10469                                                   "(typcollation <> 0) AS typcollatable, "
10470                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10471                                                   "FROM pg_catalog.pg_type "
10472                                                   "WHERE oid = '%u'::pg_catalog.oid",
10473                                                   tyinfo->dobj.catId.oid);
10474         }
10475         else if (fout->remoteVersion >= 80400)
10476         {
10477                 appendPQExpBuffer(query, "SELECT typlen, "
10478                                                   "typinput, typoutput, typreceive, typsend, "
10479                                                   "typmodin, typmodout, typanalyze, "
10480                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
10481                                                   "typsend::pg_catalog.oid AS typsendoid, "
10482                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
10483                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
10484                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10485                                                   "typcategory, typispreferred, "
10486                                                   "typdelim, typbyval, typalign, typstorage, "
10487                                                   "false AS typcollatable, "
10488                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10489                                                   "FROM pg_catalog.pg_type "
10490                                                   "WHERE oid = '%u'::pg_catalog.oid",
10491                                                   tyinfo->dobj.catId.oid);
10492         }
10493         else if (fout->remoteVersion >= 80300)
10494         {
10495                 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
10496                 appendPQExpBuffer(query, "SELECT typlen, "
10497                                                   "typinput, typoutput, typreceive, typsend, "
10498                                                   "typmodin, typmodout, typanalyze, "
10499                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
10500                                                   "typsend::pg_catalog.oid AS typsendoid, "
10501                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
10502                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
10503                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10504                                                   "'U' AS typcategory, false AS typispreferred, "
10505                                                   "typdelim, typbyval, typalign, typstorage, "
10506                                                   "false AS typcollatable, "
10507                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10508                                                   "FROM pg_catalog.pg_type "
10509                                                   "WHERE oid = '%u'::pg_catalog.oid",
10510                                                   tyinfo->dobj.catId.oid);
10511         }
10512         else
10513         {
10514                 appendPQExpBuffer(query, "SELECT typlen, "
10515                                                   "typinput, typoutput, typreceive, typsend, "
10516                                                   "'-' AS typmodin, '-' AS typmodout, "
10517                                                   "typanalyze, "
10518                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
10519                                                   "typsend::pg_catalog.oid AS typsendoid, "
10520                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
10521                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10522                                                   "'U' AS typcategory, false AS typispreferred, "
10523                                                   "typdelim, typbyval, typalign, typstorage, "
10524                                                   "false AS typcollatable, "
10525                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10526                                                   "FROM pg_catalog.pg_type "
10527                                                   "WHERE oid = '%u'::pg_catalog.oid",
10528                                                   tyinfo->dobj.catId.oid);
10529         }
10530
10531         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10532
10533         typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
10534         typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
10535         typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
10536         typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
10537         typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
10538         typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
10539         typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
10540         typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
10541         typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
10542         typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
10543         typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
10544         typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
10545         typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
10546         typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
10547         typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
10548         typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
10549         typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
10550         typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
10551         typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
10552         typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
10553         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10554                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10555         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10556         {
10557                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10558                 typdefault_is_literal = true;   /* it needs quotes */
10559         }
10560         else
10561                 typdefault = NULL;
10562
10563         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10564         qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10565
10566         /*
10567          * The reason we include CASCADE is that the circular dependency between
10568          * the type and its I/O functions makes it impossible to drop the type any
10569          * other way.
10570          */
10571         appendPQExpBuffer(delq, "DROP TYPE %s CASCADE;\n", qualtypname);
10572
10573         /*
10574          * We might already have a shell type, but setting pg_type_oid is
10575          * harmless, and in any case we'd better set the array type OID.
10576          */
10577         if (dopt->binary_upgrade)
10578                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10579                                                                                                  tyinfo->dobj.catId.oid,
10580                                                                                                  false);
10581
10582         appendPQExpBuffer(q,
10583                                           "CREATE TYPE %s (\n"
10584                                           "    INTERNALLENGTH = %s",
10585                                           qualtypname,
10586                                           (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
10587
10588         /* regproc result is sufficiently quoted already */
10589         appendPQExpBuffer(q, ",\n    INPUT = %s", typinput);
10590         appendPQExpBuffer(q, ",\n    OUTPUT = %s", typoutput);
10591         if (OidIsValid(typreceiveoid))
10592                 appendPQExpBuffer(q, ",\n    RECEIVE = %s", typreceive);
10593         if (OidIsValid(typsendoid))
10594                 appendPQExpBuffer(q, ",\n    SEND = %s", typsend);
10595         if (OidIsValid(typmodinoid))
10596                 appendPQExpBuffer(q, ",\n    TYPMOD_IN = %s", typmodin);
10597         if (OidIsValid(typmodoutoid))
10598                 appendPQExpBuffer(q, ",\n    TYPMOD_OUT = %s", typmodout);
10599         if (OidIsValid(typanalyzeoid))
10600                 appendPQExpBuffer(q, ",\n    ANALYZE = %s", typanalyze);
10601
10602         if (strcmp(typcollatable, "t") == 0)
10603                 appendPQExpBufferStr(q, ",\n    COLLATABLE = true");
10604
10605         if (typdefault != NULL)
10606         {
10607                 appendPQExpBufferStr(q, ",\n    DEFAULT = ");
10608                 if (typdefault_is_literal)
10609                         appendStringLiteralAH(q, typdefault, fout);
10610                 else
10611                         appendPQExpBufferStr(q, typdefault);
10612         }
10613
10614         if (OidIsValid(tyinfo->typelem))
10615         {
10616                 char       *elemType;
10617
10618                 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
10619                 appendPQExpBuffer(q, ",\n    ELEMENT = %s", elemType);
10620                 free(elemType);
10621         }
10622
10623         if (strcmp(typcategory, "U") != 0)
10624         {
10625                 appendPQExpBufferStr(q, ",\n    CATEGORY = ");
10626                 appendStringLiteralAH(q, typcategory, fout);
10627         }
10628
10629         if (strcmp(typispreferred, "t") == 0)
10630                 appendPQExpBufferStr(q, ",\n    PREFERRED = true");
10631
10632         if (typdelim && strcmp(typdelim, ",") != 0)
10633         {
10634                 appendPQExpBufferStr(q, ",\n    DELIMITER = ");
10635                 appendStringLiteralAH(q, typdelim, fout);
10636         }
10637
10638         if (strcmp(typalign, "c") == 0)
10639                 appendPQExpBufferStr(q, ",\n    ALIGNMENT = char");
10640         else if (strcmp(typalign, "s") == 0)
10641                 appendPQExpBufferStr(q, ",\n    ALIGNMENT = int2");
10642         else if (strcmp(typalign, "i") == 0)
10643                 appendPQExpBufferStr(q, ",\n    ALIGNMENT = int4");
10644         else if (strcmp(typalign, "d") == 0)
10645                 appendPQExpBufferStr(q, ",\n    ALIGNMENT = double");
10646
10647         if (strcmp(typstorage, "p") == 0)
10648                 appendPQExpBufferStr(q, ",\n    STORAGE = plain");
10649         else if (strcmp(typstorage, "e") == 0)
10650                 appendPQExpBufferStr(q, ",\n    STORAGE = external");
10651         else if (strcmp(typstorage, "x") == 0)
10652                 appendPQExpBufferStr(q, ",\n    STORAGE = extended");
10653         else if (strcmp(typstorage, "m") == 0)
10654                 appendPQExpBufferStr(q, ",\n    STORAGE = main");
10655
10656         if (strcmp(typbyval, "t") == 0)
10657                 appendPQExpBufferStr(q, ",\n    PASSEDBYVALUE");
10658
10659         appendPQExpBufferStr(q, "\n);\n");
10660
10661         if (dopt->binary_upgrade)
10662                 binary_upgrade_extension_member(q, &tyinfo->dobj,
10663                                                                                 "TYPE", qtypname,
10664                                                                                 tyinfo->dobj.namespace->dobj.name);
10665
10666         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10667                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10668                                          tyinfo->dobj.name,
10669                                          tyinfo->dobj.namespace->dobj.name,
10670                                          NULL,
10671                                          tyinfo->rolname, false,
10672                                          "TYPE", SECTION_PRE_DATA,
10673                                          q->data, delq->data, NULL,
10674                                          NULL, 0,
10675                                          NULL, NULL);
10676
10677         /* Dump Type Comments and Security Labels */
10678         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10679                 dumpComment(fout, "TYPE", qtypname,
10680                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10681                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10682
10683         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10684                 dumpSecLabel(fout, "TYPE", qtypname,
10685                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10686                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10687
10688         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10689                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10690                                 qtypname, NULL,
10691                                 tyinfo->dobj.namespace->dobj.name,
10692                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10693                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10694
10695         PQclear(res);
10696         destroyPQExpBuffer(q);
10697         destroyPQExpBuffer(delq);
10698         destroyPQExpBuffer(query);
10699         free(qtypname);
10700         free(qualtypname);
10701 }
10702
10703 /*
10704  * dumpDomain
10705  *        writes out to fout the queries to recreate a user-defined domain
10706  */
10707 static void
10708 dumpDomain(Archive *fout, TypeInfo *tyinfo)
10709 {
10710         DumpOptions *dopt = fout->dopt;
10711         PQExpBuffer q = createPQExpBuffer();
10712         PQExpBuffer delq = createPQExpBuffer();
10713         PQExpBuffer query = createPQExpBuffer();
10714         PGresult   *res;
10715         int                     i;
10716         char       *qtypname;
10717         char       *qualtypname;
10718         char       *typnotnull;
10719         char       *typdefn;
10720         char       *typdefault;
10721         Oid                     typcollation;
10722         bool            typdefault_is_literal = false;
10723
10724         /* Fetch domain specific details */
10725         if (fout->remoteVersion >= 90100)
10726         {
10727                 /* typcollation is new in 9.1 */
10728                 appendPQExpBuffer(query, "SELECT t.typnotnull, "
10729                                                   "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
10730                                                   "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10731                                                   "t.typdefault, "
10732                                                   "CASE WHEN t.typcollation <> u.typcollation "
10733                                                   "THEN t.typcollation ELSE 0 END AS typcollation "
10734                                                   "FROM pg_catalog.pg_type t "
10735                                                   "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
10736                                                   "WHERE t.oid = '%u'::pg_catalog.oid",
10737                                                   tyinfo->dobj.catId.oid);
10738         }
10739         else
10740         {
10741                 appendPQExpBuffer(query, "SELECT typnotnull, "
10742                                                   "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
10743                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10744                                                   "typdefault, 0 AS typcollation "
10745                                                   "FROM pg_catalog.pg_type "
10746                                                   "WHERE oid = '%u'::pg_catalog.oid",
10747                                                   tyinfo->dobj.catId.oid);
10748         }
10749
10750         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10751
10752         typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
10753         typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
10754         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10755                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10756         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10757         {
10758                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10759                 typdefault_is_literal = true;   /* it needs quotes */
10760         }
10761         else
10762                 typdefault = NULL;
10763         typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
10764
10765         if (dopt->binary_upgrade)
10766                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10767                                                                                                  tyinfo->dobj.catId.oid,
10768                                                                                                  true); /* force array type */
10769
10770         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10771         qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10772
10773         appendPQExpBuffer(q,
10774                                           "CREATE DOMAIN %s AS %s",
10775                                           qualtypname,
10776                                           typdefn);
10777
10778         /* Print collation only if different from base type's collation */
10779         if (OidIsValid(typcollation))
10780         {
10781                 CollInfo   *coll;
10782
10783                 coll = findCollationByOid(typcollation);
10784                 if (coll)
10785                         appendPQExpBuffer(q, " COLLATE %s", fmtQualifiedDumpable(coll));
10786         }
10787
10788         if (typnotnull[0] == 't')
10789                 appendPQExpBufferStr(q, " NOT NULL");
10790
10791         if (typdefault != NULL)
10792         {
10793                 appendPQExpBufferStr(q, " DEFAULT ");
10794                 if (typdefault_is_literal)
10795                         appendStringLiteralAH(q, typdefault, fout);
10796                 else
10797                         appendPQExpBufferStr(q, typdefault);
10798         }
10799
10800         PQclear(res);
10801
10802         /*
10803          * Add any CHECK constraints for the domain
10804          */
10805         for (i = 0; i < tyinfo->nDomChecks; i++)
10806         {
10807                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10808
10809                 if (!domcheck->separate)
10810                         appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
10811                                                           fmtId(domcheck->dobj.name), domcheck->condef);
10812         }
10813
10814         appendPQExpBufferStr(q, ";\n");
10815
10816         appendPQExpBuffer(delq, "DROP DOMAIN %s;\n", qualtypname);
10817
10818         if (dopt->binary_upgrade)
10819                 binary_upgrade_extension_member(q, &tyinfo->dobj,
10820                                                                                 "DOMAIN", qtypname,
10821                                                                                 tyinfo->dobj.namespace->dobj.name);
10822
10823         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10824                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10825                                          tyinfo->dobj.name,
10826                                          tyinfo->dobj.namespace->dobj.name,
10827                                          NULL,
10828                                          tyinfo->rolname, false,
10829                                          "DOMAIN", SECTION_PRE_DATA,
10830                                          q->data, delq->data, NULL,
10831                                          NULL, 0,
10832                                          NULL, NULL);
10833
10834         /* Dump Domain Comments and Security Labels */
10835         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10836                 dumpComment(fout, "DOMAIN", qtypname,
10837                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10838                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10839
10840         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10841                 dumpSecLabel(fout, "DOMAIN", qtypname,
10842                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10843                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10844
10845         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10846                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10847                                 qtypname, NULL,
10848                                 tyinfo->dobj.namespace->dobj.name,
10849                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10850                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10851
10852         /* Dump any per-constraint comments */
10853         for (i = 0; i < tyinfo->nDomChecks; i++)
10854         {
10855                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10856                 PQExpBuffer conprefix = createPQExpBuffer();
10857
10858                 appendPQExpBuffer(conprefix, "CONSTRAINT %s ON DOMAIN",
10859                                                   fmtId(domcheck->dobj.name));
10860
10861                 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10862                         dumpComment(fout, conprefix->data, qtypname,
10863                                                 tyinfo->dobj.namespace->dobj.name,
10864                                                 tyinfo->rolname,
10865                                                 domcheck->dobj.catId, 0, tyinfo->dobj.dumpId);
10866
10867                 destroyPQExpBuffer(conprefix);
10868         }
10869
10870         destroyPQExpBuffer(q);
10871         destroyPQExpBuffer(delq);
10872         destroyPQExpBuffer(query);
10873         free(qtypname);
10874         free(qualtypname);
10875 }
10876
10877 /*
10878  * dumpCompositeType
10879  *        writes out to fout the queries to recreate a user-defined stand-alone
10880  *        composite type
10881  */
10882 static void
10883 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
10884 {
10885         DumpOptions *dopt = fout->dopt;
10886         PQExpBuffer q = createPQExpBuffer();
10887         PQExpBuffer dropped = createPQExpBuffer();
10888         PQExpBuffer delq = createPQExpBuffer();
10889         PQExpBuffer query = createPQExpBuffer();
10890         PGresult   *res;
10891         char       *qtypname;
10892         char       *qualtypname;
10893         int                     ntups;
10894         int                     i_attname;
10895         int                     i_atttypdefn;
10896         int                     i_attlen;
10897         int                     i_attalign;
10898         int                     i_attisdropped;
10899         int                     i_attcollation;
10900         int                     i;
10901         int                     actual_atts;
10902
10903         /* Fetch type specific details */
10904         if (fout->remoteVersion >= 90100)
10905         {
10906                 /*
10907                  * attcollation is new in 9.1.  Since we only want to dump COLLATE
10908                  * clauses for attributes whose collation is different from their
10909                  * type's default, we use a CASE here to suppress uninteresting
10910                  * attcollations cheaply.  atttypid will be 0 for dropped columns;
10911                  * collation does not matter for those.
10912                  */
10913                 appendPQExpBuffer(query, "SELECT a.attname, "
10914                                                   "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10915                                                   "a.attlen, a.attalign, a.attisdropped, "
10916                                                   "CASE WHEN a.attcollation <> at.typcollation "
10917                                                   "THEN a.attcollation ELSE 0 END AS attcollation "
10918                                                   "FROM pg_catalog.pg_type ct "
10919                                                   "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
10920                                                   "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
10921                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
10922                                                   "ORDER BY a.attnum ",
10923                                                   tyinfo->dobj.catId.oid);
10924         }
10925         else
10926         {
10927                 /*
10928                  * Since ALTER TYPE could not drop columns until 9.1, attisdropped
10929                  * should always be false.
10930                  */
10931                 appendPQExpBuffer(query, "SELECT a.attname, "
10932                                                   "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10933                                                   "a.attlen, a.attalign, a.attisdropped, "
10934                                                   "0 AS attcollation "
10935                                                   "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
10936                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
10937                                                   "AND a.attrelid = ct.typrelid "
10938                                                   "ORDER BY a.attnum ",
10939                                                   tyinfo->dobj.catId.oid);
10940         }
10941
10942         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10943
10944         ntups = PQntuples(res);
10945
10946         i_attname = PQfnumber(res, "attname");
10947         i_atttypdefn = PQfnumber(res, "atttypdefn");
10948         i_attlen = PQfnumber(res, "attlen");
10949         i_attalign = PQfnumber(res, "attalign");
10950         i_attisdropped = PQfnumber(res, "attisdropped");
10951         i_attcollation = PQfnumber(res, "attcollation");
10952
10953         if (dopt->binary_upgrade)
10954         {
10955                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10956                                                                                                  tyinfo->dobj.catId.oid,
10957                                                                                                  false);
10958                 binary_upgrade_set_pg_class_oids(fout, q, tyinfo->typrelid, false);
10959         }
10960
10961         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10962         qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
10963
10964         appendPQExpBuffer(q, "CREATE TYPE %s AS (",
10965                                           qualtypname);
10966
10967         actual_atts = 0;
10968         for (i = 0; i < ntups; i++)
10969         {
10970                 char       *attname;
10971                 char       *atttypdefn;
10972                 char       *attlen;
10973                 char       *attalign;
10974                 bool            attisdropped;
10975                 Oid                     attcollation;
10976
10977                 attname = PQgetvalue(res, i, i_attname);
10978                 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
10979                 attlen = PQgetvalue(res, i, i_attlen);
10980                 attalign = PQgetvalue(res, i, i_attalign);
10981                 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
10982                 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
10983
10984                 if (attisdropped && !dopt->binary_upgrade)
10985                         continue;
10986
10987                 /* Format properly if not first attr */
10988                 if (actual_atts++ > 0)
10989                         appendPQExpBufferChar(q, ',');
10990                 appendPQExpBufferStr(q, "\n\t");
10991
10992                 if (!attisdropped)
10993                 {
10994                         appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
10995
10996                         /* Add collation if not default for the column type */
10997                         if (OidIsValid(attcollation))
10998                         {
10999                                 CollInfo   *coll;
11000
11001                                 coll = findCollationByOid(attcollation);
11002                                 if (coll)
11003                                         appendPQExpBuffer(q, " COLLATE %s",
11004                                                                           fmtQualifiedDumpable(coll));
11005                         }
11006                 }
11007                 else
11008                 {
11009                         /*
11010                          * This is a dropped attribute and we're in binary_upgrade mode.
11011                          * Insert a placeholder for it in the CREATE TYPE command, and set
11012                          * length and alignment with direct UPDATE to the catalogs
11013                          * afterwards. See similar code in dumpTableSchema().
11014                          */
11015                         appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
11016
11017                         /* stash separately for insertion after the CREATE TYPE */
11018                         appendPQExpBufferStr(dropped,
11019                                                                  "\n-- For binary upgrade, recreate dropped column.\n");
11020                         appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
11021                                                           "SET attlen = %s, "
11022                                                           "attalign = '%s', attbyval = false\n"
11023                                                           "WHERE attname = ", attlen, attalign);
11024                         appendStringLiteralAH(dropped, attname, fout);
11025                         appendPQExpBufferStr(dropped, "\n  AND attrelid = ");
11026                         appendStringLiteralAH(dropped, qualtypname, fout);
11027                         appendPQExpBufferStr(dropped, "::pg_catalog.regclass;\n");
11028
11029                         appendPQExpBuffer(dropped, "ALTER TYPE %s ",
11030                                                           qualtypname);
11031                         appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
11032                                                           fmtId(attname));
11033                 }
11034         }
11035         appendPQExpBufferStr(q, "\n);\n");
11036         appendPQExpBufferStr(q, dropped->data);
11037
11038         appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
11039
11040         if (dopt->binary_upgrade)
11041                 binary_upgrade_extension_member(q, &tyinfo->dobj,
11042                                                                                 "TYPE", qtypname,
11043                                                                                 tyinfo->dobj.namespace->dobj.name);
11044
11045         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11046                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11047                                          tyinfo->dobj.name,
11048                                          tyinfo->dobj.namespace->dobj.name,
11049                                          NULL,
11050                                          tyinfo->rolname, false,
11051                                          "TYPE", SECTION_PRE_DATA,
11052                                          q->data, delq->data, NULL,
11053                                          NULL, 0,
11054                                          NULL, NULL);
11055
11056
11057         /* Dump Type Comments and Security Labels */
11058         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11059                 dumpComment(fout, "TYPE", qtypname,
11060                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11061                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11062
11063         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11064                 dumpSecLabel(fout, "TYPE", qtypname,
11065                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11066                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11067
11068         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11069                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
11070                                 qtypname, NULL,
11071                                 tyinfo->dobj.namespace->dobj.name,
11072                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
11073                                 tyinfo->inittypacl, tyinfo->initrtypacl);
11074
11075         PQclear(res);
11076         destroyPQExpBuffer(q);
11077         destroyPQExpBuffer(dropped);
11078         destroyPQExpBuffer(delq);
11079         destroyPQExpBuffer(query);
11080         free(qtypname);
11081         free(qualtypname);
11082
11083         /* Dump any per-column comments */
11084         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11085                 dumpCompositeTypeColComments(fout, tyinfo);
11086 }
11087
11088 /*
11089  * dumpCompositeTypeColComments
11090  *        writes out to fout the queries to recreate comments on the columns of
11091  *        a user-defined stand-alone composite type
11092  */
11093 static void
11094 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
11095 {
11096         CommentItem *comments;
11097         int                     ncomments;
11098         PGresult   *res;
11099         PQExpBuffer query;
11100         PQExpBuffer target;
11101         Oid                     pgClassOid;
11102         int                     i;
11103         int                     ntups;
11104         int                     i_attname;
11105         int                     i_attnum;
11106
11107         /* do nothing, if --no-comments is supplied */
11108         if (fout->dopt->no_comments)
11109                 return;
11110
11111         query = createPQExpBuffer();
11112
11113         appendPQExpBuffer(query,
11114                                           "SELECT c.tableoid, a.attname, a.attnum "
11115                                           "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
11116                                           "WHERE c.oid = '%u' AND c.oid = a.attrelid "
11117                                           "  AND NOT a.attisdropped "
11118                                           "ORDER BY a.attnum ",
11119                                           tyinfo->typrelid);
11120
11121         /* Fetch column attnames */
11122         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11123
11124         ntups = PQntuples(res);
11125         if (ntups < 1)
11126         {
11127                 PQclear(res);
11128                 destroyPQExpBuffer(query);
11129                 return;
11130         }
11131
11132         pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
11133
11134         /* Search for comments associated with type's pg_class OID */
11135         ncomments = findComments(fout,
11136                                                          pgClassOid,
11137                                                          tyinfo->typrelid,
11138                                                          &comments);
11139
11140         /* If no comments exist, we're done */
11141         if (ncomments <= 0)
11142         {
11143                 PQclear(res);
11144                 destroyPQExpBuffer(query);
11145                 return;
11146         }
11147
11148         /* Build COMMENT ON statements */
11149         target = createPQExpBuffer();
11150
11151         i_attnum = PQfnumber(res, "attnum");
11152         i_attname = PQfnumber(res, "attname");
11153         while (ncomments > 0)
11154         {
11155                 const char *attname;
11156
11157                 attname = NULL;
11158                 for (i = 0; i < ntups; i++)
11159                 {
11160                         if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
11161                         {
11162                                 attname = PQgetvalue(res, i, i_attname);
11163                                 break;
11164                         }
11165                 }
11166                 if (attname)                    /* just in case we don't find it */
11167                 {
11168                         const char *descr = comments->descr;
11169
11170                         resetPQExpBuffer(target);
11171                         appendPQExpBuffer(target, "COLUMN %s.",
11172                                                           fmtId(tyinfo->dobj.name));
11173                         appendPQExpBufferStr(target, fmtId(attname));
11174
11175                         resetPQExpBuffer(query);
11176                         appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
11177                                                           fmtQualifiedDumpable(tyinfo));
11178                         appendPQExpBuffer(query, "%s IS ", fmtId(attname));
11179                         appendStringLiteralAH(query, descr, fout);
11180                         appendPQExpBufferStr(query, ";\n");
11181
11182                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
11183                                                  target->data,
11184                                                  tyinfo->dobj.namespace->dobj.name,
11185                                                  NULL, tyinfo->rolname,
11186                                                  false, "COMMENT", SECTION_NONE,
11187                                                  query->data, "", NULL,
11188                                                  &(tyinfo->dobj.dumpId), 1,
11189                                                  NULL, NULL);
11190                 }
11191
11192                 comments++;
11193                 ncomments--;
11194         }
11195
11196         PQclear(res);
11197         destroyPQExpBuffer(query);
11198         destroyPQExpBuffer(target);
11199 }
11200
11201 /*
11202  * dumpShellType
11203  *        writes out to fout the queries to create a shell type
11204  *
11205  * We dump a shell definition in advance of the I/O functions for the type.
11206  */
11207 static void
11208 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
11209 {
11210         DumpOptions *dopt = fout->dopt;
11211         PQExpBuffer q;
11212
11213         /* Skip if not to be dumped */
11214         if (!stinfo->dobj.dump || dopt->dataOnly)
11215                 return;
11216
11217         q = createPQExpBuffer();
11218
11219         /*
11220          * Note the lack of a DROP command for the shell type; any required DROP
11221          * is driven off the base type entry, instead.  This interacts with
11222          * _printTocEntry()'s use of the presence of a DROP command to decide
11223          * whether an entry needs an ALTER OWNER command.  We don't want to alter
11224          * the shell type's owner immediately on creation; that should happen only
11225          * after it's filled in, otherwise the backend complains.
11226          */
11227
11228         if (dopt->binary_upgrade)
11229                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
11230                                                                                                  stinfo->baseType->dobj.catId.oid,
11231                                                                                                  false);
11232
11233         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
11234                                           fmtQualifiedDumpable(stinfo));
11235
11236         if (stinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11237                 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
11238                                          stinfo->dobj.name,
11239                                          stinfo->dobj.namespace->dobj.name,
11240                                          NULL,
11241                                          stinfo->baseType->rolname, false,
11242                                          "SHELL TYPE", SECTION_PRE_DATA,
11243                                          q->data, "", NULL,
11244                                          NULL, 0,
11245                                          NULL, NULL);
11246
11247         destroyPQExpBuffer(q);
11248 }
11249
11250 /*
11251  * dumpProcLang
11252  *                writes out to fout the queries to recreate a user-defined
11253  *                procedural language
11254  */
11255 static void
11256 dumpProcLang(Archive *fout, ProcLangInfo *plang)
11257 {
11258         DumpOptions *dopt = fout->dopt;
11259         PQExpBuffer defqry;
11260         PQExpBuffer delqry;
11261         bool            useParams;
11262         char       *qlanname;
11263         FuncInfo   *funcInfo;
11264         FuncInfo   *inlineInfo = NULL;
11265         FuncInfo   *validatorInfo = NULL;
11266
11267         /* Skip if not to be dumped */
11268         if (!plang->dobj.dump || dopt->dataOnly)
11269                 return;
11270
11271         /*
11272          * Try to find the support function(s).  It is not an error if we don't
11273          * find them --- if the functions are in the pg_catalog schema, as is
11274          * standard in 8.1 and up, then we won't have loaded them. (In this case
11275          * we will emit a parameterless CREATE LANGUAGE command, which will
11276          * require PL template knowledge in the backend to reload.)
11277          */
11278
11279         funcInfo = findFuncByOid(plang->lanplcallfoid);
11280         if (funcInfo != NULL && !funcInfo->dobj.dump)
11281                 funcInfo = NULL;                /* treat not-dumped same as not-found */
11282
11283         if (OidIsValid(plang->laninline))
11284         {
11285                 inlineInfo = findFuncByOid(plang->laninline);
11286                 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
11287                         inlineInfo = NULL;
11288         }
11289
11290         if (OidIsValid(plang->lanvalidator))
11291         {
11292                 validatorInfo = findFuncByOid(plang->lanvalidator);
11293                 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
11294                         validatorInfo = NULL;
11295         }
11296
11297         /*
11298          * If the functions are dumpable then emit a traditional CREATE LANGUAGE
11299          * with parameters.  Otherwise, we'll write a parameterless command, which
11300          * will rely on data from pg_pltemplate.
11301          */
11302         useParams = (funcInfo != NULL &&
11303                                  (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
11304                                  (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
11305
11306         defqry = createPQExpBuffer();
11307         delqry = createPQExpBuffer();
11308
11309         qlanname = pg_strdup(fmtId(plang->dobj.name));
11310
11311         appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
11312                                           qlanname);
11313
11314         if (useParams)
11315         {
11316                 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
11317                                                   plang->lanpltrusted ? "TRUSTED " : "",
11318                                                   qlanname);
11319                 appendPQExpBuffer(defqry, " HANDLER %s",
11320                                                   fmtQualifiedDumpable(funcInfo));
11321                 if (OidIsValid(plang->laninline))
11322                         appendPQExpBuffer(defqry, " INLINE %s",
11323                                                           fmtQualifiedDumpable(inlineInfo));
11324                 if (OidIsValid(plang->lanvalidator))
11325                         appendPQExpBuffer(defqry, " VALIDATOR %s",
11326                                                           fmtQualifiedDumpable(validatorInfo));
11327         }
11328         else
11329         {
11330                 /*
11331                  * If not dumping parameters, then use CREATE OR REPLACE so that the
11332                  * command will not fail if the language is preinstalled in the target
11333                  * database.  We restrict the use of REPLACE to this case so as to
11334                  * eliminate the risk of replacing a language with incompatible
11335                  * parameter settings: this command will only succeed at all if there
11336                  * is a pg_pltemplate entry, and if there is one, the existing entry
11337                  * must match it too.
11338                  */
11339                 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
11340                                                   qlanname);
11341         }
11342         appendPQExpBufferStr(defqry, ";\n");
11343
11344         if (dopt->binary_upgrade)
11345                 binary_upgrade_extension_member(defqry, &plang->dobj,
11346                                                                                 "LANGUAGE", qlanname, NULL);
11347
11348         if (plang->dobj.dump & DUMP_COMPONENT_DEFINITION)
11349                 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
11350                                          plang->dobj.name,
11351                                          NULL, NULL, plang->lanowner,
11352                                          false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
11353                                          defqry->data, delqry->data, NULL,
11354                                          NULL, 0,
11355                                          NULL, NULL);
11356
11357         /* Dump Proc Lang Comments and Security Labels */
11358         if (plang->dobj.dump & DUMP_COMPONENT_COMMENT)
11359                 dumpComment(fout, "LANGUAGE", qlanname,
11360                                         NULL, plang->lanowner,
11361                                         plang->dobj.catId, 0, plang->dobj.dumpId);
11362
11363         if (plang->dobj.dump & DUMP_COMPONENT_SECLABEL)
11364                 dumpSecLabel(fout, "LANGUAGE", qlanname,
11365                                          NULL, plang->lanowner,
11366                                          plang->dobj.catId, 0, plang->dobj.dumpId);
11367
11368         if (plang->lanpltrusted && plang->dobj.dump & DUMP_COMPONENT_ACL)
11369                 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
11370                                 qlanname, NULL, NULL,
11371                                 plang->lanowner, plang->lanacl, plang->rlanacl,
11372                                 plang->initlanacl, plang->initrlanacl);
11373
11374         free(qlanname);
11375
11376         destroyPQExpBuffer(defqry);
11377         destroyPQExpBuffer(delqry);
11378 }
11379
11380 /*
11381  * format_function_arguments: generate function name and argument list
11382  *
11383  * This is used when we can rely on pg_get_function_arguments to format
11384  * the argument list.  Note, however, that pg_get_function_arguments
11385  * does not special-case zero-argument aggregates.
11386  */
11387 static char *
11388 format_function_arguments(FuncInfo *finfo, char *funcargs, bool is_agg)
11389 {
11390         PQExpBufferData fn;
11391
11392         initPQExpBuffer(&fn);
11393         appendPQExpBufferStr(&fn, fmtId(finfo->dobj.name));
11394         if (is_agg && finfo->nargs == 0)
11395                 appendPQExpBufferStr(&fn, "(*)");
11396         else
11397                 appendPQExpBuffer(&fn, "(%s)", funcargs);
11398         return fn.data;
11399 }
11400
11401 /*
11402  * format_function_arguments_old: generate function name and argument list
11403  *
11404  * The argument type names are qualified if needed.  The function name
11405  * is never qualified.
11406  *
11407  * This is used only with pre-8.4 servers, so we aren't expecting to see
11408  * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
11409  *
11410  * Any or all of allargtypes, argmodes, argnames may be NULL.
11411  */
11412 static char *
11413 format_function_arguments_old(Archive *fout,
11414                                                           FuncInfo *finfo, int nallargs,
11415                                                           char **allargtypes,
11416                                                           char **argmodes,
11417                                                           char **argnames)
11418 {
11419         PQExpBufferData fn;
11420         int                     j;
11421
11422         initPQExpBuffer(&fn);
11423         appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11424         for (j = 0; j < nallargs; j++)
11425         {
11426                 Oid                     typid;
11427                 char       *typname;
11428                 const char *argmode;
11429                 const char *argname;
11430
11431                 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
11432                 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
11433
11434                 if (argmodes)
11435                 {
11436                         switch (argmodes[j][0])
11437                         {
11438                                 case PROARGMODE_IN:
11439                                         argmode = "";
11440                                         break;
11441                                 case PROARGMODE_OUT:
11442                                         argmode = "OUT ";
11443                                         break;
11444                                 case PROARGMODE_INOUT:
11445                                         argmode = "INOUT ";
11446                                         break;
11447                                 default:
11448                                         write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
11449                                         argmode = "";
11450                                         break;
11451                         }
11452                 }
11453                 else
11454                         argmode = "";
11455
11456                 argname = argnames ? argnames[j] : (char *) NULL;
11457                 if (argname && argname[0] == '\0')
11458                         argname = NULL;
11459
11460                 appendPQExpBuffer(&fn, "%s%s%s%s%s",
11461                                                   (j > 0) ? ", " : "",
11462                                                   argmode,
11463                                                   argname ? fmtId(argname) : "",
11464                                                   argname ? " " : "",
11465                                                   typname);
11466                 free(typname);
11467         }
11468         appendPQExpBufferChar(&fn, ')');
11469         return fn.data;
11470 }
11471
11472 /*
11473  * format_function_signature: generate function name and argument list
11474  *
11475  * This is like format_function_arguments_old except that only a minimal
11476  * list of input argument types is generated; this is sufficient to
11477  * reference the function, but not to define it.
11478  *
11479  * If honor_quotes is false then the function name is never quoted.
11480  * This is appropriate for use in TOC tags, but not in SQL commands.
11481  */
11482 static char *
11483 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
11484 {
11485         PQExpBufferData fn;
11486         int                     j;
11487
11488         initPQExpBuffer(&fn);
11489         if (honor_quotes)
11490                 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11491         else
11492                 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
11493         for (j = 0; j < finfo->nargs; j++)
11494         {
11495                 char       *typname;
11496
11497                 if (j > 0)
11498                         appendPQExpBufferStr(&fn, ", ");
11499
11500                 typname = getFormattedTypeName(fout, finfo->argtypes[j],
11501                                                                            zeroAsOpaque);
11502                 appendPQExpBufferStr(&fn, typname);
11503                 free(typname);
11504         }
11505         appendPQExpBufferChar(&fn, ')');
11506         return fn.data;
11507 }
11508
11509
11510 /*
11511  * dumpFunc:
11512  *        dump out one function
11513  */
11514 static void
11515 dumpFunc(Archive *fout, FuncInfo *finfo)
11516 {
11517         DumpOptions *dopt = fout->dopt;
11518         PQExpBuffer query;
11519         PQExpBuffer q;
11520         PQExpBuffer delqry;
11521         PQExpBuffer asPart;
11522         PGresult   *res;
11523         char       *funcsig;            /* identity signature */
11524         char       *funcfullsig = NULL; /* full signature */
11525         char       *funcsig_tag;
11526         char       *proretset;
11527         char       *prosrc;
11528         char       *probin;
11529         char       *funcargs;
11530         char       *funciargs;
11531         char       *funcresult;
11532         char       *proallargtypes;
11533         char       *proargmodes;
11534         char       *proargnames;
11535         char       *protrftypes;
11536         char       *prokind;
11537         char       *provolatile;
11538         char       *proisstrict;
11539         char       *prosecdef;
11540         char       *proleakproof;
11541         char       *proconfig;
11542         char       *procost;
11543         char       *prorows;
11544         char       *proparallel;
11545         char       *lanname;
11546         char       *rettypename;
11547         int                     nallargs;
11548         char      **allargtypes = NULL;
11549         char      **argmodes = NULL;
11550         char      **argnames = NULL;
11551         char      **configitems = NULL;
11552         int                     nconfigitems = 0;
11553         const char *keyword;
11554         int                     i;
11555
11556         /* Skip if not to be dumped */
11557         if (!finfo->dobj.dump || dopt->dataOnly)
11558                 return;
11559
11560         query = createPQExpBuffer();
11561         q = createPQExpBuffer();
11562         delqry = createPQExpBuffer();
11563         asPart = createPQExpBuffer();
11564
11565         /* Fetch function-specific details */
11566         if (fout->remoteVersion >= 110000)
11567         {
11568                 /*
11569                  * prokind was added in 11
11570                  */
11571                 appendPQExpBuffer(query,
11572                                                   "SELECT proretset, prosrc, probin, "
11573                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11574                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11575                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11576                                                   "array_to_string(protrftypes, ' ') AS protrftypes, "
11577                                                   "prokind, provolatile, proisstrict, prosecdef, "
11578                                                   "proleakproof, proconfig, procost, prorows, "
11579                                                   "proparallel, "
11580                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11581                                                   "FROM pg_catalog.pg_proc "
11582                                                   "WHERE oid = '%u'::pg_catalog.oid",
11583                                                   finfo->dobj.catId.oid);
11584         }
11585         else if (fout->remoteVersion >= 90600)
11586         {
11587                 /*
11588                  * proparallel was added in 9.6
11589                  */
11590                 appendPQExpBuffer(query,
11591                                                   "SELECT proretset, prosrc, probin, "
11592                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11593                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11594                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11595                                                   "array_to_string(protrftypes, ' ') AS protrftypes, "
11596                                                   "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11597                                                   "provolatile, proisstrict, prosecdef, "
11598                                                   "proleakproof, proconfig, procost, prorows, "
11599                                                   "proparallel, "
11600                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11601                                                   "FROM pg_catalog.pg_proc "
11602                                                   "WHERE oid = '%u'::pg_catalog.oid",
11603                                                   finfo->dobj.catId.oid);
11604         }
11605         else if (fout->remoteVersion >= 90500)
11606         {
11607                 /*
11608                  * protrftypes was added in 9.5
11609                  */
11610                 appendPQExpBuffer(query,
11611                                                   "SELECT proretset, prosrc, probin, "
11612                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11613                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11614                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11615                                                   "array_to_string(protrftypes, ' ') AS protrftypes, "
11616                                                   "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11617                                                   "provolatile, proisstrict, prosecdef, "
11618                                                   "proleakproof, proconfig, procost, prorows, "
11619                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11620                                                   "FROM pg_catalog.pg_proc "
11621                                                   "WHERE oid = '%u'::pg_catalog.oid",
11622                                                   finfo->dobj.catId.oid);
11623         }
11624         else if (fout->remoteVersion >= 90200)
11625         {
11626                 /*
11627                  * proleakproof was added in 9.2
11628                  */
11629                 appendPQExpBuffer(query,
11630                                                   "SELECT proretset, prosrc, probin, "
11631                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11632                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11633                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11634                                                   "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11635                                                   "provolatile, proisstrict, prosecdef, "
11636                                                   "proleakproof, proconfig, procost, prorows, "
11637                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11638                                                   "FROM pg_catalog.pg_proc "
11639                                                   "WHERE oid = '%u'::pg_catalog.oid",
11640                                                   finfo->dobj.catId.oid);
11641         }
11642         else if (fout->remoteVersion >= 80400)
11643         {
11644                 /*
11645                  * In 8.4 and up we rely on pg_get_function_arguments and
11646                  * pg_get_function_result instead of examining proallargtypes etc.
11647                  */
11648                 appendPQExpBuffer(query,
11649                                                   "SELECT proretset, prosrc, probin, "
11650                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11651                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11652                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11653                                                   "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
11654                                                   "provolatile, proisstrict, prosecdef, "
11655                                                   "false AS proleakproof, "
11656                                                   " proconfig, procost, prorows, "
11657                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11658                                                   "FROM pg_catalog.pg_proc "
11659                                                   "WHERE oid = '%u'::pg_catalog.oid",
11660                                                   finfo->dobj.catId.oid);
11661         }
11662         else if (fout->remoteVersion >= 80300)
11663         {
11664                 appendPQExpBuffer(query,
11665                                                   "SELECT proretset, prosrc, probin, "
11666                                                   "proallargtypes, proargmodes, proargnames, "
11667                                                   "'f' AS prokind, "
11668                                                   "provolatile, proisstrict, prosecdef, "
11669                                                   "false AS proleakproof, "
11670                                                   "proconfig, procost, prorows, "
11671                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11672                                                   "FROM pg_catalog.pg_proc "
11673                                                   "WHERE oid = '%u'::pg_catalog.oid",
11674                                                   finfo->dobj.catId.oid);
11675         }
11676         else if (fout->remoteVersion >= 80100)
11677         {
11678                 appendPQExpBuffer(query,
11679                                                   "SELECT proretset, prosrc, probin, "
11680                                                   "proallargtypes, proargmodes, proargnames, "
11681                                                   "'f' AS prokind, "
11682                                                   "provolatile, proisstrict, prosecdef, "
11683                                                   "false AS proleakproof, "
11684                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
11685                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11686                                                   "FROM pg_catalog.pg_proc "
11687                                                   "WHERE oid = '%u'::pg_catalog.oid",
11688                                                   finfo->dobj.catId.oid);
11689         }
11690         else
11691         {
11692                 appendPQExpBuffer(query,
11693                                                   "SELECT proretset, prosrc, probin, "
11694                                                   "null AS proallargtypes, "
11695                                                   "null AS proargmodes, "
11696                                                   "proargnames, "
11697                                                   "'f' AS prokind, "
11698                                                   "provolatile, proisstrict, prosecdef, "
11699                                                   "false AS proleakproof, "
11700                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
11701                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11702                                                   "FROM pg_catalog.pg_proc "
11703                                                   "WHERE oid = '%u'::pg_catalog.oid",
11704                                                   finfo->dobj.catId.oid);
11705         }
11706
11707         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11708
11709         proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
11710         prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
11711         probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
11712         if (fout->remoteVersion >= 80400)
11713         {
11714                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
11715                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
11716                 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
11717                 proallargtypes = proargmodes = proargnames = NULL;
11718         }
11719         else
11720         {
11721                 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
11722                 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
11723                 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
11724                 funcargs = funciargs = funcresult = NULL;
11725         }
11726         if (PQfnumber(res, "protrftypes") != -1)
11727                 protrftypes = PQgetvalue(res, 0, PQfnumber(res, "protrftypes"));
11728         else
11729                 protrftypes = NULL;
11730         prokind = PQgetvalue(res, 0, PQfnumber(res, "prokind"));
11731         provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
11732         proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
11733         prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
11734         proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
11735         proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
11736         procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
11737         prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
11738
11739         if (PQfnumber(res, "proparallel") != -1)
11740                 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
11741         else
11742                 proparallel = NULL;
11743
11744         lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
11745
11746         /*
11747          * See backend/commands/functioncmds.c for details of how the 'AS' clause
11748          * is used.  In 8.4 and up, an unused probin is NULL (here ""); previous
11749          * versions would set it to "-".  There are no known cases in which prosrc
11750          * is unused, so the tests below for "-" are probably useless.
11751          */
11752         if (probin[0] != '\0' && strcmp(probin, "-") != 0)
11753         {
11754                 appendPQExpBufferStr(asPart, "AS ");
11755                 appendStringLiteralAH(asPart, probin, fout);
11756                 if (strcmp(prosrc, "-") != 0)
11757                 {
11758                         appendPQExpBufferStr(asPart, ", ");
11759
11760                         /*
11761                          * where we have bin, use dollar quoting if allowed and src
11762                          * contains quote or backslash; else use regular quoting.
11763                          */
11764                         if (dopt->disable_dollar_quoting ||
11765                                 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
11766                                 appendStringLiteralAH(asPart, prosrc, fout);
11767                         else
11768                                 appendStringLiteralDQ(asPart, prosrc, NULL);
11769                 }
11770         }
11771         else
11772         {
11773                 if (strcmp(prosrc, "-") != 0)
11774                 {
11775                         appendPQExpBufferStr(asPart, "AS ");
11776                         /* with no bin, dollar quote src unconditionally if allowed */
11777                         if (dopt->disable_dollar_quoting)
11778                                 appendStringLiteralAH(asPart, prosrc, fout);
11779                         else
11780                                 appendStringLiteralDQ(asPart, prosrc, NULL);
11781                 }
11782         }
11783
11784         nallargs = finfo->nargs;        /* unless we learn different from allargs */
11785
11786         if (proallargtypes && *proallargtypes)
11787         {
11788                 int                     nitems = 0;
11789
11790                 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
11791                         nitems < finfo->nargs)
11792                 {
11793                         write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
11794                         if (allargtypes)
11795                                 free(allargtypes);
11796                         allargtypes = NULL;
11797                 }
11798                 else
11799                         nallargs = nitems;
11800         }
11801
11802         if (proargmodes && *proargmodes)
11803         {
11804                 int                     nitems = 0;
11805
11806                 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
11807                         nitems != nallargs)
11808                 {
11809                         write_msg(NULL, "WARNING: could not parse proargmodes array\n");
11810                         if (argmodes)
11811                                 free(argmodes);
11812                         argmodes = NULL;
11813                 }
11814         }
11815
11816         if (proargnames && *proargnames)
11817         {
11818                 int                     nitems = 0;
11819
11820                 if (!parsePGArray(proargnames, &argnames, &nitems) ||
11821                         nitems != nallargs)
11822                 {
11823                         write_msg(NULL, "WARNING: could not parse proargnames array\n");
11824                         if (argnames)
11825                                 free(argnames);
11826                         argnames = NULL;
11827                 }
11828         }
11829
11830         if (proconfig && *proconfig)
11831         {
11832                 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
11833                 {
11834                         write_msg(NULL, "WARNING: could not parse proconfig array\n");
11835                         if (configitems)
11836                                 free(configitems);
11837                         configitems = NULL;
11838                         nconfigitems = 0;
11839                 }
11840         }
11841
11842         if (funcargs)
11843         {
11844                 /* 8.4 or later; we rely on server-side code for most of the work */
11845                 funcfullsig = format_function_arguments(finfo, funcargs, false);
11846                 funcsig = format_function_arguments(finfo, funciargs, false);
11847         }
11848         else
11849                 /* pre-8.4, do it ourselves */
11850                 funcsig = format_function_arguments_old(fout,
11851                                                                                                 finfo, nallargs, allargtypes,
11852                                                                                                 argmodes, argnames);
11853
11854         funcsig_tag = format_function_signature(fout, finfo, false);
11855
11856         if (prokind[0] == PROKIND_PROCEDURE)
11857                 keyword = "PROCEDURE";
11858         else
11859                 keyword = "FUNCTION";   /* works for window functions too */
11860
11861         appendPQExpBuffer(delqry, "DROP %s %s.%s;\n",
11862                                           keyword,
11863                                           fmtId(finfo->dobj.namespace->dobj.name),
11864                                           funcsig);
11865
11866         appendPQExpBuffer(q, "CREATE %s %s.%s",
11867                                           keyword,
11868                                           fmtId(finfo->dobj.namespace->dobj.name),
11869                                           funcfullsig ? funcfullsig :
11870                                           funcsig);
11871
11872         if (prokind[0] == PROKIND_PROCEDURE)
11873                  /* no result type to output */ ;
11874         else if (funcresult)
11875                 appendPQExpBuffer(q, " RETURNS %s", funcresult);
11876         else
11877         {
11878                 rettypename = getFormattedTypeName(fout, finfo->prorettype,
11879                                                                                    zeroAsOpaque);
11880                 appendPQExpBuffer(q, " RETURNS %s%s",
11881                                                   (proretset[0] == 't') ? "SETOF " : "",
11882                                                   rettypename);
11883                 free(rettypename);
11884         }
11885
11886         appendPQExpBuffer(q, "\n    LANGUAGE %s", fmtId(lanname));
11887
11888         if (protrftypes != NULL && strcmp(protrftypes, "") != 0)
11889         {
11890                 Oid                *typeids = palloc(FUNC_MAX_ARGS * sizeof(Oid));
11891                 int                     i;
11892
11893                 appendPQExpBufferStr(q, " TRANSFORM ");
11894                 parseOidArray(protrftypes, typeids, FUNC_MAX_ARGS);
11895                 for (i = 0; typeids[i]; i++)
11896                 {
11897                         if (i != 0)
11898                                 appendPQExpBufferStr(q, ", ");
11899                         appendPQExpBuffer(q, "FOR TYPE %s",
11900                                                           getFormattedTypeName(fout, typeids[i], zeroAsNone));
11901                 }
11902         }
11903
11904         if (prokind[0] == PROKIND_WINDOW)
11905                 appendPQExpBufferStr(q, " WINDOW");
11906
11907         if (provolatile[0] != PROVOLATILE_VOLATILE)
11908         {
11909                 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
11910                         appendPQExpBufferStr(q, " IMMUTABLE");
11911                 else if (provolatile[0] == PROVOLATILE_STABLE)
11912                         appendPQExpBufferStr(q, " STABLE");
11913                 else if (provolatile[0] != PROVOLATILE_VOLATILE)
11914                         exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
11915                                                   finfo->dobj.name);
11916         }
11917
11918         if (proisstrict[0] == 't')
11919                 appendPQExpBufferStr(q, " STRICT");
11920
11921         if (prosecdef[0] == 't')
11922                 appendPQExpBufferStr(q, " SECURITY DEFINER");
11923
11924         if (proleakproof[0] == 't')
11925                 appendPQExpBufferStr(q, " LEAKPROOF");
11926
11927         /*
11928          * COST and ROWS are emitted only if present and not default, so as not to
11929          * break backwards-compatibility of the dump without need.  Keep this code
11930          * in sync with the defaults in functioncmds.c.
11931          */
11932         if (strcmp(procost, "0") != 0)
11933         {
11934                 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
11935                 {
11936                         /* default cost is 1 */
11937                         if (strcmp(procost, "1") != 0)
11938                                 appendPQExpBuffer(q, " COST %s", procost);
11939                 }
11940                 else
11941                 {
11942                         /* default cost is 100 */
11943                         if (strcmp(procost, "100") != 0)
11944                                 appendPQExpBuffer(q, " COST %s", procost);
11945                 }
11946         }
11947         if (proretset[0] == 't' &&
11948                 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
11949                 appendPQExpBuffer(q, " ROWS %s", prorows);
11950
11951         if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
11952         {
11953                 if (proparallel[0] == PROPARALLEL_SAFE)
11954                         appendPQExpBufferStr(q, " PARALLEL SAFE");
11955                 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
11956                         appendPQExpBufferStr(q, " PARALLEL RESTRICTED");
11957                 else if (proparallel[0] != PROPARALLEL_UNSAFE)
11958                         exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
11959                                                   finfo->dobj.name);
11960         }
11961
11962         for (i = 0; i < nconfigitems; i++)
11963         {
11964                 /* we feel free to scribble on configitems[] here */
11965                 char       *configitem = configitems[i];
11966                 char       *pos;
11967
11968                 pos = strchr(configitem, '=');
11969                 if (pos == NULL)
11970                         continue;
11971                 *pos++ = '\0';
11972                 appendPQExpBuffer(q, "\n    SET %s TO ", fmtId(configitem));
11973
11974                 /*
11975                  * Variables that are marked GUC_LIST_QUOTE were already fully quoted
11976                  * by flatten_set_variable_args() before they were put into the
11977                  * proconfig array.  However, because the quoting rules used there
11978                  * aren't exactly like SQL's, we have to break the list value apart
11979                  * and then quote the elements as string literals.  (The elements may
11980                  * be double-quoted as-is, but we can't just feed them to the SQL
11981                  * parser; it would do the wrong thing with elements that are
11982                  * zero-length or longer than NAMEDATALEN.)
11983                  *
11984                  * Variables that are not so marked should just be emitted as simple
11985                  * string literals.  If the variable is not known to
11986                  * variable_is_guc_list_quote(), we'll do that; this makes it unsafe
11987                  * to use GUC_LIST_QUOTE for extension variables.
11988                  */
11989                 if (variable_is_guc_list_quote(configitem))
11990                 {
11991                         char      **namelist;
11992                         char      **nameptr;
11993
11994                         /* Parse string into list of identifiers */
11995                         /* this shouldn't fail really */
11996                         if (SplitGUCList(pos, ',', &namelist))
11997                         {
11998                                 for (nameptr = namelist; *nameptr; nameptr++)
11999                                 {
12000                                         if (nameptr != namelist)
12001                                                 appendPQExpBufferStr(q, ", ");
12002                                         appendStringLiteralAH(q, *nameptr, fout);
12003                                 }
12004                         }
12005                         pg_free(namelist);
12006                 }
12007                 else
12008                         appendStringLiteralAH(q, pos, fout);
12009         }
12010
12011         appendPQExpBuffer(q, "\n    %s;\n", asPart->data);
12012
12013         if (dopt->binary_upgrade)
12014                 binary_upgrade_extension_member(q, &finfo->dobj,
12015                                                                                 keyword, funcsig,
12016                                                                                 finfo->dobj.namespace->dobj.name);
12017
12018         if (finfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12019                 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
12020                                          funcsig_tag,
12021                                          finfo->dobj.namespace->dobj.name,
12022                                          NULL,
12023                                          finfo->rolname, false,
12024                                          keyword, SECTION_PRE_DATA,
12025                                          q->data, delqry->data, NULL,
12026                                          NULL, 0,
12027                                          NULL, NULL);
12028
12029         /* Dump Function Comments and Security Labels */
12030         if (finfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12031                 dumpComment(fout, keyword, funcsig,
12032                                         finfo->dobj.namespace->dobj.name, finfo->rolname,
12033                                         finfo->dobj.catId, 0, finfo->dobj.dumpId);
12034
12035         if (finfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
12036                 dumpSecLabel(fout, keyword, funcsig,
12037                                          finfo->dobj.namespace->dobj.name, finfo->rolname,
12038                                          finfo->dobj.catId, 0, finfo->dobj.dumpId);
12039
12040         if (finfo->dobj.dump & DUMP_COMPONENT_ACL)
12041                 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, keyword,
12042                                 funcsig, NULL,
12043                                 finfo->dobj.namespace->dobj.name,
12044                                 finfo->rolname, finfo->proacl, finfo->rproacl,
12045                                 finfo->initproacl, finfo->initrproacl);
12046
12047         PQclear(res);
12048
12049         destroyPQExpBuffer(query);
12050         destroyPQExpBuffer(q);
12051         destroyPQExpBuffer(delqry);
12052         destroyPQExpBuffer(asPart);
12053         free(funcsig);
12054         if (funcfullsig)
12055                 free(funcfullsig);
12056         free(funcsig_tag);
12057         if (allargtypes)
12058                 free(allargtypes);
12059         if (argmodes)
12060                 free(argmodes);
12061         if (argnames)
12062                 free(argnames);
12063         if (configitems)
12064                 free(configitems);
12065 }
12066
12067
12068 /*
12069  * Dump a user-defined cast
12070  */
12071 static void
12072 dumpCast(Archive *fout, CastInfo *cast)
12073 {
12074         DumpOptions *dopt = fout->dopt;
12075         PQExpBuffer defqry;
12076         PQExpBuffer delqry;
12077         PQExpBuffer labelq;
12078         PQExpBuffer castargs;
12079         FuncInfo   *funcInfo = NULL;
12080         char       *sourceType;
12081         char       *targetType;
12082
12083         /* Skip if not to be dumped */
12084         if (!cast->dobj.dump || dopt->dataOnly)
12085                 return;
12086
12087         /* Cannot dump if we don't have the cast function's info */
12088         if (OidIsValid(cast->castfunc))
12089         {
12090                 funcInfo = findFuncByOid(cast->castfunc);
12091                 if (funcInfo == NULL)
12092                         exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12093                                                   cast->castfunc);
12094         }
12095
12096         defqry = createPQExpBuffer();
12097         delqry = createPQExpBuffer();
12098         labelq = createPQExpBuffer();
12099         castargs = createPQExpBuffer();
12100
12101         sourceType = getFormattedTypeName(fout, cast->castsource, zeroAsNone);
12102         targetType = getFormattedTypeName(fout, cast->casttarget, zeroAsNone);
12103         appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
12104                                           sourceType, targetType);
12105
12106         appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
12107                                           sourceType, targetType);
12108
12109         switch (cast->castmethod)
12110         {
12111                 case COERCION_METHOD_BINARY:
12112                         appendPQExpBufferStr(defqry, "WITHOUT FUNCTION");
12113                         break;
12114                 case COERCION_METHOD_INOUT:
12115                         appendPQExpBufferStr(defqry, "WITH INOUT");
12116                         break;
12117                 case COERCION_METHOD_FUNCTION:
12118                         if (funcInfo)
12119                         {
12120                                 char       *fsig = format_function_signature(fout, funcInfo, true);
12121
12122                                 /*
12123                                  * Always qualify the function name (format_function_signature
12124                                  * won't qualify it).
12125                                  */
12126                                 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
12127                                                                   fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
12128                                 free(fsig);
12129                         }
12130                         else
12131                                 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
12132                         break;
12133                 default:
12134                         write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
12135         }
12136
12137         if (cast->castcontext == 'a')
12138                 appendPQExpBufferStr(defqry, " AS ASSIGNMENT");
12139         else if (cast->castcontext == 'i')
12140                 appendPQExpBufferStr(defqry, " AS IMPLICIT");
12141         appendPQExpBufferStr(defqry, ";\n");
12142
12143         appendPQExpBuffer(labelq, "CAST (%s AS %s)",
12144                                           sourceType, targetType);
12145
12146         appendPQExpBuffer(castargs, "(%s AS %s)",
12147                                           sourceType, targetType);
12148
12149         if (dopt->binary_upgrade)
12150                 binary_upgrade_extension_member(defqry, &cast->dobj,
12151                                                                                 "CAST", castargs->data, NULL);
12152
12153         if (cast->dobj.dump & DUMP_COMPONENT_DEFINITION)
12154                 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
12155                                          labelq->data,
12156                                          NULL, NULL, "",
12157                                          false, "CAST", SECTION_PRE_DATA,
12158                                          defqry->data, delqry->data, NULL,
12159                                          NULL, 0,
12160                                          NULL, NULL);
12161
12162         /* Dump Cast Comments */
12163         if (cast->dobj.dump & DUMP_COMPONENT_COMMENT)
12164                 dumpComment(fout, "CAST", castargs->data,
12165                                         NULL, "",
12166                                         cast->dobj.catId, 0, cast->dobj.dumpId);
12167
12168         free(sourceType);
12169         free(targetType);
12170
12171         destroyPQExpBuffer(defqry);
12172         destroyPQExpBuffer(delqry);
12173         destroyPQExpBuffer(labelq);
12174         destroyPQExpBuffer(castargs);
12175 }
12176
12177 /*
12178  * Dump a transform
12179  */
12180 static void
12181 dumpTransform(Archive *fout, TransformInfo *transform)
12182 {
12183         DumpOptions *dopt = fout->dopt;
12184         PQExpBuffer defqry;
12185         PQExpBuffer delqry;
12186         PQExpBuffer labelq;
12187         PQExpBuffer transformargs;
12188         FuncInfo   *fromsqlFuncInfo = NULL;
12189         FuncInfo   *tosqlFuncInfo = NULL;
12190         char       *lanname;
12191         char       *transformType;
12192
12193         /* Skip if not to be dumped */
12194         if (!transform->dobj.dump || dopt->dataOnly)
12195                 return;
12196
12197         /* Cannot dump if we don't have the transform functions' info */
12198         if (OidIsValid(transform->trffromsql))
12199         {
12200                 fromsqlFuncInfo = findFuncByOid(transform->trffromsql);
12201                 if (fromsqlFuncInfo == NULL)
12202                         exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12203                                                   transform->trffromsql);
12204         }
12205         if (OidIsValid(transform->trftosql))
12206         {
12207                 tosqlFuncInfo = findFuncByOid(transform->trftosql);
12208                 if (tosqlFuncInfo == NULL)
12209                         exit_horribly(NULL, "could not find function definition for function with OID %u\n",
12210                                                   transform->trftosql);
12211         }
12212
12213         defqry = createPQExpBuffer();
12214         delqry = createPQExpBuffer();
12215         labelq = createPQExpBuffer();
12216         transformargs = createPQExpBuffer();
12217
12218         lanname = get_language_name(fout, transform->trflang);
12219         transformType = getFormattedTypeName(fout, transform->trftype, zeroAsNone);
12220
12221         appendPQExpBuffer(delqry, "DROP TRANSFORM FOR %s LANGUAGE %s;\n",
12222                                           transformType, lanname);
12223
12224         appendPQExpBuffer(defqry, "CREATE TRANSFORM FOR %s LANGUAGE %s (",
12225                                           transformType, lanname);
12226
12227         if (!transform->trffromsql && !transform->trftosql)
12228                 write_msg(NULL, "WARNING: bogus transform definition, at least one of trffromsql and trftosql should be nonzero\n");
12229
12230         if (transform->trffromsql)
12231         {
12232                 if (fromsqlFuncInfo)
12233                 {
12234                         char       *fsig = format_function_signature(fout, fromsqlFuncInfo, true);
12235
12236                         /*
12237                          * Always qualify the function name (format_function_signature
12238                          * won't qualify it).
12239                          */
12240                         appendPQExpBuffer(defqry, "FROM SQL WITH FUNCTION %s.%s",
12241                                                           fmtId(fromsqlFuncInfo->dobj.namespace->dobj.name), fsig);
12242                         free(fsig);
12243                 }
12244                 else
12245                         write_msg(NULL, "WARNING: bogus value in pg_transform.trffromsql field\n");
12246         }
12247
12248         if (transform->trftosql)
12249         {
12250                 if (transform->trffromsql)
12251                         appendPQExpBuffer(defqry, ", ");
12252
12253                 if (tosqlFuncInfo)
12254                 {
12255                         char       *fsig = format_function_signature(fout, tosqlFuncInfo, true);
12256
12257                         /*
12258                          * Always qualify the function name (format_function_signature
12259                          * won't qualify it).
12260                          */
12261                         appendPQExpBuffer(defqry, "TO SQL WITH FUNCTION %s.%s",
12262                                                           fmtId(tosqlFuncInfo->dobj.namespace->dobj.name), fsig);
12263                         free(fsig);
12264                 }
12265                 else
12266                         write_msg(NULL, "WARNING: bogus value in pg_transform.trftosql field\n");
12267         }
12268
12269         appendPQExpBuffer(defqry, ");\n");
12270
12271         appendPQExpBuffer(labelq, "TRANSFORM FOR %s LANGUAGE %s",
12272                                           transformType, lanname);
12273
12274         appendPQExpBuffer(transformargs, "FOR %s LANGUAGE %s",
12275                                           transformType, lanname);
12276
12277         if (dopt->binary_upgrade)
12278                 binary_upgrade_extension_member(defqry, &transform->dobj,
12279                                                                                 "TRANSFORM", transformargs->data, NULL);
12280
12281         if (transform->dobj.dump & DUMP_COMPONENT_DEFINITION)
12282                 ArchiveEntry(fout, transform->dobj.catId, transform->dobj.dumpId,
12283                                          labelq->data,
12284                                          NULL, NULL, "",
12285                                          false, "TRANSFORM", SECTION_PRE_DATA,
12286                                          defqry->data, delqry->data, NULL,
12287                                          transform->dobj.dependencies, transform->dobj.nDeps,
12288                                          NULL, NULL);
12289
12290         /* Dump Transform Comments */
12291         if (transform->dobj.dump & DUMP_COMPONENT_COMMENT)
12292                 dumpComment(fout, "TRANSFORM", transformargs->data,
12293                                         NULL, "",
12294                                         transform->dobj.catId, 0, transform->dobj.dumpId);
12295
12296         free(lanname);
12297         free(transformType);
12298         destroyPQExpBuffer(defqry);
12299         destroyPQExpBuffer(delqry);
12300         destroyPQExpBuffer(labelq);
12301         destroyPQExpBuffer(transformargs);
12302 }
12303
12304
12305 /*
12306  * dumpOpr
12307  *        write out a single operator definition
12308  */
12309 static void
12310 dumpOpr(Archive *fout, OprInfo *oprinfo)
12311 {
12312         DumpOptions *dopt = fout->dopt;
12313         PQExpBuffer query;
12314         PQExpBuffer q;
12315         PQExpBuffer delq;
12316         PQExpBuffer oprid;
12317         PQExpBuffer details;
12318         PGresult   *res;
12319         int                     i_oprkind;
12320         int                     i_oprcode;
12321         int                     i_oprleft;
12322         int                     i_oprright;
12323         int                     i_oprcom;
12324         int                     i_oprnegate;
12325         int                     i_oprrest;
12326         int                     i_oprjoin;
12327         int                     i_oprcanmerge;
12328         int                     i_oprcanhash;
12329         char       *oprkind;
12330         char       *oprcode;
12331         char       *oprleft;
12332         char       *oprright;
12333         char       *oprcom;
12334         char       *oprnegate;
12335         char       *oprrest;
12336         char       *oprjoin;
12337         char       *oprcanmerge;
12338         char       *oprcanhash;
12339         char       *oprregproc;
12340         char       *oprref;
12341
12342         /* Skip if not to be dumped */
12343         if (!oprinfo->dobj.dump || dopt->dataOnly)
12344                 return;
12345
12346         /*
12347          * some operators are invalid because they were the result of user
12348          * defining operators before commutators exist
12349          */
12350         if (!OidIsValid(oprinfo->oprcode))
12351                 return;
12352
12353         query = createPQExpBuffer();
12354         q = createPQExpBuffer();
12355         delq = createPQExpBuffer();
12356         oprid = createPQExpBuffer();
12357         details = createPQExpBuffer();
12358
12359         if (fout->remoteVersion >= 80300)
12360         {
12361                 appendPQExpBuffer(query, "SELECT oprkind, "
12362                                                   "oprcode::pg_catalog.regprocedure, "
12363                                                   "oprleft::pg_catalog.regtype, "
12364                                                   "oprright::pg_catalog.regtype, "
12365                                                   "oprcom, "
12366                                                   "oprnegate, "
12367                                                   "oprrest::pg_catalog.regprocedure, "
12368                                                   "oprjoin::pg_catalog.regprocedure, "
12369                                                   "oprcanmerge, oprcanhash "
12370                                                   "FROM pg_catalog.pg_operator "
12371                                                   "WHERE oid = '%u'::pg_catalog.oid",
12372                                                   oprinfo->dobj.catId.oid);
12373         }
12374         else
12375         {
12376                 appendPQExpBuffer(query, "SELECT oprkind, "
12377                                                   "oprcode::pg_catalog.regprocedure, "
12378                                                   "oprleft::pg_catalog.regtype, "
12379                                                   "oprright::pg_catalog.regtype, "
12380                                                   "oprcom, "
12381                                                   "oprnegate, "
12382                                                   "oprrest::pg_catalog.regprocedure, "
12383                                                   "oprjoin::pg_catalog.regprocedure, "
12384                                                   "(oprlsortop != 0) AS oprcanmerge, "
12385                                                   "oprcanhash "
12386                                                   "FROM pg_catalog.pg_operator "
12387                                                   "WHERE oid = '%u'::pg_catalog.oid",
12388                                                   oprinfo->dobj.catId.oid);
12389         }
12390
12391         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12392
12393         i_oprkind = PQfnumber(res, "oprkind");
12394         i_oprcode = PQfnumber(res, "oprcode");
12395         i_oprleft = PQfnumber(res, "oprleft");
12396         i_oprright = PQfnumber(res, "oprright");
12397         i_oprcom = PQfnumber(res, "oprcom");
12398         i_oprnegate = PQfnumber(res, "oprnegate");
12399         i_oprrest = PQfnumber(res, "oprrest");
12400         i_oprjoin = PQfnumber(res, "oprjoin");
12401         i_oprcanmerge = PQfnumber(res, "oprcanmerge");
12402         i_oprcanhash = PQfnumber(res, "oprcanhash");
12403
12404         oprkind = PQgetvalue(res, 0, i_oprkind);
12405         oprcode = PQgetvalue(res, 0, i_oprcode);
12406         oprleft = PQgetvalue(res, 0, i_oprleft);
12407         oprright = PQgetvalue(res, 0, i_oprright);
12408         oprcom = PQgetvalue(res, 0, i_oprcom);
12409         oprnegate = PQgetvalue(res, 0, i_oprnegate);
12410         oprrest = PQgetvalue(res, 0, i_oprrest);
12411         oprjoin = PQgetvalue(res, 0, i_oprjoin);
12412         oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
12413         oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
12414
12415         oprregproc = convertRegProcReference(fout, oprcode);
12416         if (oprregproc)
12417         {
12418                 appendPQExpBuffer(details, "    FUNCTION = %s", oprregproc);
12419                 free(oprregproc);
12420         }
12421
12422         appendPQExpBuffer(oprid, "%s (",
12423                                           oprinfo->dobj.name);
12424
12425         /*
12426          * right unary means there's a left arg and left unary means there's a
12427          * right arg
12428          */
12429         if (strcmp(oprkind, "r") == 0 ||
12430                 strcmp(oprkind, "b") == 0)
12431         {
12432                 appendPQExpBuffer(details, ",\n    LEFTARG = %s", oprleft);
12433                 appendPQExpBufferStr(oprid, oprleft);
12434         }
12435         else
12436                 appendPQExpBufferStr(oprid, "NONE");
12437
12438         if (strcmp(oprkind, "l") == 0 ||
12439                 strcmp(oprkind, "b") == 0)
12440         {
12441                 appendPQExpBuffer(details, ",\n    RIGHTARG = %s", oprright);
12442                 appendPQExpBuffer(oprid, ", %s)", oprright);
12443         }
12444         else
12445                 appendPQExpBufferStr(oprid, ", NONE)");
12446
12447         oprref = getFormattedOperatorName(fout, oprcom);
12448         if (oprref)
12449         {
12450                 appendPQExpBuffer(details, ",\n    COMMUTATOR = %s", oprref);
12451                 free(oprref);
12452         }
12453
12454         oprref = getFormattedOperatorName(fout, oprnegate);
12455         if (oprref)
12456         {
12457                 appendPQExpBuffer(details, ",\n    NEGATOR = %s", oprref);
12458                 free(oprref);
12459         }
12460
12461         if (strcmp(oprcanmerge, "t") == 0)
12462                 appendPQExpBufferStr(details, ",\n    MERGES");
12463
12464         if (strcmp(oprcanhash, "t") == 0)
12465                 appendPQExpBufferStr(details, ",\n    HASHES");
12466
12467         oprregproc = convertRegProcReference(fout, oprrest);
12468         if (oprregproc)
12469         {
12470                 appendPQExpBuffer(details, ",\n    RESTRICT = %s", oprregproc);
12471                 free(oprregproc);
12472         }
12473
12474         oprregproc = convertRegProcReference(fout, oprjoin);
12475         if (oprregproc)
12476         {
12477                 appendPQExpBuffer(details, ",\n    JOIN = %s", oprregproc);
12478                 free(oprregproc);
12479         }
12480
12481         appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
12482                                           fmtId(oprinfo->dobj.namespace->dobj.name),
12483                                           oprid->data);
12484
12485         appendPQExpBuffer(q, "CREATE OPERATOR %s.%s (\n%s\n);\n",
12486                                           fmtId(oprinfo->dobj.namespace->dobj.name),
12487                                           oprinfo->dobj.name, details->data);
12488
12489         if (dopt->binary_upgrade)
12490                 binary_upgrade_extension_member(q, &oprinfo->dobj,
12491                                                                                 "OPERATOR", oprid->data,
12492                                                                                 oprinfo->dobj.namespace->dobj.name);
12493
12494         if (oprinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12495                 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
12496                                          oprinfo->dobj.name,
12497                                          oprinfo->dobj.namespace->dobj.name,
12498                                          NULL,
12499                                          oprinfo->rolname,
12500                                          false, "OPERATOR", SECTION_PRE_DATA,
12501                                          q->data, delq->data, NULL,
12502                                          NULL, 0,
12503                                          NULL, NULL);
12504
12505         /* Dump Operator Comments */
12506         if (oprinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12507                 dumpComment(fout, "OPERATOR", oprid->data,
12508                                         oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
12509                                         oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
12510
12511         PQclear(res);
12512
12513         destroyPQExpBuffer(query);
12514         destroyPQExpBuffer(q);
12515         destroyPQExpBuffer(delq);
12516         destroyPQExpBuffer(oprid);
12517         destroyPQExpBuffer(details);
12518 }
12519
12520 /*
12521  * Convert a function reference obtained from pg_operator
12522  *
12523  * Returns allocated string of what to print, or NULL if function references
12524  * is InvalidOid. Returned string is expected to be free'd by the caller.
12525  *
12526  * The input is a REGPROCEDURE display; we have to strip the argument-types
12527  * part.
12528  */
12529 static char *
12530 convertRegProcReference(Archive *fout, const char *proc)
12531 {
12532         char       *name;
12533         char       *paren;
12534         bool            inquote;
12535
12536         /* In all cases "-" means a null reference */
12537         if (strcmp(proc, "-") == 0)
12538                 return NULL;
12539
12540         name = pg_strdup(proc);
12541         /* find non-double-quoted left paren */
12542         inquote = false;
12543         for (paren = name; *paren; paren++)
12544         {
12545                 if (*paren == '(' && !inquote)
12546                 {
12547                         *paren = '\0';
12548                         break;
12549                 }
12550                 if (*paren == '"')
12551                         inquote = !inquote;
12552         }
12553         return name;
12554 }
12555
12556 /*
12557  * getFormattedOperatorName - retrieve the operator name for the
12558  * given operator OID (presented in string form).
12559  *
12560  * Returns an allocated string, or NULL if the given OID is invalid.
12561  * Caller is responsible for free'ing result string.
12562  *
12563  * What we produce has the format "OPERATOR(schema.oprname)".  This is only
12564  * useful in commands where the operator's argument types can be inferred from
12565  * context.  We always schema-qualify the name, though.  The predecessor to
12566  * this code tried to skip the schema qualification if possible, but that led
12567  * to wrong results in corner cases, such as if an operator and its negator
12568  * are in different schemas.
12569  */
12570 static char *
12571 getFormattedOperatorName(Archive *fout, const char *oproid)
12572 {
12573         OprInfo    *oprInfo;
12574
12575         /* In all cases "0" means a null reference */
12576         if (strcmp(oproid, "0") == 0)
12577                 return NULL;
12578
12579         oprInfo = findOprByOid(atooid(oproid));
12580         if (oprInfo == NULL)
12581         {
12582                 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
12583                                   oproid);
12584                 return NULL;
12585         }
12586
12587         return psprintf("OPERATOR(%s.%s)",
12588                                         fmtId(oprInfo->dobj.namespace->dobj.name),
12589                                         oprInfo->dobj.name);
12590 }
12591
12592 /*
12593  * Convert a function OID obtained from pg_ts_parser or pg_ts_template
12594  *
12595  * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
12596  * argument lists of these functions are predetermined.  Note that the
12597  * caller should ensure we are in the proper schema, because the results
12598  * are search path dependent!
12599  */
12600 static char *
12601 convertTSFunction(Archive *fout, Oid funcOid)
12602 {
12603         char       *result;
12604         char            query[128];
12605         PGresult   *res;
12606
12607         snprintf(query, sizeof(query),
12608                          "SELECT '%u'::pg_catalog.regproc", funcOid);
12609         res = ExecuteSqlQueryForSingleRow(fout, query);
12610
12611         result = pg_strdup(PQgetvalue(res, 0, 0));
12612
12613         PQclear(res);
12614
12615         return result;
12616 }
12617
12618 /*
12619  * dumpAccessMethod
12620  *        write out a single access method definition
12621  */
12622 static void
12623 dumpAccessMethod(Archive *fout, AccessMethodInfo *aminfo)
12624 {
12625         DumpOptions *dopt = fout->dopt;
12626         PQExpBuffer q;
12627         PQExpBuffer delq;
12628         char       *qamname;
12629
12630         /* Skip if not to be dumped */
12631         if (!aminfo->dobj.dump || dopt->dataOnly)
12632                 return;
12633
12634         q = createPQExpBuffer();
12635         delq = createPQExpBuffer();
12636
12637         qamname = pg_strdup(fmtId(aminfo->dobj.name));
12638
12639         appendPQExpBuffer(q, "CREATE ACCESS METHOD %s ", qamname);
12640
12641         switch (aminfo->amtype)
12642         {
12643                 case AMTYPE_INDEX:
12644                         appendPQExpBuffer(q, "TYPE INDEX ");
12645                         break;
12646                 default:
12647                         write_msg(NULL, "WARNING: invalid type \"%c\" of access method \"%s\"\n",
12648                                           aminfo->amtype, qamname);
12649                         destroyPQExpBuffer(q);
12650                         destroyPQExpBuffer(delq);
12651                         free(qamname);
12652                         return;
12653         }
12654
12655         appendPQExpBuffer(q, "HANDLER %s;\n", aminfo->amhandler);
12656
12657         appendPQExpBuffer(delq, "DROP ACCESS METHOD %s;\n",
12658                                           qamname);
12659
12660         if (dopt->binary_upgrade)
12661                 binary_upgrade_extension_member(q, &aminfo->dobj,
12662                                                                                 "ACCESS METHOD", qamname, NULL);
12663
12664         if (aminfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12665                 ArchiveEntry(fout, aminfo->dobj.catId, aminfo->dobj.dumpId,
12666                                          aminfo->dobj.name,
12667                                          NULL,
12668                                          NULL,
12669                                          "",
12670                                          false, "ACCESS METHOD", SECTION_PRE_DATA,
12671                                          q->data, delq->data, NULL,
12672                                          NULL, 0,
12673                                          NULL, NULL);
12674
12675         /* Dump Access Method Comments */
12676         if (aminfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12677                 dumpComment(fout, "ACCESS METHOD", qamname,
12678                                         NULL, "",
12679                                         aminfo->dobj.catId, 0, aminfo->dobj.dumpId);
12680
12681         destroyPQExpBuffer(q);
12682         destroyPQExpBuffer(delq);
12683         free(qamname);
12684 }
12685
12686 /*
12687  * dumpOpclass
12688  *        write out a single operator class definition
12689  */
12690 static void
12691 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
12692 {
12693         DumpOptions *dopt = fout->dopt;
12694         PQExpBuffer query;
12695         PQExpBuffer q;
12696         PQExpBuffer delq;
12697         PQExpBuffer nameusing;
12698         PGresult   *res;
12699         int                     ntups;
12700         int                     i_opcintype;
12701         int                     i_opckeytype;
12702         int                     i_opcdefault;
12703         int                     i_opcfamily;
12704         int                     i_opcfamilyname;
12705         int                     i_opcfamilynsp;
12706         int                     i_amname;
12707         int                     i_amopstrategy;
12708         int                     i_amopreqcheck;
12709         int                     i_amopopr;
12710         int                     i_sortfamily;
12711         int                     i_sortfamilynsp;
12712         int                     i_amprocnum;
12713         int                     i_amproc;
12714         int                     i_amproclefttype;
12715         int                     i_amprocrighttype;
12716         char       *opcintype;
12717         char       *opckeytype;
12718         char       *opcdefault;
12719         char       *opcfamily;
12720         char       *opcfamilyname;
12721         char       *opcfamilynsp;
12722         char       *amname;
12723         char       *amopstrategy;
12724         char       *amopreqcheck;
12725         char       *amopopr;
12726         char       *sortfamily;
12727         char       *sortfamilynsp;
12728         char       *amprocnum;
12729         char       *amproc;
12730         char       *amproclefttype;
12731         char       *amprocrighttype;
12732         bool            needComma;
12733         int                     i;
12734
12735         /* Skip if not to be dumped */
12736         if (!opcinfo->dobj.dump || dopt->dataOnly)
12737                 return;
12738
12739         query = createPQExpBuffer();
12740         q = createPQExpBuffer();
12741         delq = createPQExpBuffer();
12742         nameusing = createPQExpBuffer();
12743
12744         /* Get additional fields from the pg_opclass row */
12745         if (fout->remoteVersion >= 80300)
12746         {
12747                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12748                                                   "opckeytype::pg_catalog.regtype, "
12749                                                   "opcdefault, opcfamily, "
12750                                                   "opfname AS opcfamilyname, "
12751                                                   "nspname AS opcfamilynsp, "
12752                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
12753                                                   "FROM pg_catalog.pg_opclass c "
12754                                                   "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
12755                                                   "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12756                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
12757                                                   opcinfo->dobj.catId.oid);
12758         }
12759         else
12760         {
12761                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12762                                                   "opckeytype::pg_catalog.regtype, "
12763                                                   "opcdefault, NULL AS opcfamily, "
12764                                                   "NULL AS opcfamilyname, "
12765                                                   "NULL AS opcfamilynsp, "
12766                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
12767                                                   "FROM pg_catalog.pg_opclass "
12768                                                   "WHERE oid = '%u'::pg_catalog.oid",
12769                                                   opcinfo->dobj.catId.oid);
12770         }
12771
12772         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12773
12774         i_opcintype = PQfnumber(res, "opcintype");
12775         i_opckeytype = PQfnumber(res, "opckeytype");
12776         i_opcdefault = PQfnumber(res, "opcdefault");
12777         i_opcfamily = PQfnumber(res, "opcfamily");
12778         i_opcfamilyname = PQfnumber(res, "opcfamilyname");
12779         i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
12780         i_amname = PQfnumber(res, "amname");
12781
12782         /* opcintype may still be needed after we PQclear res */
12783         opcintype = pg_strdup(PQgetvalue(res, 0, i_opcintype));
12784         opckeytype = PQgetvalue(res, 0, i_opckeytype);
12785         opcdefault = PQgetvalue(res, 0, i_opcdefault);
12786         /* opcfamily will still be needed after we PQclear res */
12787         opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
12788         opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
12789         opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
12790         /* amname will still be needed after we PQclear res */
12791         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
12792
12793         appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
12794                                           fmtQualifiedDumpable(opcinfo));
12795         appendPQExpBuffer(delq, " USING %s;\n",
12796                                           fmtId(amname));
12797
12798         /* Build the fixed portion of the CREATE command */
12799         appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n    ",
12800                                           fmtQualifiedDumpable(opcinfo));
12801         if (strcmp(opcdefault, "t") == 0)
12802                 appendPQExpBufferStr(q, "DEFAULT ");
12803         appendPQExpBuffer(q, "FOR TYPE %s USING %s",
12804                                           opcintype,
12805                                           fmtId(amname));
12806         if (strlen(opcfamilyname) > 0)
12807         {
12808                 appendPQExpBufferStr(q, " FAMILY ");
12809                 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
12810                 appendPQExpBufferStr(q, fmtId(opcfamilyname));
12811         }
12812         appendPQExpBufferStr(q, " AS\n    ");
12813
12814         needComma = false;
12815
12816         if (strcmp(opckeytype, "-") != 0)
12817         {
12818                 appendPQExpBuffer(q, "STORAGE %s",
12819                                                   opckeytype);
12820                 needComma = true;
12821         }
12822
12823         PQclear(res);
12824
12825         /*
12826          * Now fetch and print the OPERATOR entries (pg_amop rows).
12827          *
12828          * Print only those opfamily members that are tied to the opclass by
12829          * pg_depend entries.
12830          *
12831          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
12832          * older server's opclass in which it is used.  This is to avoid
12833          * hard-to-detect breakage if a newer pg_dump is used to dump from an
12834          * older server and then reload into that old version.  This can go away
12835          * once 8.3 is so old as to not be of interest to anyone.
12836          */
12837         resetPQExpBuffer(query);
12838
12839         if (fout->remoteVersion >= 90100)
12840         {
12841                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12842                                                   "amopopr::pg_catalog.regoperator, "
12843                                                   "opfname AS sortfamily, "
12844                                                   "nspname AS sortfamilynsp "
12845                                                   "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
12846                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
12847                                                   "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
12848                                                   "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12849                                                   "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12850                                                   "AND refobjid = '%u'::pg_catalog.oid "
12851                                                   "AND amopfamily = '%s'::pg_catalog.oid "
12852                                                   "ORDER BY amopstrategy",
12853                                                   opcinfo->dobj.catId.oid,
12854                                                   opcfamily);
12855         }
12856         else if (fout->remoteVersion >= 80400)
12857         {
12858                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12859                                                   "amopopr::pg_catalog.regoperator, "
12860                                                   "NULL AS sortfamily, "
12861                                                   "NULL AS sortfamilynsp "
12862                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12863                                                   "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12864                                                   "AND refobjid = '%u'::pg_catalog.oid "
12865                                                   "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12866                                                   "AND objid = ao.oid "
12867                                                   "ORDER BY amopstrategy",
12868                                                   opcinfo->dobj.catId.oid);
12869         }
12870         else if (fout->remoteVersion >= 80300)
12871         {
12872                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12873                                                   "amopopr::pg_catalog.regoperator, "
12874                                                   "NULL AS sortfamily, "
12875                                                   "NULL AS sortfamilynsp "
12876                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12877                                                   "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12878                                                   "AND refobjid = '%u'::pg_catalog.oid "
12879                                                   "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12880                                                   "AND objid = ao.oid "
12881                                                   "ORDER BY amopstrategy",
12882                                                   opcinfo->dobj.catId.oid);
12883         }
12884         else
12885         {
12886                 /*
12887                  * Here, we print all entries since there are no opfamilies and hence
12888                  * no loose operators to worry about.
12889                  */
12890                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12891                                                   "amopopr::pg_catalog.regoperator, "
12892                                                   "NULL AS sortfamily, "
12893                                                   "NULL AS sortfamilynsp "
12894                                                   "FROM pg_catalog.pg_amop "
12895                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
12896                                                   "ORDER BY amopstrategy",
12897                                                   opcinfo->dobj.catId.oid);
12898         }
12899
12900         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12901
12902         ntups = PQntuples(res);
12903
12904         i_amopstrategy = PQfnumber(res, "amopstrategy");
12905         i_amopreqcheck = PQfnumber(res, "amopreqcheck");
12906         i_amopopr = PQfnumber(res, "amopopr");
12907         i_sortfamily = PQfnumber(res, "sortfamily");
12908         i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
12909
12910         for (i = 0; i < ntups; i++)
12911         {
12912                 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
12913                 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
12914                 amopopr = PQgetvalue(res, i, i_amopopr);
12915                 sortfamily = PQgetvalue(res, i, i_sortfamily);
12916                 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
12917
12918                 if (needComma)
12919                         appendPQExpBufferStr(q, " ,\n    ");
12920
12921                 appendPQExpBuffer(q, "OPERATOR %s %s",
12922                                                   amopstrategy, amopopr);
12923
12924                 if (strlen(sortfamily) > 0)
12925                 {
12926                         appendPQExpBufferStr(q, " FOR ORDER BY ");
12927                         appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
12928                         appendPQExpBufferStr(q, fmtId(sortfamily));
12929                 }
12930
12931                 if (strcmp(amopreqcheck, "t") == 0)
12932                         appendPQExpBufferStr(q, " RECHECK");
12933
12934                 needComma = true;
12935         }
12936
12937         PQclear(res);
12938
12939         /*
12940          * Now fetch and print the FUNCTION entries (pg_amproc rows).
12941          *
12942          * Print only those opfamily members that are tied to the opclass by
12943          * pg_depend entries.
12944          *
12945          * We print the amproclefttype/amprocrighttype even though in most cases
12946          * the backend could deduce the right values, because of the corner case
12947          * of a btree sort support function for a cross-type comparison.  That's
12948          * only allowed in 9.2 and later, but for simplicity print them in all
12949          * versions that have the columns.
12950          */
12951         resetPQExpBuffer(query);
12952
12953         if (fout->remoteVersion >= 80300)
12954         {
12955                 appendPQExpBuffer(query, "SELECT amprocnum, "
12956                                                   "amproc::pg_catalog.regprocedure, "
12957                                                   "amproclefttype::pg_catalog.regtype, "
12958                                                   "amprocrighttype::pg_catalog.regtype "
12959                                                   "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
12960                                                   "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12961                                                   "AND refobjid = '%u'::pg_catalog.oid "
12962                                                   "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
12963                                                   "AND objid = ap.oid "
12964                                                   "ORDER BY amprocnum",
12965                                                   opcinfo->dobj.catId.oid);
12966         }
12967         else
12968         {
12969                 appendPQExpBuffer(query, "SELECT amprocnum, "
12970                                                   "amproc::pg_catalog.regprocedure, "
12971                                                   "'' AS amproclefttype, "
12972                                                   "'' AS amprocrighttype "
12973                                                   "FROM pg_catalog.pg_amproc "
12974                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
12975                                                   "ORDER BY amprocnum",
12976                                                   opcinfo->dobj.catId.oid);
12977         }
12978
12979         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12980
12981         ntups = PQntuples(res);
12982
12983         i_amprocnum = PQfnumber(res, "amprocnum");
12984         i_amproc = PQfnumber(res, "amproc");
12985         i_amproclefttype = PQfnumber(res, "amproclefttype");
12986         i_amprocrighttype = PQfnumber(res, "amprocrighttype");
12987
12988         for (i = 0; i < ntups; i++)
12989         {
12990                 amprocnum = PQgetvalue(res, i, i_amprocnum);
12991                 amproc = PQgetvalue(res, i, i_amproc);
12992                 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
12993                 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
12994
12995                 if (needComma)
12996                         appendPQExpBufferStr(q, " ,\n    ");
12997
12998                 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
12999
13000                 if (*amproclefttype && *amprocrighttype)
13001                         appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
13002
13003                 appendPQExpBuffer(q, " %s", amproc);
13004
13005                 needComma = true;
13006         }
13007
13008         PQclear(res);
13009
13010         /*
13011          * If needComma is still false it means we haven't added anything after
13012          * the AS keyword.  To avoid printing broken SQL, append a dummy STORAGE
13013          * clause with the same datatype.  This isn't sanctioned by the
13014          * documentation, but actually DefineOpClass will treat it as a no-op.
13015          */
13016         if (!needComma)
13017                 appendPQExpBuffer(q, "STORAGE %s", opcintype);
13018
13019         appendPQExpBufferStr(q, ";\n");
13020
13021         appendPQExpBufferStr(nameusing, fmtId(opcinfo->dobj.name));
13022         appendPQExpBuffer(nameusing, " USING %s",
13023                                           fmtId(amname));
13024
13025         if (dopt->binary_upgrade)
13026                 binary_upgrade_extension_member(q, &opcinfo->dobj,
13027                                                                                 "OPERATOR CLASS", nameusing->data,
13028                                                                                 opcinfo->dobj.namespace->dobj.name);
13029
13030         if (opcinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13031                 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
13032                                          opcinfo->dobj.name,
13033                                          opcinfo->dobj.namespace->dobj.name,
13034                                          NULL,
13035                                          opcinfo->rolname,
13036                                          false, "OPERATOR CLASS", SECTION_PRE_DATA,
13037                                          q->data, delq->data, NULL,
13038                                          NULL, 0,
13039                                          NULL, NULL);
13040
13041         /* Dump Operator Class Comments */
13042         if (opcinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13043                 dumpComment(fout, "OPERATOR CLASS", nameusing->data,
13044                                         opcinfo->dobj.namespace->dobj.name, opcinfo->rolname,
13045                                         opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
13046
13047         free(opcintype);
13048         free(opcfamily);
13049         free(amname);
13050         destroyPQExpBuffer(query);
13051         destroyPQExpBuffer(q);
13052         destroyPQExpBuffer(delq);
13053         destroyPQExpBuffer(nameusing);
13054 }
13055
13056 /*
13057  * dumpOpfamily
13058  *        write out a single operator family definition
13059  *
13060  * Note: this also dumps any "loose" operator members that aren't bound to a
13061  * specific opclass within the opfamily.
13062  */
13063 static void
13064 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
13065 {
13066         DumpOptions *dopt = fout->dopt;
13067         PQExpBuffer query;
13068         PQExpBuffer q;
13069         PQExpBuffer delq;
13070         PQExpBuffer nameusing;
13071         PGresult   *res;
13072         PGresult   *res_ops;
13073         PGresult   *res_procs;
13074         int                     ntups;
13075         int                     i_amname;
13076         int                     i_amopstrategy;
13077         int                     i_amopreqcheck;
13078         int                     i_amopopr;
13079         int                     i_sortfamily;
13080         int                     i_sortfamilynsp;
13081         int                     i_amprocnum;
13082         int                     i_amproc;
13083         int                     i_amproclefttype;
13084         int                     i_amprocrighttype;
13085         char       *amname;
13086         char       *amopstrategy;
13087         char       *amopreqcheck;
13088         char       *amopopr;
13089         char       *sortfamily;
13090         char       *sortfamilynsp;
13091         char       *amprocnum;
13092         char       *amproc;
13093         char       *amproclefttype;
13094         char       *amprocrighttype;
13095         bool            needComma;
13096         int                     i;
13097
13098         /* Skip if not to be dumped */
13099         if (!opfinfo->dobj.dump || dopt->dataOnly)
13100                 return;
13101
13102         query = createPQExpBuffer();
13103         q = createPQExpBuffer();
13104         delq = createPQExpBuffer();
13105         nameusing = createPQExpBuffer();
13106
13107         /*
13108          * Fetch only those opfamily members that are tied directly to the
13109          * opfamily by pg_depend entries.
13110          *
13111          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
13112          * older server's opclass in which it is used.  This is to avoid
13113          * hard-to-detect breakage if a newer pg_dump is used to dump from an
13114          * older server and then reload into that old version.  This can go away
13115          * once 8.3 is so old as to not be of interest to anyone.
13116          */
13117         if (fout->remoteVersion >= 90100)
13118         {
13119                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13120                                                   "amopopr::pg_catalog.regoperator, "
13121                                                   "opfname AS sortfamily, "
13122                                                   "nspname AS sortfamilynsp "
13123                                                   "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
13124                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
13125                                                   "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
13126                                                   "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13127                                                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13128                                                   "AND refobjid = '%u'::pg_catalog.oid "
13129                                                   "AND amopfamily = '%u'::pg_catalog.oid "
13130                                                   "ORDER BY amopstrategy",
13131                                                   opfinfo->dobj.catId.oid,
13132                                                   opfinfo->dobj.catId.oid);
13133         }
13134         else if (fout->remoteVersion >= 80400)
13135         {
13136                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
13137                                                   "amopopr::pg_catalog.regoperator, "
13138                                                   "NULL AS sortfamily, "
13139                                                   "NULL AS sortfamilynsp "
13140                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13141                                                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13142                                                   "AND refobjid = '%u'::pg_catalog.oid "
13143                                                   "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13144                                                   "AND objid = ao.oid "
13145                                                   "ORDER BY amopstrategy",
13146                                                   opfinfo->dobj.catId.oid);
13147         }
13148         else
13149         {
13150                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
13151                                                   "amopopr::pg_catalog.regoperator, "
13152                                                   "NULL AS sortfamily, "
13153                                                   "NULL AS sortfamilynsp "
13154                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13155                                                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13156                                                   "AND refobjid = '%u'::pg_catalog.oid "
13157                                                   "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13158                                                   "AND objid = ao.oid "
13159                                                   "ORDER BY amopstrategy",
13160                                                   opfinfo->dobj.catId.oid);
13161         }
13162
13163         res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13164
13165         resetPQExpBuffer(query);
13166
13167         appendPQExpBuffer(query, "SELECT amprocnum, "
13168                                           "amproc::pg_catalog.regprocedure, "
13169                                           "amproclefttype::pg_catalog.regtype, "
13170                                           "amprocrighttype::pg_catalog.regtype "
13171                                           "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
13172                                           "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13173                                           "AND refobjid = '%u'::pg_catalog.oid "
13174                                           "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
13175                                           "AND objid = ap.oid "
13176                                           "ORDER BY amprocnum",
13177                                           opfinfo->dobj.catId.oid);
13178
13179         res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13180
13181         /* Get additional fields from the pg_opfamily row */
13182         resetPQExpBuffer(query);
13183
13184         appendPQExpBuffer(query, "SELECT "
13185                                           "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
13186                                           "FROM pg_catalog.pg_opfamily "
13187                                           "WHERE oid = '%u'::pg_catalog.oid",
13188                                           opfinfo->dobj.catId.oid);
13189
13190         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13191
13192         i_amname = PQfnumber(res, "amname");
13193
13194         /* amname will still be needed after we PQclear res */
13195         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
13196
13197         appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
13198                                           fmtQualifiedDumpable(opfinfo));
13199         appendPQExpBuffer(delq, " USING %s;\n",
13200                                           fmtId(amname));
13201
13202         /* Build the fixed portion of the CREATE command */
13203         appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
13204                                           fmtQualifiedDumpable(opfinfo));
13205         appendPQExpBuffer(q, " USING %s;\n",
13206                                           fmtId(amname));
13207
13208         PQclear(res);
13209
13210         /* Do we need an ALTER to add loose members? */
13211         if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
13212         {
13213                 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
13214                                                   fmtQualifiedDumpable(opfinfo));
13215                 appendPQExpBuffer(q, " USING %s ADD\n    ",
13216                                                   fmtId(amname));
13217
13218                 needComma = false;
13219
13220                 /*
13221                  * Now fetch and print the OPERATOR entries (pg_amop rows).
13222                  */
13223                 ntups = PQntuples(res_ops);
13224
13225                 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
13226                 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
13227                 i_amopopr = PQfnumber(res_ops, "amopopr");
13228                 i_sortfamily = PQfnumber(res_ops, "sortfamily");
13229                 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
13230
13231                 for (i = 0; i < ntups; i++)
13232                 {
13233                         amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
13234                         amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
13235                         amopopr = PQgetvalue(res_ops, i, i_amopopr);
13236                         sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
13237                         sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
13238
13239                         if (needComma)
13240                                 appendPQExpBufferStr(q, " ,\n    ");
13241
13242                         appendPQExpBuffer(q, "OPERATOR %s %s",
13243                                                           amopstrategy, amopopr);
13244
13245                         if (strlen(sortfamily) > 0)
13246                         {
13247                                 appendPQExpBufferStr(q, " FOR ORDER BY ");
13248                                 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
13249                                 appendPQExpBufferStr(q, fmtId(sortfamily));
13250                         }
13251
13252                         if (strcmp(amopreqcheck, "t") == 0)
13253                                 appendPQExpBufferStr(q, " RECHECK");
13254
13255                         needComma = true;
13256                 }
13257
13258                 /*
13259                  * Now fetch and print the FUNCTION entries (pg_amproc rows).
13260                  */
13261                 ntups = PQntuples(res_procs);
13262
13263                 i_amprocnum = PQfnumber(res_procs, "amprocnum");
13264                 i_amproc = PQfnumber(res_procs, "amproc");
13265                 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
13266                 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
13267
13268                 for (i = 0; i < ntups; i++)
13269                 {
13270                         amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
13271                         amproc = PQgetvalue(res_procs, i, i_amproc);
13272                         amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
13273                         amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
13274
13275                         if (needComma)
13276                                 appendPQExpBufferStr(q, " ,\n    ");
13277
13278                         appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
13279                                                           amprocnum, amproclefttype, amprocrighttype,
13280                                                           amproc);
13281
13282                         needComma = true;
13283                 }
13284
13285                 appendPQExpBufferStr(q, ";\n");
13286         }
13287
13288         appendPQExpBufferStr(nameusing, fmtId(opfinfo->dobj.name));
13289         appendPQExpBuffer(nameusing, " USING %s",
13290                                           fmtId(amname));
13291
13292         if (dopt->binary_upgrade)
13293                 binary_upgrade_extension_member(q, &opfinfo->dobj,
13294                                                                                 "OPERATOR FAMILY", nameusing->data,
13295                                                                                 opfinfo->dobj.namespace->dobj.name);
13296
13297         if (opfinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13298                 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
13299                                          opfinfo->dobj.name,
13300                                          opfinfo->dobj.namespace->dobj.name,
13301                                          NULL,
13302                                          opfinfo->rolname,
13303                                          false, "OPERATOR FAMILY", SECTION_PRE_DATA,
13304                                          q->data, delq->data, NULL,
13305                                          NULL, 0,
13306                                          NULL, NULL);
13307
13308         /* Dump Operator Family Comments */
13309         if (opfinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13310                 dumpComment(fout, "OPERATOR FAMILY", nameusing->data,
13311                                         opfinfo->dobj.namespace->dobj.name, opfinfo->rolname,
13312                                         opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
13313
13314         free(amname);
13315         PQclear(res_ops);
13316         PQclear(res_procs);
13317         destroyPQExpBuffer(query);
13318         destroyPQExpBuffer(q);
13319         destroyPQExpBuffer(delq);
13320         destroyPQExpBuffer(nameusing);
13321 }
13322
13323 /*
13324  * dumpCollation
13325  *        write out a single collation definition
13326  */
13327 static void
13328 dumpCollation(Archive *fout, CollInfo *collinfo)
13329 {
13330         DumpOptions *dopt = fout->dopt;
13331         PQExpBuffer query;
13332         PQExpBuffer q;
13333         PQExpBuffer delq;
13334         char       *qcollname;
13335         PGresult   *res;
13336         int                     i_collprovider;
13337         int                     i_collcollate;
13338         int                     i_collctype;
13339         const char *collprovider;
13340         const char *collcollate;
13341         const char *collctype;
13342
13343         /* Skip if not to be dumped */
13344         if (!collinfo->dobj.dump || dopt->dataOnly)
13345                 return;
13346
13347         query = createPQExpBuffer();
13348         q = createPQExpBuffer();
13349         delq = createPQExpBuffer();
13350
13351         qcollname = pg_strdup(fmtId(collinfo->dobj.name));
13352
13353         /* Get collation-specific details */
13354         if (fout->remoteVersion >= 100000)
13355                 appendPQExpBuffer(query, "SELECT "
13356                                                   "collprovider, "
13357                                                   "collcollate, "
13358                                                   "collctype, "
13359                                                   "collversion "
13360                                                   "FROM pg_catalog.pg_collation c "
13361                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
13362                                                   collinfo->dobj.catId.oid);
13363         else
13364                 appendPQExpBuffer(query, "SELECT "
13365                                                   "'c' AS collprovider, "
13366                                                   "collcollate, "
13367                                                   "collctype, "
13368                                                   "NULL AS collversion "
13369                                                   "FROM pg_catalog.pg_collation c "
13370                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
13371                                                   collinfo->dobj.catId.oid);
13372
13373         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13374
13375         i_collprovider = PQfnumber(res, "collprovider");
13376         i_collcollate = PQfnumber(res, "collcollate");
13377         i_collctype = PQfnumber(res, "collctype");
13378
13379         collprovider = PQgetvalue(res, 0, i_collprovider);
13380         collcollate = PQgetvalue(res, 0, i_collcollate);
13381         collctype = PQgetvalue(res, 0, i_collctype);
13382
13383         appendPQExpBuffer(delq, "DROP COLLATION %s;\n",
13384                                           fmtQualifiedDumpable(collinfo));
13385
13386         appendPQExpBuffer(q, "CREATE COLLATION %s (",
13387                                           fmtQualifiedDumpable(collinfo));
13388
13389         appendPQExpBufferStr(q, "provider = ");
13390         if (collprovider[0] == 'c')
13391                 appendPQExpBufferStr(q, "libc");
13392         else if (collprovider[0] == 'i')
13393                 appendPQExpBufferStr(q, "icu");
13394         else if (collprovider[0] == 'd')
13395                 /* to allow dumping pg_catalog; not accepted on input */
13396                 appendPQExpBufferStr(q, "default");
13397         else
13398                 exit_horribly(NULL,
13399                                           "unrecognized collation provider: %s\n",
13400                                           collprovider);
13401
13402         if (strcmp(collcollate, collctype) == 0)
13403         {
13404                 appendPQExpBufferStr(q, ", locale = ");
13405                 appendStringLiteralAH(q, collcollate, fout);
13406         }
13407         else
13408         {
13409                 appendPQExpBufferStr(q, ", lc_collate = ");
13410                 appendStringLiteralAH(q, collcollate, fout);
13411                 appendPQExpBufferStr(q, ", lc_ctype = ");
13412                 appendStringLiteralAH(q, collctype, fout);
13413         }
13414
13415         /*
13416          * For binary upgrade, carry over the collation version.  For normal
13417          * dump/restore, omit the version, so that it is computed upon restore.
13418          */
13419         if (dopt->binary_upgrade)
13420         {
13421                 int                     i_collversion;
13422
13423                 i_collversion = PQfnumber(res, "collversion");
13424                 if (!PQgetisnull(res, 0, i_collversion))
13425                 {
13426                         appendPQExpBufferStr(q, ", version = ");
13427                         appendStringLiteralAH(q,
13428                                                                   PQgetvalue(res, 0, i_collversion),
13429                                                                   fout);
13430                 }
13431         }
13432
13433         appendPQExpBufferStr(q, ");\n");
13434
13435         if (dopt->binary_upgrade)
13436                 binary_upgrade_extension_member(q, &collinfo->dobj,
13437                                                                                 "COLLATION", qcollname,
13438                                                                                 collinfo->dobj.namespace->dobj.name);
13439
13440         if (collinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13441                 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
13442                                          collinfo->dobj.name,
13443                                          collinfo->dobj.namespace->dobj.name,
13444                                          NULL,
13445                                          collinfo->rolname,
13446                                          false, "COLLATION", SECTION_PRE_DATA,
13447                                          q->data, delq->data, NULL,
13448                                          NULL, 0,
13449                                          NULL, NULL);
13450
13451         /* Dump Collation Comments */
13452         if (collinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13453                 dumpComment(fout, "COLLATION", qcollname,
13454                                         collinfo->dobj.namespace->dobj.name, collinfo->rolname,
13455                                         collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
13456
13457         PQclear(res);
13458
13459         destroyPQExpBuffer(query);
13460         destroyPQExpBuffer(q);
13461         destroyPQExpBuffer(delq);
13462         free(qcollname);
13463 }
13464
13465 /*
13466  * dumpConversion
13467  *        write out a single conversion definition
13468  */
13469 static void
13470 dumpConversion(Archive *fout, ConvInfo *convinfo)
13471 {
13472         DumpOptions *dopt = fout->dopt;
13473         PQExpBuffer query;
13474         PQExpBuffer q;
13475         PQExpBuffer delq;
13476         char       *qconvname;
13477         PGresult   *res;
13478         int                     i_conforencoding;
13479         int                     i_contoencoding;
13480         int                     i_conproc;
13481         int                     i_condefault;
13482         const char *conforencoding;
13483         const char *contoencoding;
13484         const char *conproc;
13485         bool            condefault;
13486
13487         /* Skip if not to be dumped */
13488         if (!convinfo->dobj.dump || dopt->dataOnly)
13489                 return;
13490
13491         query = createPQExpBuffer();
13492         q = createPQExpBuffer();
13493         delq = createPQExpBuffer();
13494
13495         qconvname = pg_strdup(fmtId(convinfo->dobj.name));
13496
13497         /* Get conversion-specific details */
13498         appendPQExpBuffer(query, "SELECT "
13499                                           "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
13500                                           "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
13501                                           "conproc, condefault "
13502                                           "FROM pg_catalog.pg_conversion c "
13503                                           "WHERE c.oid = '%u'::pg_catalog.oid",
13504                                           convinfo->dobj.catId.oid);
13505
13506         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13507
13508         i_conforencoding = PQfnumber(res, "conforencoding");
13509         i_contoencoding = PQfnumber(res, "contoencoding");
13510         i_conproc = PQfnumber(res, "conproc");
13511         i_condefault = PQfnumber(res, "condefault");
13512
13513         conforencoding = PQgetvalue(res, 0, i_conforencoding);
13514         contoencoding = PQgetvalue(res, 0, i_contoencoding);
13515         conproc = PQgetvalue(res, 0, i_conproc);
13516         condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
13517
13518         appendPQExpBuffer(delq, "DROP CONVERSION %s;\n",
13519                                           fmtQualifiedDumpable(convinfo));
13520
13521         appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
13522                                           (condefault) ? "DEFAULT " : "",
13523                                           fmtQualifiedDumpable(convinfo));
13524         appendStringLiteralAH(q, conforencoding, fout);
13525         appendPQExpBufferStr(q, " TO ");
13526         appendStringLiteralAH(q, contoencoding, fout);
13527         /* regproc output is already sufficiently quoted */
13528         appendPQExpBuffer(q, " FROM %s;\n", conproc);
13529
13530         if (dopt->binary_upgrade)
13531                 binary_upgrade_extension_member(q, &convinfo->dobj,
13532                                                                                 "CONVERSION", qconvname,
13533                                                                                 convinfo->dobj.namespace->dobj.name);
13534
13535         if (convinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13536                 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
13537                                          convinfo->dobj.name,
13538                                          convinfo->dobj.namespace->dobj.name,
13539                                          NULL,
13540                                          convinfo->rolname,
13541                                          false, "CONVERSION", SECTION_PRE_DATA,
13542                                          q->data, delq->data, NULL,
13543                                          NULL, 0,
13544                                          NULL, NULL);
13545
13546         /* Dump Conversion Comments */
13547         if (convinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13548                 dumpComment(fout, "CONVERSION", qconvname,
13549                                         convinfo->dobj.namespace->dobj.name, convinfo->rolname,
13550                                         convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
13551
13552         PQclear(res);
13553
13554         destroyPQExpBuffer(query);
13555         destroyPQExpBuffer(q);
13556         destroyPQExpBuffer(delq);
13557         free(qconvname);
13558 }
13559
13560 /*
13561  * format_aggregate_signature: generate aggregate name and argument list
13562  *
13563  * The argument type names are qualified if needed.  The aggregate name
13564  * is never qualified.
13565  */
13566 static char *
13567 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
13568 {
13569         PQExpBufferData buf;
13570         int                     j;
13571
13572         initPQExpBuffer(&buf);
13573         if (honor_quotes)
13574                 appendPQExpBufferStr(&buf, fmtId(agginfo->aggfn.dobj.name));
13575         else
13576                 appendPQExpBufferStr(&buf, agginfo->aggfn.dobj.name);
13577
13578         if (agginfo->aggfn.nargs == 0)
13579                 appendPQExpBuffer(&buf, "(*)");
13580         else
13581         {
13582                 appendPQExpBufferChar(&buf, '(');
13583                 for (j = 0; j < agginfo->aggfn.nargs; j++)
13584                 {
13585                         char       *typname;
13586
13587                         typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
13588                                                                                    zeroAsOpaque);
13589
13590                         appendPQExpBuffer(&buf, "%s%s",
13591                                                           (j > 0) ? ", " : "",
13592                                                           typname);
13593                         free(typname);
13594                 }
13595                 appendPQExpBufferChar(&buf, ')');
13596         }
13597         return buf.data;
13598 }
13599
13600 /*
13601  * dumpAgg
13602  *        write out a single aggregate definition
13603  */
13604 static void
13605 dumpAgg(Archive *fout, AggInfo *agginfo)
13606 {
13607         DumpOptions *dopt = fout->dopt;
13608         PQExpBuffer query;
13609         PQExpBuffer q;
13610         PQExpBuffer delq;
13611         PQExpBuffer details;
13612         char       *aggsig;                     /* identity signature */
13613         char       *aggfullsig = NULL;  /* full signature */
13614         char       *aggsig_tag;
13615         PGresult   *res;
13616         int                     i_aggtransfn;
13617         int                     i_aggfinalfn;
13618         int                     i_aggcombinefn;
13619         int                     i_aggserialfn;
13620         int                     i_aggdeserialfn;
13621         int                     i_aggmtransfn;
13622         int                     i_aggminvtransfn;
13623         int                     i_aggmfinalfn;
13624         int                     i_aggfinalextra;
13625         int                     i_aggmfinalextra;
13626         int                     i_aggfinalmodify;
13627         int                     i_aggmfinalmodify;
13628         int                     i_aggsortop;
13629         int                     i_aggkind;
13630         int                     i_aggtranstype;
13631         int                     i_aggtransspace;
13632         int                     i_aggmtranstype;
13633         int                     i_aggmtransspace;
13634         int                     i_agginitval;
13635         int                     i_aggminitval;
13636         int                     i_convertok;
13637         int                     i_proparallel;
13638         const char *aggtransfn;
13639         const char *aggfinalfn;
13640         const char *aggcombinefn;
13641         const char *aggserialfn;
13642         const char *aggdeserialfn;
13643         const char *aggmtransfn;
13644         const char *aggminvtransfn;
13645         const char *aggmfinalfn;
13646         bool            aggfinalextra;
13647         bool            aggmfinalextra;
13648         char            aggfinalmodify;
13649         char            aggmfinalmodify;
13650         const char *aggsortop;
13651         char       *aggsortconvop;
13652         char            aggkind;
13653         const char *aggtranstype;
13654         const char *aggtransspace;
13655         const char *aggmtranstype;
13656         const char *aggmtransspace;
13657         const char *agginitval;
13658         const char *aggminitval;
13659         bool            convertok;
13660         const char *proparallel;
13661         char            defaultfinalmodify;
13662
13663         /* Skip if not to be dumped */
13664         if (!agginfo->aggfn.dobj.dump || dopt->dataOnly)
13665                 return;
13666
13667         query = createPQExpBuffer();
13668         q = createPQExpBuffer();
13669         delq = createPQExpBuffer();
13670         details = createPQExpBuffer();
13671
13672         /* Get aggregate-specific details */
13673         if (fout->remoteVersion >= 110000)
13674         {
13675                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13676                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13677                                                   "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13678                                                   "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13679                                                   "aggfinalextra, aggmfinalextra, "
13680                                                   "aggfinalmodify, aggmfinalmodify, "
13681                                                   "aggsortop, "
13682                                                   "aggkind, "
13683                                                   "aggtransspace, agginitval, "
13684                                                   "aggmtransspace, aggminitval, "
13685                                                   "true AS convertok, "
13686                                                   "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13687                                                   "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13688                                                   "p.proparallel "
13689                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13690                                                   "WHERE a.aggfnoid = p.oid "
13691                                                   "AND p.oid = '%u'::pg_catalog.oid",
13692                                                   agginfo->aggfn.dobj.catId.oid);
13693         }
13694         else if (fout->remoteVersion >= 90600)
13695         {
13696                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13697                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13698                                                   "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13699                                                   "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13700                                                   "aggfinalextra, aggmfinalextra, "
13701                                                   "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13702                                                   "aggsortop, "
13703                                                   "aggkind, "
13704                                                   "aggtransspace, agginitval, "
13705                                                   "aggmtransspace, aggminitval, "
13706                                                   "true AS convertok, "
13707                                                   "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13708                                                   "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13709                                                   "p.proparallel "
13710                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13711                                                   "WHERE a.aggfnoid = p.oid "
13712                                                   "AND p.oid = '%u'::pg_catalog.oid",
13713                                                   agginfo->aggfn.dobj.catId.oid);
13714         }
13715         else if (fout->remoteVersion >= 90400)
13716         {
13717                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13718                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13719                                                   "'-' AS aggcombinefn, '-' AS aggserialfn, "
13720                                                   "'-' AS aggdeserialfn, aggmtransfn, aggminvtransfn, "
13721                                                   "aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13722                                                   "aggfinalextra, aggmfinalextra, "
13723                                                   "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13724                                                   "aggsortop, "
13725                                                   "aggkind, "
13726                                                   "aggtransspace, agginitval, "
13727                                                   "aggmtransspace, aggminitval, "
13728                                                   "true AS convertok, "
13729                                                   "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13730                                                   "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13731                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13732                                                   "WHERE a.aggfnoid = p.oid "
13733                                                   "AND p.oid = '%u'::pg_catalog.oid",
13734                                                   agginfo->aggfn.dobj.catId.oid);
13735         }
13736         else if (fout->remoteVersion >= 80400)
13737         {
13738                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13739                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13740                                                   "'-' AS aggcombinefn, '-' AS aggserialfn, "
13741                                                   "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13742                                                   "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13743                                                   "0 AS aggmtranstype, false AS aggfinalextra, "
13744                                                   "false AS aggmfinalextra, "
13745                                                   "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13746                                                   "aggsortop, "
13747                                                   "'n' AS aggkind, "
13748                                                   "0 AS aggtransspace, agginitval, "
13749                                                   "0 AS aggmtransspace, NULL AS aggminitval, "
13750                                                   "true AS convertok, "
13751                                                   "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13752                                                   "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13753                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13754                                                   "WHERE a.aggfnoid = p.oid "
13755                                                   "AND p.oid = '%u'::pg_catalog.oid",
13756                                                   agginfo->aggfn.dobj.catId.oid);
13757         }
13758         else if (fout->remoteVersion >= 80100)
13759         {
13760                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13761                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13762                                                   "'-' AS aggcombinefn, '-' AS aggserialfn, "
13763                                                   "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13764                                                   "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13765                                                   "0 AS aggmtranstype, false AS aggfinalextra, "
13766                                                   "false AS aggmfinalextra, "
13767                                                   "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13768                                                   "aggsortop, "
13769                                                   "'n' AS aggkind, "
13770                                                   "0 AS aggtransspace, agginitval, "
13771                                                   "0 AS aggmtransspace, NULL AS aggminitval, "
13772                                                   "true AS convertok "
13773                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13774                                                   "WHERE a.aggfnoid = p.oid "
13775                                                   "AND p.oid = '%u'::pg_catalog.oid",
13776                                                   agginfo->aggfn.dobj.catId.oid);
13777         }
13778         else
13779         {
13780                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13781                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13782                                                   "'-' AS aggcombinefn, '-' AS aggserialfn, "
13783                                                   "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13784                                                   "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13785                                                   "0 AS aggmtranstype, false AS aggfinalextra, "
13786                                                   "false AS aggmfinalextra, "
13787                                                   "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
13788                                                   "0 AS aggsortop, "
13789                                                   "'n' AS aggkind, "
13790                                                   "0 AS aggtransspace, agginitval, "
13791                                                   "0 AS aggmtransspace, NULL AS aggminitval, "
13792                                                   "true AS convertok "
13793                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13794                                                   "WHERE a.aggfnoid = p.oid "
13795                                                   "AND p.oid = '%u'::pg_catalog.oid",
13796                                                   agginfo->aggfn.dobj.catId.oid);
13797         }
13798
13799         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13800
13801         i_aggtransfn = PQfnumber(res, "aggtransfn");
13802         i_aggfinalfn = PQfnumber(res, "aggfinalfn");
13803         i_aggcombinefn = PQfnumber(res, "aggcombinefn");
13804         i_aggserialfn = PQfnumber(res, "aggserialfn");
13805         i_aggdeserialfn = PQfnumber(res, "aggdeserialfn");
13806         i_aggmtransfn = PQfnumber(res, "aggmtransfn");
13807         i_aggminvtransfn = PQfnumber(res, "aggminvtransfn");
13808         i_aggmfinalfn = PQfnumber(res, "aggmfinalfn");
13809         i_aggfinalextra = PQfnumber(res, "aggfinalextra");
13810         i_aggmfinalextra = PQfnumber(res, "aggmfinalextra");
13811         i_aggfinalmodify = PQfnumber(res, "aggfinalmodify");
13812         i_aggmfinalmodify = PQfnumber(res, "aggmfinalmodify");
13813         i_aggsortop = PQfnumber(res, "aggsortop");
13814         i_aggkind = PQfnumber(res, "aggkind");
13815         i_aggtranstype = PQfnumber(res, "aggtranstype");
13816         i_aggtransspace = PQfnumber(res, "aggtransspace");
13817         i_aggmtranstype = PQfnumber(res, "aggmtranstype");
13818         i_aggmtransspace = PQfnumber(res, "aggmtransspace");
13819         i_agginitval = PQfnumber(res, "agginitval");
13820         i_aggminitval = PQfnumber(res, "aggminitval");
13821         i_convertok = PQfnumber(res, "convertok");
13822         i_proparallel = PQfnumber(res, "proparallel");
13823
13824         aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
13825         aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
13826         aggcombinefn = PQgetvalue(res, 0, i_aggcombinefn);
13827         aggserialfn = PQgetvalue(res, 0, i_aggserialfn);
13828         aggdeserialfn = PQgetvalue(res, 0, i_aggdeserialfn);
13829         aggmtransfn = PQgetvalue(res, 0, i_aggmtransfn);
13830         aggminvtransfn = PQgetvalue(res, 0, i_aggminvtransfn);
13831         aggmfinalfn = PQgetvalue(res, 0, i_aggmfinalfn);
13832         aggfinalextra = (PQgetvalue(res, 0, i_aggfinalextra)[0] == 't');
13833         aggmfinalextra = (PQgetvalue(res, 0, i_aggmfinalextra)[0] == 't');
13834         aggfinalmodify = PQgetvalue(res, 0, i_aggfinalmodify)[0];
13835         aggmfinalmodify = PQgetvalue(res, 0, i_aggmfinalmodify)[0];
13836         aggsortop = PQgetvalue(res, 0, i_aggsortop);
13837         aggkind = PQgetvalue(res, 0, i_aggkind)[0];
13838         aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
13839         aggtransspace = PQgetvalue(res, 0, i_aggtransspace);
13840         aggmtranstype = PQgetvalue(res, 0, i_aggmtranstype);
13841         aggmtransspace = PQgetvalue(res, 0, i_aggmtransspace);
13842         agginitval = PQgetvalue(res, 0, i_agginitval);
13843         aggminitval = PQgetvalue(res, 0, i_aggminitval);
13844         convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
13845
13846         if (fout->remoteVersion >= 80400)
13847         {
13848                 /* 8.4 or later; we rely on server-side code for most of the work */
13849                 char       *funcargs;
13850                 char       *funciargs;
13851
13852                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
13853                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
13854                 aggfullsig = format_function_arguments(&agginfo->aggfn, funcargs, true);
13855                 aggsig = format_function_arguments(&agginfo->aggfn, funciargs, true);
13856         }
13857         else
13858                 /* pre-8.4, do it ourselves */
13859                 aggsig = format_aggregate_signature(agginfo, fout, true);
13860
13861         aggsig_tag = format_aggregate_signature(agginfo, fout, false);
13862
13863         if (i_proparallel != -1)
13864                 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
13865         else
13866                 proparallel = NULL;
13867
13868         if (!convertok)
13869         {
13870                 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
13871                                   aggsig);
13872
13873                 if (aggfullsig)
13874                         free(aggfullsig);
13875
13876                 free(aggsig);
13877
13878                 return;
13879         }
13880
13881         /* identify default modify flag for aggkind (must match DefineAggregate) */
13882         defaultfinalmodify = (aggkind == AGGKIND_NORMAL) ? AGGMODIFY_READ_ONLY : AGGMODIFY_READ_WRITE;
13883         /* replace omitted flags for old versions */
13884         if (aggfinalmodify == '0')
13885                 aggfinalmodify = defaultfinalmodify;
13886         if (aggmfinalmodify == '0')
13887                 aggmfinalmodify = defaultfinalmodify;
13888
13889         /* regproc and regtype output is already sufficiently quoted */
13890         appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
13891                                           aggtransfn, aggtranstype);
13892
13893         if (strcmp(aggtransspace, "0") != 0)
13894         {
13895                 appendPQExpBuffer(details, ",\n    SSPACE = %s",
13896                                                   aggtransspace);
13897         }
13898
13899         if (!PQgetisnull(res, 0, i_agginitval))
13900         {
13901                 appendPQExpBufferStr(details, ",\n    INITCOND = ");
13902                 appendStringLiteralAH(details, agginitval, fout);
13903         }
13904
13905         if (strcmp(aggfinalfn, "-") != 0)
13906         {
13907                 appendPQExpBuffer(details, ",\n    FINALFUNC = %s",
13908                                                   aggfinalfn);
13909                 if (aggfinalextra)
13910                         appendPQExpBufferStr(details, ",\n    FINALFUNC_EXTRA");
13911                 if (aggfinalmodify != defaultfinalmodify)
13912                 {
13913                         switch (aggfinalmodify)
13914                         {
13915                                 case AGGMODIFY_READ_ONLY:
13916                                         appendPQExpBufferStr(details, ",\n    FINALFUNC_MODIFY = READ_ONLY");
13917                                         break;
13918                                 case AGGMODIFY_SHAREABLE:
13919                                         appendPQExpBufferStr(details, ",\n    FINALFUNC_MODIFY = SHAREABLE");
13920                                         break;
13921                                 case AGGMODIFY_READ_WRITE:
13922                                         appendPQExpBufferStr(details, ",\n    FINALFUNC_MODIFY = READ_WRITE");
13923                                         break;
13924                                 default:
13925                                         exit_horribly(NULL, "unrecognized aggfinalmodify value for aggregate \"%s\"\n",
13926                                                                   agginfo->aggfn.dobj.name);
13927                                         break;
13928                         }
13929                 }
13930         }
13931
13932         if (strcmp(aggcombinefn, "-") != 0)
13933                 appendPQExpBuffer(details, ",\n    COMBINEFUNC = %s", aggcombinefn);
13934
13935         if (strcmp(aggserialfn, "-") != 0)
13936                 appendPQExpBuffer(details, ",\n    SERIALFUNC = %s", aggserialfn);
13937
13938         if (strcmp(aggdeserialfn, "-") != 0)
13939                 appendPQExpBuffer(details, ",\n    DESERIALFUNC = %s", aggdeserialfn);
13940
13941         if (strcmp(aggmtransfn, "-") != 0)
13942         {
13943                 appendPQExpBuffer(details, ",\n    MSFUNC = %s,\n    MINVFUNC = %s,\n    MSTYPE = %s",
13944                                                   aggmtransfn,
13945                                                   aggminvtransfn,
13946                                                   aggmtranstype);
13947         }
13948
13949         if (strcmp(aggmtransspace, "0") != 0)
13950         {
13951                 appendPQExpBuffer(details, ",\n    MSSPACE = %s",
13952                                                   aggmtransspace);
13953         }
13954
13955         if (!PQgetisnull(res, 0, i_aggminitval))
13956         {
13957                 appendPQExpBufferStr(details, ",\n    MINITCOND = ");
13958                 appendStringLiteralAH(details, aggminitval, fout);
13959         }
13960
13961         if (strcmp(aggmfinalfn, "-") != 0)
13962         {
13963                 appendPQExpBuffer(details, ",\n    MFINALFUNC = %s",
13964                                                   aggmfinalfn);
13965                 if (aggmfinalextra)
13966                         appendPQExpBufferStr(details, ",\n    MFINALFUNC_EXTRA");
13967                 if (aggmfinalmodify != defaultfinalmodify)
13968                 {
13969                         switch (aggmfinalmodify)
13970                         {
13971                                 case AGGMODIFY_READ_ONLY:
13972                                         appendPQExpBufferStr(details, ",\n    MFINALFUNC_MODIFY = READ_ONLY");
13973                                         break;
13974                                 case AGGMODIFY_SHAREABLE:
13975                                         appendPQExpBufferStr(details, ",\n    MFINALFUNC_MODIFY = SHAREABLE");
13976                                         break;
13977                                 case AGGMODIFY_READ_WRITE:
13978                                         appendPQExpBufferStr(details, ",\n    MFINALFUNC_MODIFY = READ_WRITE");
13979                                         break;
13980                                 default:
13981                                         exit_horribly(NULL, "unrecognized aggmfinalmodify value for aggregate \"%s\"\n",
13982                                                                   agginfo->aggfn.dobj.name);
13983                                         break;
13984                         }
13985                 }
13986         }
13987
13988         aggsortconvop = getFormattedOperatorName(fout, aggsortop);
13989         if (aggsortconvop)
13990         {
13991                 appendPQExpBuffer(details, ",\n    SORTOP = %s",
13992                                                   aggsortconvop);
13993                 free(aggsortconvop);
13994         }
13995
13996         if (aggkind == AGGKIND_HYPOTHETICAL)
13997                 appendPQExpBufferStr(details, ",\n    HYPOTHETICAL");
13998
13999         if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
14000         {
14001                 if (proparallel[0] == PROPARALLEL_SAFE)
14002                         appendPQExpBufferStr(details, ",\n    PARALLEL = safe");
14003                 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
14004                         appendPQExpBufferStr(details, ",\n    PARALLEL = restricted");
14005                 else if (proparallel[0] != PROPARALLEL_UNSAFE)
14006                         exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
14007                                                   agginfo->aggfn.dobj.name);
14008         }
14009
14010         appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
14011                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
14012                                           aggsig);
14013
14014         appendPQExpBuffer(q, "CREATE AGGREGATE %s.%s (\n%s\n);\n",
14015                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
14016                                           aggfullsig ? aggfullsig : aggsig, details->data);
14017
14018         if (dopt->binary_upgrade)
14019                 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj,
14020                                                                                 "AGGREGATE", aggsig,
14021                                                                                 agginfo->aggfn.dobj.namespace->dobj.name);
14022
14023         if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_DEFINITION)
14024                 ArchiveEntry(fout, agginfo->aggfn.dobj.catId,
14025                                          agginfo->aggfn.dobj.dumpId,
14026                                          aggsig_tag,
14027                                          agginfo->aggfn.dobj.namespace->dobj.name,
14028                                          NULL,
14029                                          agginfo->aggfn.rolname,
14030                                          false, "AGGREGATE", SECTION_PRE_DATA,
14031                                          q->data, delq->data, NULL,
14032                                          NULL, 0,
14033                                          NULL, NULL);
14034
14035         /* Dump Aggregate Comments */
14036         if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_COMMENT)
14037                 dumpComment(fout, "AGGREGATE", aggsig,
14038                                         agginfo->aggfn.dobj.namespace->dobj.name,
14039                                         agginfo->aggfn.rolname,
14040                                         agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
14041
14042         if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_SECLABEL)
14043                 dumpSecLabel(fout, "AGGREGATE", aggsig,
14044                                          agginfo->aggfn.dobj.namespace->dobj.name,
14045                                          agginfo->aggfn.rolname,
14046                                          agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
14047
14048         /*
14049          * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
14050          * command look like a function's GRANT; in particular this affects the
14051          * syntax for zero-argument aggregates and ordered-set aggregates.
14052          */
14053         free(aggsig);
14054
14055         aggsig = format_function_signature(fout, &agginfo->aggfn, true);
14056
14057         if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_ACL)
14058                 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
14059                                 "FUNCTION", aggsig, NULL,
14060                                 agginfo->aggfn.dobj.namespace->dobj.name,
14061                                 agginfo->aggfn.rolname, agginfo->aggfn.proacl,
14062                                 agginfo->aggfn.rproacl,
14063                                 agginfo->aggfn.initproacl, agginfo->aggfn.initrproacl);
14064
14065         free(aggsig);
14066         if (aggfullsig)
14067                 free(aggfullsig);
14068         free(aggsig_tag);
14069
14070         PQclear(res);
14071
14072         destroyPQExpBuffer(query);
14073         destroyPQExpBuffer(q);
14074         destroyPQExpBuffer(delq);
14075         destroyPQExpBuffer(details);
14076 }
14077
14078 /*
14079  * dumpTSParser
14080  *        write out a single text search parser
14081  */
14082 static void
14083 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
14084 {
14085         DumpOptions *dopt = fout->dopt;
14086         PQExpBuffer q;
14087         PQExpBuffer delq;
14088         char       *qprsname;
14089
14090         /* Skip if not to be dumped */
14091         if (!prsinfo->dobj.dump || dopt->dataOnly)
14092                 return;
14093
14094         q = createPQExpBuffer();
14095         delq = createPQExpBuffer();
14096
14097         qprsname = pg_strdup(fmtId(prsinfo->dobj.name));
14098
14099         appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
14100                                           fmtQualifiedDumpable(prsinfo));
14101
14102         appendPQExpBuffer(q, "    START = %s,\n",
14103                                           convertTSFunction(fout, prsinfo->prsstart));
14104         appendPQExpBuffer(q, "    GETTOKEN = %s,\n",
14105                                           convertTSFunction(fout, prsinfo->prstoken));
14106         appendPQExpBuffer(q, "    END = %s,\n",
14107                                           convertTSFunction(fout, prsinfo->prsend));
14108         if (prsinfo->prsheadline != InvalidOid)
14109                 appendPQExpBuffer(q, "    HEADLINE = %s,\n",
14110                                                   convertTSFunction(fout, prsinfo->prsheadline));
14111         appendPQExpBuffer(q, "    LEXTYPES = %s );\n",
14112                                           convertTSFunction(fout, prsinfo->prslextype));
14113
14114         appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s;\n",
14115                                           fmtQualifiedDumpable(prsinfo));
14116
14117         if (dopt->binary_upgrade)
14118                 binary_upgrade_extension_member(q, &prsinfo->dobj,
14119                                                                                 "TEXT SEARCH PARSER", qprsname,
14120                                                                                 prsinfo->dobj.namespace->dobj.name);
14121
14122         if (prsinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14123                 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
14124                                          prsinfo->dobj.name,
14125                                          prsinfo->dobj.namespace->dobj.name,
14126                                          NULL,
14127                                          "",
14128                                          false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
14129                                          q->data, delq->data, NULL,
14130                                          NULL, 0,
14131                                          NULL, NULL);
14132
14133         /* Dump Parser Comments */
14134         if (prsinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14135                 dumpComment(fout, "TEXT SEARCH PARSER", qprsname,
14136                                         prsinfo->dobj.namespace->dobj.name, "",
14137                                         prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
14138
14139         destroyPQExpBuffer(q);
14140         destroyPQExpBuffer(delq);
14141         free(qprsname);
14142 }
14143
14144 /*
14145  * dumpTSDictionary
14146  *        write out a single text search dictionary
14147  */
14148 static void
14149 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
14150 {
14151         DumpOptions *dopt = fout->dopt;
14152         PQExpBuffer q;
14153         PQExpBuffer delq;
14154         PQExpBuffer query;
14155         char       *qdictname;
14156         PGresult   *res;
14157         char       *nspname;
14158         char       *tmplname;
14159
14160         /* Skip if not to be dumped */
14161         if (!dictinfo->dobj.dump || dopt->dataOnly)
14162                 return;
14163
14164         q = createPQExpBuffer();
14165         delq = createPQExpBuffer();
14166         query = createPQExpBuffer();
14167
14168         qdictname = pg_strdup(fmtId(dictinfo->dobj.name));
14169
14170         /* Fetch name and namespace of the dictionary's template */
14171         appendPQExpBuffer(query, "SELECT nspname, tmplname "
14172                                           "FROM pg_ts_template p, pg_namespace n "
14173                                           "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
14174                                           dictinfo->dicttemplate);
14175         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14176         nspname = PQgetvalue(res, 0, 0);
14177         tmplname = PQgetvalue(res, 0, 1);
14178
14179         appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
14180                                           fmtQualifiedDumpable(dictinfo));
14181
14182         appendPQExpBufferStr(q, "    TEMPLATE = ");
14183         appendPQExpBuffer(q, "%s.", fmtId(nspname));
14184         appendPQExpBufferStr(q, fmtId(tmplname));
14185
14186         PQclear(res);
14187
14188         /* the dictinitoption can be dumped straight into the command */
14189         if (dictinfo->dictinitoption)
14190                 appendPQExpBuffer(q, ",\n    %s", dictinfo->dictinitoption);
14191
14192         appendPQExpBufferStr(q, " );\n");
14193
14194         appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s;\n",
14195                                           fmtQualifiedDumpable(dictinfo));
14196
14197         if (dopt->binary_upgrade)
14198                 binary_upgrade_extension_member(q, &dictinfo->dobj,
14199                                                                                 "TEXT SEARCH DICTIONARY", qdictname,
14200                                                                                 dictinfo->dobj.namespace->dobj.name);
14201
14202         if (dictinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14203                 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
14204                                          dictinfo->dobj.name,
14205                                          dictinfo->dobj.namespace->dobj.name,
14206                                          NULL,
14207                                          dictinfo->rolname,
14208                                          false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
14209                                          q->data, delq->data, NULL,
14210                                          NULL, 0,
14211                                          NULL, NULL);
14212
14213         /* Dump Dictionary Comments */
14214         if (dictinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14215                 dumpComment(fout, "TEXT SEARCH DICTIONARY", qdictname,
14216                                         dictinfo->dobj.namespace->dobj.name, dictinfo->rolname,
14217                                         dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
14218
14219         destroyPQExpBuffer(q);
14220         destroyPQExpBuffer(delq);
14221         destroyPQExpBuffer(query);
14222         free(qdictname);
14223 }
14224
14225 /*
14226  * dumpTSTemplate
14227  *        write out a single text search template
14228  */
14229 static void
14230 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
14231 {
14232         DumpOptions *dopt = fout->dopt;
14233         PQExpBuffer q;
14234         PQExpBuffer delq;
14235         char       *qtmplname;
14236
14237         /* Skip if not to be dumped */
14238         if (!tmplinfo->dobj.dump || dopt->dataOnly)
14239                 return;
14240
14241         q = createPQExpBuffer();
14242         delq = createPQExpBuffer();
14243
14244         qtmplname = pg_strdup(fmtId(tmplinfo->dobj.name));
14245
14246         appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
14247                                           fmtQualifiedDumpable(tmplinfo));
14248
14249         if (tmplinfo->tmplinit != InvalidOid)
14250                 appendPQExpBuffer(q, "    INIT = %s,\n",
14251                                                   convertTSFunction(fout, tmplinfo->tmplinit));
14252         appendPQExpBuffer(q, "    LEXIZE = %s );\n",
14253                                           convertTSFunction(fout, tmplinfo->tmpllexize));
14254
14255         appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s;\n",
14256                                           fmtQualifiedDumpable(tmplinfo));
14257
14258         if (dopt->binary_upgrade)
14259                 binary_upgrade_extension_member(q, &tmplinfo->dobj,
14260                                                                                 "TEXT SEARCH TEMPLATE", qtmplname,
14261                                                                                 tmplinfo->dobj.namespace->dobj.name);
14262
14263         if (tmplinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14264                 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
14265                                          tmplinfo->dobj.name,
14266                                          tmplinfo->dobj.namespace->dobj.name,
14267                                          NULL,
14268                                          "",
14269                                          false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
14270                                          q->data, delq->data, NULL,
14271                                          NULL, 0,
14272                                          NULL, NULL);
14273
14274         /* Dump Template Comments */
14275         if (tmplinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14276                 dumpComment(fout, "TEXT SEARCH TEMPLATE", qtmplname,
14277                                         tmplinfo->dobj.namespace->dobj.name, "",
14278                                         tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
14279
14280         destroyPQExpBuffer(q);
14281         destroyPQExpBuffer(delq);
14282         free(qtmplname);
14283 }
14284
14285 /*
14286  * dumpTSConfig
14287  *        write out a single text search configuration
14288  */
14289 static void
14290 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
14291 {
14292         DumpOptions *dopt = fout->dopt;
14293         PQExpBuffer q;
14294         PQExpBuffer delq;
14295         PQExpBuffer query;
14296         char       *qcfgname;
14297         PGresult   *res;
14298         char       *nspname;
14299         char       *prsname;
14300         int                     ntups,
14301                                 i;
14302         int                     i_tokenname;
14303         int                     i_dictname;
14304
14305         /* Skip if not to be dumped */
14306         if (!cfginfo->dobj.dump || dopt->dataOnly)
14307                 return;
14308
14309         q = createPQExpBuffer();
14310         delq = createPQExpBuffer();
14311         query = createPQExpBuffer();
14312
14313         qcfgname = pg_strdup(fmtId(cfginfo->dobj.name));
14314
14315         /* Fetch name and namespace of the config's parser */
14316         appendPQExpBuffer(query, "SELECT nspname, prsname "
14317                                           "FROM pg_ts_parser p, pg_namespace n "
14318                                           "WHERE p.oid = '%u' AND n.oid = prsnamespace",
14319                                           cfginfo->cfgparser);
14320         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14321         nspname = PQgetvalue(res, 0, 0);
14322         prsname = PQgetvalue(res, 0, 1);
14323
14324         appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
14325                                           fmtQualifiedDumpable(cfginfo));
14326
14327         appendPQExpBuffer(q, "    PARSER = %s.", fmtId(nspname));
14328         appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
14329
14330         PQclear(res);
14331
14332         resetPQExpBuffer(query);
14333         appendPQExpBuffer(query,
14334                                           "SELECT\n"
14335                                           "  ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t\n"
14336                                           "    WHERE t.tokid = m.maptokentype ) AS tokenname,\n"
14337                                           "  m.mapdict::pg_catalog.regdictionary AS dictname\n"
14338                                           "FROM pg_catalog.pg_ts_config_map AS m\n"
14339                                           "WHERE m.mapcfg = '%u'\n"
14340                                           "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
14341                                           cfginfo->cfgparser, cfginfo->dobj.catId.oid);
14342
14343         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14344         ntups = PQntuples(res);
14345
14346         i_tokenname = PQfnumber(res, "tokenname");
14347         i_dictname = PQfnumber(res, "dictname");
14348
14349         for (i = 0; i < ntups; i++)
14350         {
14351                 char       *tokenname = PQgetvalue(res, i, i_tokenname);
14352                 char       *dictname = PQgetvalue(res, i, i_dictname);
14353
14354                 if (i == 0 ||
14355                         strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
14356                 {
14357                         /* starting a new token type, so start a new command */
14358                         if (i > 0)
14359                                 appendPQExpBufferStr(q, ";\n");
14360                         appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
14361                                                           fmtQualifiedDumpable(cfginfo));
14362                         /* tokenname needs quoting, dictname does NOT */
14363                         appendPQExpBuffer(q, "    ADD MAPPING FOR %s WITH %s",
14364                                                           fmtId(tokenname), dictname);
14365                 }
14366                 else
14367                         appendPQExpBuffer(q, ", %s", dictname);
14368         }
14369
14370         if (ntups > 0)
14371                 appendPQExpBufferStr(q, ";\n");
14372
14373         PQclear(res);
14374
14375         appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s;\n",
14376                                           fmtQualifiedDumpable(cfginfo));
14377
14378         if (dopt->binary_upgrade)
14379                 binary_upgrade_extension_member(q, &cfginfo->dobj,
14380                                                                                 "TEXT SEARCH CONFIGURATION", qcfgname,
14381                                                                                 cfginfo->dobj.namespace->dobj.name);
14382
14383         if (cfginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14384                 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
14385                                          cfginfo->dobj.name,
14386                                          cfginfo->dobj.namespace->dobj.name,
14387                                          NULL,
14388                                          cfginfo->rolname,
14389                                          false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
14390                                          q->data, delq->data, NULL,
14391                                          NULL, 0,
14392                                          NULL, NULL);
14393
14394         /* Dump Configuration Comments */
14395         if (cfginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14396                 dumpComment(fout, "TEXT SEARCH CONFIGURATION", qcfgname,
14397                                         cfginfo->dobj.namespace->dobj.name, cfginfo->rolname,
14398                                         cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
14399
14400         destroyPQExpBuffer(q);
14401         destroyPQExpBuffer(delq);
14402         destroyPQExpBuffer(query);
14403         free(qcfgname);
14404 }
14405
14406 /*
14407  * dumpForeignDataWrapper
14408  *        write out a single foreign-data wrapper definition
14409  */
14410 static void
14411 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
14412 {
14413         DumpOptions *dopt = fout->dopt;
14414         PQExpBuffer q;
14415         PQExpBuffer delq;
14416         char       *qfdwname;
14417
14418         /* Skip if not to be dumped */
14419         if (!fdwinfo->dobj.dump || dopt->dataOnly)
14420                 return;
14421
14422         q = createPQExpBuffer();
14423         delq = createPQExpBuffer();
14424
14425         qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
14426
14427         appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
14428                                           qfdwname);
14429
14430         if (strcmp(fdwinfo->fdwhandler, "-") != 0)
14431                 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
14432
14433         if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
14434                 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
14435
14436         if (strlen(fdwinfo->fdwoptions) > 0)
14437                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", fdwinfo->fdwoptions);
14438
14439         appendPQExpBufferStr(q, ";\n");
14440
14441         appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
14442                                           qfdwname);
14443
14444         if (dopt->binary_upgrade)
14445                 binary_upgrade_extension_member(q, &fdwinfo->dobj,
14446                                                                                 "FOREIGN DATA WRAPPER", qfdwname,
14447                                                                                 NULL);
14448
14449         if (fdwinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14450                 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14451                                          fdwinfo->dobj.name,
14452                                          NULL,
14453                                          NULL,
14454                                          fdwinfo->rolname,
14455                                          false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
14456                                          q->data, delq->data, NULL,
14457                                          NULL, 0,
14458                                          NULL, NULL);
14459
14460         /* Dump Foreign Data Wrapper Comments */
14461         if (fdwinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14462                 dumpComment(fout, "FOREIGN DATA WRAPPER", qfdwname,
14463                                         NULL, fdwinfo->rolname,
14464                                         fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
14465
14466         /* Handle the ACL */
14467         if (fdwinfo->dobj.dump & DUMP_COMPONENT_ACL)
14468                 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14469                                 "FOREIGN DATA WRAPPER", qfdwname, NULL,
14470                                 NULL, fdwinfo->rolname,
14471                                 fdwinfo->fdwacl, fdwinfo->rfdwacl,
14472                                 fdwinfo->initfdwacl, fdwinfo->initrfdwacl);
14473
14474         free(qfdwname);
14475
14476         destroyPQExpBuffer(q);
14477         destroyPQExpBuffer(delq);
14478 }
14479
14480 /*
14481  * dumpForeignServer
14482  *        write out a foreign server definition
14483  */
14484 static void
14485 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
14486 {
14487         DumpOptions *dopt = fout->dopt;
14488         PQExpBuffer q;
14489         PQExpBuffer delq;
14490         PQExpBuffer query;
14491         PGresult   *res;
14492         char       *qsrvname;
14493         char       *fdwname;
14494
14495         /* Skip if not to be dumped */
14496         if (!srvinfo->dobj.dump || dopt->dataOnly)
14497                 return;
14498
14499         q = createPQExpBuffer();
14500         delq = createPQExpBuffer();
14501         query = createPQExpBuffer();
14502
14503         qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
14504
14505         /* look up the foreign-data wrapper */
14506         appendPQExpBuffer(query, "SELECT fdwname "
14507                                           "FROM pg_foreign_data_wrapper w "
14508                                           "WHERE w.oid = '%u'",
14509                                           srvinfo->srvfdw);
14510         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14511         fdwname = PQgetvalue(res, 0, 0);
14512
14513         appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
14514         if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
14515         {
14516                 appendPQExpBufferStr(q, " TYPE ");
14517                 appendStringLiteralAH(q, srvinfo->srvtype, fout);
14518         }
14519         if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
14520         {
14521                 appendPQExpBufferStr(q, " VERSION ");
14522                 appendStringLiteralAH(q, srvinfo->srvversion, fout);
14523         }
14524
14525         appendPQExpBufferStr(q, " FOREIGN DATA WRAPPER ");
14526         appendPQExpBufferStr(q, fmtId(fdwname));
14527
14528         if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
14529                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", srvinfo->srvoptions);
14530
14531         appendPQExpBufferStr(q, ";\n");
14532
14533         appendPQExpBuffer(delq, "DROP SERVER %s;\n",
14534                                           qsrvname);
14535
14536         if (dopt->binary_upgrade)
14537                 binary_upgrade_extension_member(q, &srvinfo->dobj,
14538                                                                                 "SERVER", qsrvname, NULL);
14539
14540         if (srvinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14541                 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14542                                          srvinfo->dobj.name,
14543                                          NULL,
14544                                          NULL,
14545                                          srvinfo->rolname,
14546                                          false, "SERVER", SECTION_PRE_DATA,
14547                                          q->data, delq->data, NULL,
14548                                          NULL, 0,
14549                                          NULL, NULL);
14550
14551         /* Dump Foreign Server Comments */
14552         if (srvinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14553                 dumpComment(fout, "SERVER", qsrvname,
14554                                         NULL, srvinfo->rolname,
14555                                         srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
14556
14557         /* Handle the ACL */
14558         if (srvinfo->dobj.dump & DUMP_COMPONENT_ACL)
14559                 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14560                                 "FOREIGN SERVER", qsrvname, NULL,
14561                                 NULL, srvinfo->rolname,
14562                                 srvinfo->srvacl, srvinfo->rsrvacl,
14563                                 srvinfo->initsrvacl, srvinfo->initrsrvacl);
14564
14565         /* Dump user mappings */
14566         if (srvinfo->dobj.dump & DUMP_COMPONENT_USERMAP)
14567                 dumpUserMappings(fout,
14568                                                  srvinfo->dobj.name, NULL,
14569                                                  srvinfo->rolname,
14570                                                  srvinfo->dobj.catId, srvinfo->dobj.dumpId);
14571
14572         free(qsrvname);
14573
14574         destroyPQExpBuffer(q);
14575         destroyPQExpBuffer(delq);
14576         destroyPQExpBuffer(query);
14577 }
14578
14579 /*
14580  * dumpUserMappings
14581  *
14582  * This routine is used to dump any user mappings associated with the
14583  * server handed to this routine. Should be called after ArchiveEntry()
14584  * for the server.
14585  */
14586 static void
14587 dumpUserMappings(Archive *fout,
14588                                  const char *servername, const char *namespace,
14589                                  const char *owner,
14590                                  CatalogId catalogId, DumpId dumpId)
14591 {
14592         PQExpBuffer q;
14593         PQExpBuffer delq;
14594         PQExpBuffer query;
14595         PQExpBuffer tag;
14596         PGresult   *res;
14597         int                     ntups;
14598         int                     i_usename;
14599         int                     i_umoptions;
14600         int                     i;
14601
14602         q = createPQExpBuffer();
14603         tag = createPQExpBuffer();
14604         delq = createPQExpBuffer();
14605         query = createPQExpBuffer();
14606
14607         /*
14608          * We read from the publicly accessible view pg_user_mappings, so as not
14609          * to fail if run by a non-superuser.  Note that the view will show
14610          * umoptions as null if the user hasn't got privileges for the associated
14611          * server; this means that pg_dump will dump such a mapping, but with no
14612          * OPTIONS clause.  A possible alternative is to skip such mappings
14613          * altogether, but it's not clear that that's an improvement.
14614          */
14615         appendPQExpBuffer(query,
14616                                           "SELECT usename, "
14617                                           "array_to_string(ARRAY("
14618                                           "SELECT quote_ident(option_name) || ' ' || "
14619                                           "quote_literal(option_value) "
14620                                           "FROM pg_options_to_table(umoptions) "
14621                                           "ORDER BY option_name"
14622                                           "), E',\n    ') AS umoptions "
14623                                           "FROM pg_user_mappings "
14624                                           "WHERE srvid = '%u' "
14625                                           "ORDER BY usename",
14626                                           catalogId.oid);
14627
14628         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14629
14630         ntups = PQntuples(res);
14631         i_usename = PQfnumber(res, "usename");
14632         i_umoptions = PQfnumber(res, "umoptions");
14633
14634         for (i = 0; i < ntups; i++)
14635         {
14636                 char       *usename;
14637                 char       *umoptions;
14638
14639                 usename = PQgetvalue(res, i, i_usename);
14640                 umoptions = PQgetvalue(res, i, i_umoptions);
14641
14642                 resetPQExpBuffer(q);
14643                 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
14644                 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
14645
14646                 if (umoptions && strlen(umoptions) > 0)
14647                         appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", umoptions);
14648
14649                 appendPQExpBufferStr(q, ";\n");
14650
14651                 resetPQExpBuffer(delq);
14652                 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
14653                 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
14654
14655                 resetPQExpBuffer(tag);
14656                 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
14657                                                   usename, servername);
14658
14659                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14660                                          tag->data,
14661                                          namespace,
14662                                          NULL,
14663                                          owner, false,
14664                                          "USER MAPPING", SECTION_PRE_DATA,
14665                                          q->data, delq->data, NULL,
14666                                          &dumpId, 1,
14667                                          NULL, NULL);
14668         }
14669
14670         PQclear(res);
14671
14672         destroyPQExpBuffer(query);
14673         destroyPQExpBuffer(delq);
14674         destroyPQExpBuffer(tag);
14675         destroyPQExpBuffer(q);
14676 }
14677
14678 /*
14679  * Write out default privileges information
14680  */
14681 static void
14682 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
14683 {
14684         DumpOptions *dopt = fout->dopt;
14685         PQExpBuffer q;
14686         PQExpBuffer tag;
14687         const char *type;
14688
14689         /* Skip if not to be dumped */
14690         if (!daclinfo->dobj.dump || dopt->dataOnly || dopt->aclsSkip)
14691                 return;
14692
14693         q = createPQExpBuffer();
14694         tag = createPQExpBuffer();
14695
14696         switch (daclinfo->defaclobjtype)
14697         {
14698                 case DEFACLOBJ_RELATION:
14699                         type = "TABLES";
14700                         break;
14701                 case DEFACLOBJ_SEQUENCE:
14702                         type = "SEQUENCES";
14703                         break;
14704                 case DEFACLOBJ_FUNCTION:
14705                         type = "FUNCTIONS";
14706                         break;
14707                 case DEFACLOBJ_TYPE:
14708                         type = "TYPES";
14709                         break;
14710                 case DEFACLOBJ_NAMESPACE:
14711                         type = "SCHEMAS";
14712                         break;
14713                 default:
14714                         /* shouldn't get here */
14715                         exit_horribly(NULL,
14716                                                   "unrecognized object type in default privileges: %d\n",
14717                                                   (int) daclinfo->defaclobjtype);
14718                         type = "";                      /* keep compiler quiet */
14719         }
14720
14721         appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
14722
14723         /* build the actual command(s) for this tuple */
14724         if (!buildDefaultACLCommands(type,
14725                                                                  daclinfo->dobj.namespace != NULL ?
14726                                                                  daclinfo->dobj.namespace->dobj.name : NULL,
14727                                                                  daclinfo->defaclacl,
14728                                                                  daclinfo->rdefaclacl,
14729                                                                  daclinfo->initdefaclacl,
14730                                                                  daclinfo->initrdefaclacl,
14731                                                                  daclinfo->defaclrole,
14732                                                                  fout->remoteVersion,
14733                                                                  q))
14734                 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
14735                                           daclinfo->defaclacl);
14736
14737         if (daclinfo->dobj.dump & DUMP_COMPONENT_ACL)
14738                 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
14739                                          tag->data,
14740                                          daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
14741                                          NULL,
14742                                          daclinfo->defaclrole,
14743                                          false, "DEFAULT ACL", SECTION_POST_DATA,
14744                                          q->data, "", NULL,
14745                                          NULL, 0,
14746                                          NULL, NULL);
14747
14748         destroyPQExpBuffer(tag);
14749         destroyPQExpBuffer(q);
14750 }
14751
14752 /*----------
14753  * Write out grant/revoke information
14754  *
14755  * 'objCatId' is the catalog ID of the underlying object.
14756  * 'objDumpId' is the dump ID of the underlying object.
14757  * 'type' must be one of
14758  *              TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
14759  *              FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
14760  * 'name' is the formatted name of the object.  Must be quoted etc. already.
14761  * 'subname' is the formatted name of the sub-object, if any.  Must be quoted.
14762  *              (Currently we assume that subname is only provided for table columns.)
14763  * 'nspname' is the namespace the object is in (NULL if none).
14764  * 'owner' is the owner, NULL if there is no owner (for languages).
14765  * 'acls' contains the ACL string of the object from the appropriate system
14766  *              catalog field; it will be passed to buildACLCommands for building the
14767  *              appropriate GRANT commands.
14768  * 'racls' contains the ACL string of any initial-but-now-revoked ACLs of the
14769  *              object; it will be passed to buildACLCommands for building the
14770  *              appropriate REVOKE commands.
14771  * 'initacls' In binary-upgrade mode, ACL string of the object's initial
14772  *              privileges, to be recorded into pg_init_privs
14773  * 'initracls' In binary-upgrade mode, ACL string of the object's
14774  *              revoked-from-default privileges, to be recorded into pg_init_privs
14775  *
14776  * NB: initacls/initracls are needed because extensions can set privileges on
14777  * an object during the extension's script file and we record those into
14778  * pg_init_privs as that object's initial privileges.
14779  *----------
14780  */
14781 static void
14782 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
14783                 const char *type, const char *name, const char *subname,
14784                 const char *nspname, const char *owner,
14785                 const char *acls, const char *racls,
14786                 const char *initacls, const char *initracls)
14787 {
14788         DumpOptions *dopt = fout->dopt;
14789         PQExpBuffer sql;
14790
14791         /* Do nothing if ACL dump is not enabled */
14792         if (dopt->aclsSkip)
14793                 return;
14794
14795         /* --data-only skips ACLs *except* BLOB ACLs */
14796         if (dopt->dataOnly && strcmp(type, "LARGE OBJECT") != 0)
14797                 return;
14798
14799         sql = createPQExpBuffer();
14800
14801         /*
14802          * Check to see if this object has had any initial ACLs included for it.
14803          * If so, we are in binary upgrade mode and these are the ACLs to turn
14804          * into GRANT and REVOKE statements to set and record the initial
14805          * privileges for an extension object.  Let the backend know that these
14806          * are to be recorded by calling binary_upgrade_set_record_init_privs()
14807          * before and after.
14808          */
14809         if (strlen(initacls) != 0 || strlen(initracls) != 0)
14810         {
14811                 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(true);\n");
14812                 if (!buildACLCommands(name, subname, nspname, type,
14813                                                           initacls, initracls, owner,
14814                                                           "", fout->remoteVersion, sql))
14815                         exit_horribly(NULL,
14816                                                   "could not parse initial GRANT ACL list (%s) or initial REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14817                                                   initacls, initracls, name, type);
14818                 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(false);\n");
14819         }
14820
14821         if (!buildACLCommands(name, subname, nspname, type,
14822                                                   acls, racls, owner,
14823                                                   "", fout->remoteVersion, sql))
14824                 exit_horribly(NULL,
14825                                           "could not parse GRANT ACL list (%s) or REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14826                                           acls, racls, name, type);
14827
14828         if (sql->len > 0)
14829         {
14830                 PQExpBuffer tag = createPQExpBuffer();
14831
14832                 if (subname)
14833                         appendPQExpBuffer(tag, "COLUMN %s.%s", name, subname);
14834                 else
14835                         appendPQExpBuffer(tag, "%s %s", type, name);
14836
14837                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14838                                          tag->data, nspname,
14839                                          NULL,
14840                                          owner ? owner : "",
14841                                          false, "ACL", SECTION_NONE,
14842                                          sql->data, "", NULL,
14843                                          &(objDumpId), 1,
14844                                          NULL, NULL);
14845                 destroyPQExpBuffer(tag);
14846         }
14847
14848         destroyPQExpBuffer(sql);
14849 }
14850
14851 /*
14852  * dumpSecLabel
14853  *
14854  * This routine is used to dump any security labels associated with the
14855  * object handed to this routine. The routine takes the object type
14856  * and object name (ready to print, except for schema decoration), plus
14857  * the namespace and owner of the object (for labeling the ArchiveEntry),
14858  * plus catalog ID and subid which are the lookup key for pg_seclabel,
14859  * plus the dump ID for the object (for setting a dependency).
14860  * If a matching pg_seclabel entry is found, it is dumped.
14861  *
14862  * Note: although this routine takes a dumpId for dependency purposes,
14863  * that purpose is just to mark the dependency in the emitted dump file
14864  * for possible future use by pg_restore.  We do NOT use it for determining
14865  * ordering of the label in the dump file, because this routine is called
14866  * after dependency sorting occurs.  This routine should be called just after
14867  * calling ArchiveEntry() for the specified object.
14868  */
14869 static void
14870 dumpSecLabel(Archive *fout, const char *type, const char *name,
14871                          const char *namespace, const char *owner,
14872                          CatalogId catalogId, int subid, DumpId dumpId)
14873 {
14874         DumpOptions *dopt = fout->dopt;
14875         SecLabelItem *labels;
14876         int                     nlabels;
14877         int                     i;
14878         PQExpBuffer query;
14879
14880         /* do nothing, if --no-security-labels is supplied */
14881         if (dopt->no_security_labels)
14882                 return;
14883
14884         /* Security labels are schema not data ... except blob labels are data */
14885         if (strcmp(type, "LARGE OBJECT") != 0)
14886         {
14887                 if (dopt->dataOnly)
14888                         return;
14889         }
14890         else
14891         {
14892                 /* We do dump blob security labels in binary-upgrade mode */
14893                 if (dopt->schemaOnly && !dopt->binary_upgrade)
14894                         return;
14895         }
14896
14897         /* Search for security labels associated with catalogId, using table */
14898         nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
14899
14900         query = createPQExpBuffer();
14901
14902         for (i = 0; i < nlabels; i++)
14903         {
14904                 /*
14905                  * Ignore label entries for which the subid doesn't match.
14906                  */
14907                 if (labels[i].objsubid != subid)
14908                         continue;
14909
14910                 appendPQExpBuffer(query,
14911                                                   "SECURITY LABEL FOR %s ON %s ",
14912                                                   fmtId(labels[i].provider), type);
14913                 if (namespace && *namespace)
14914                         appendPQExpBuffer(query, "%s.", fmtId(namespace));
14915                 appendPQExpBuffer(query, "%s IS ", name);
14916                 appendStringLiteralAH(query, labels[i].label, fout);
14917                 appendPQExpBufferStr(query, ";\n");
14918         }
14919
14920         if (query->len > 0)
14921         {
14922                 PQExpBuffer tag = createPQExpBuffer();
14923
14924                 appendPQExpBuffer(tag, "%s %s", type, name);
14925                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14926                                          tag->data, namespace, NULL, owner,
14927                                          false, "SECURITY LABEL", SECTION_NONE,
14928                                          query->data, "", NULL,
14929                                          &(dumpId), 1,
14930                                          NULL, NULL);
14931                 destroyPQExpBuffer(tag);
14932         }
14933
14934         destroyPQExpBuffer(query);
14935 }
14936
14937 /*
14938  * dumpTableSecLabel
14939  *
14940  * As above, but dump security label for both the specified table (or view)
14941  * and its columns.
14942  */
14943 static void
14944 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
14945 {
14946         DumpOptions *dopt = fout->dopt;
14947         SecLabelItem *labels;
14948         int                     nlabels;
14949         int                     i;
14950         PQExpBuffer query;
14951         PQExpBuffer target;
14952
14953         /* do nothing, if --no-security-labels is supplied */
14954         if (dopt->no_security_labels)
14955                 return;
14956
14957         /* SecLabel are SCHEMA not data */
14958         if (dopt->dataOnly)
14959                 return;
14960
14961         /* Search for comments associated with relation, using table */
14962         nlabels = findSecLabels(fout,
14963                                                         tbinfo->dobj.catId.tableoid,
14964                                                         tbinfo->dobj.catId.oid,
14965                                                         &labels);
14966
14967         /* If security labels exist, build SECURITY LABEL statements */
14968         if (nlabels <= 0)
14969                 return;
14970
14971         query = createPQExpBuffer();
14972         target = createPQExpBuffer();
14973
14974         for (i = 0; i < nlabels; i++)
14975         {
14976                 const char *colname;
14977                 const char *provider = labels[i].provider;
14978                 const char *label = labels[i].label;
14979                 int                     objsubid = labels[i].objsubid;
14980
14981                 resetPQExpBuffer(target);
14982                 if (objsubid == 0)
14983                 {
14984                         appendPQExpBuffer(target, "%s %s", reltypename,
14985                                                           fmtQualifiedDumpable(tbinfo));
14986                 }
14987                 else
14988                 {
14989                         colname = getAttrName(objsubid, tbinfo);
14990                         /* first fmtXXX result must be consumed before calling again */
14991                         appendPQExpBuffer(target, "COLUMN %s",
14992                                                           fmtQualifiedDumpable(tbinfo));
14993                         appendPQExpBuffer(target, ".%s", fmtId(colname));
14994                 }
14995                 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
14996                                                   fmtId(provider), target->data);
14997                 appendStringLiteralAH(query, label, fout);
14998                 appendPQExpBufferStr(query, ";\n");
14999         }
15000         if (query->len > 0)
15001         {
15002                 resetPQExpBuffer(target);
15003                 appendPQExpBuffer(target, "%s %s", reltypename,
15004                                                   fmtId(tbinfo->dobj.name));
15005                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
15006                                          target->data,
15007                                          tbinfo->dobj.namespace->dobj.name,
15008                                          NULL, tbinfo->rolname,
15009                                          false, "SECURITY LABEL", SECTION_NONE,
15010                                          query->data, "", NULL,
15011                                          &(tbinfo->dobj.dumpId), 1,
15012                                          NULL, NULL);
15013         }
15014         destroyPQExpBuffer(query);
15015         destroyPQExpBuffer(target);
15016 }
15017
15018 /*
15019  * findSecLabels
15020  *
15021  * Find the security label(s), if any, associated with the given object.
15022  * All the objsubid values associated with the given classoid/objoid are
15023  * found with one search.
15024  */
15025 static int
15026 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
15027 {
15028         /* static storage for table of security labels */
15029         static SecLabelItem *labels = NULL;
15030         static int      nlabels = -1;
15031
15032         SecLabelItem *middle = NULL;
15033         SecLabelItem *low;
15034         SecLabelItem *high;
15035         int                     nmatch;
15036
15037         /* Get security labels if we didn't already */
15038         if (nlabels < 0)
15039                 nlabels = collectSecLabels(fout, &labels);
15040
15041         if (nlabels <= 0)                       /* no labels, so no match is possible */
15042         {
15043                 *items = NULL;
15044                 return 0;
15045         }
15046
15047         /*
15048          * Do binary search to find some item matching the object.
15049          */
15050         low = &labels[0];
15051         high = &labels[nlabels - 1];
15052         while (low <= high)
15053         {
15054                 middle = low + (high - low) / 2;
15055
15056                 if (classoid < middle->classoid)
15057                         high = middle - 1;
15058                 else if (classoid > middle->classoid)
15059                         low = middle + 1;
15060                 else if (objoid < middle->objoid)
15061                         high = middle - 1;
15062                 else if (objoid > middle->objoid)
15063                         low = middle + 1;
15064                 else
15065                         break;                          /* found a match */
15066         }
15067
15068         if (low > high)                         /* no matches */
15069         {
15070                 *items = NULL;
15071                 return 0;
15072         }
15073
15074         /*
15075          * Now determine how many items match the object.  The search loop
15076          * invariant still holds: only items between low and high inclusive could
15077          * match.
15078          */
15079         nmatch = 1;
15080         while (middle > low)
15081         {
15082                 if (classoid != middle[-1].classoid ||
15083                         objoid != middle[-1].objoid)
15084                         break;
15085                 middle--;
15086                 nmatch++;
15087         }
15088
15089         *items = middle;
15090
15091         middle += nmatch;
15092         while (middle <= high)
15093         {
15094                 if (classoid != middle->classoid ||
15095                         objoid != middle->objoid)
15096                         break;
15097                 middle++;
15098                 nmatch++;
15099         }
15100
15101         return nmatch;
15102 }
15103
15104 /*
15105  * collectSecLabels
15106  *
15107  * Construct a table of all security labels available for database objects.
15108  * It's much faster to pull them all at once.
15109  *
15110  * The table is sorted by classoid/objid/objsubid for speed in lookup.
15111  */
15112 static int
15113 collectSecLabels(Archive *fout, SecLabelItem **items)
15114 {
15115         PGresult   *res;
15116         PQExpBuffer query;
15117         int                     i_label;
15118         int                     i_provider;
15119         int                     i_classoid;
15120         int                     i_objoid;
15121         int                     i_objsubid;
15122         int                     ntups;
15123         int                     i;
15124         SecLabelItem *labels;
15125
15126         query = createPQExpBuffer();
15127
15128         appendPQExpBufferStr(query,
15129                                                  "SELECT label, provider, classoid, objoid, objsubid "
15130                                                  "FROM pg_catalog.pg_seclabel "
15131                                                  "ORDER BY classoid, objoid, objsubid");
15132
15133         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15134
15135         /* Construct lookup table containing OIDs in numeric form */
15136         i_label = PQfnumber(res, "label");
15137         i_provider = PQfnumber(res, "provider");
15138         i_classoid = PQfnumber(res, "classoid");
15139         i_objoid = PQfnumber(res, "objoid");
15140         i_objsubid = PQfnumber(res, "objsubid");
15141
15142         ntups = PQntuples(res);
15143
15144         labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
15145
15146         for (i = 0; i < ntups; i++)
15147         {
15148                 labels[i].label = PQgetvalue(res, i, i_label);
15149                 labels[i].provider = PQgetvalue(res, i, i_provider);
15150                 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
15151                 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
15152                 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
15153         }
15154
15155         /* Do NOT free the PGresult since we are keeping pointers into it */
15156         destroyPQExpBuffer(query);
15157
15158         *items = labels;
15159         return ntups;
15160 }
15161
15162 /*
15163  * dumpTable
15164  *        write out to fout the declarations (not data) of a user-defined table
15165  */
15166 static void
15167 dumpTable(Archive *fout, TableInfo *tbinfo)
15168 {
15169         DumpOptions *dopt = fout->dopt;
15170         char       *namecopy;
15171
15172         /*
15173          * noop if we are not dumping anything about this table, or if we are
15174          * doing a data-only dump
15175          */
15176         if (!tbinfo->dobj.dump || dopt->dataOnly)
15177                 return;
15178
15179         if (tbinfo->relkind == RELKIND_SEQUENCE)
15180                 dumpSequence(fout, tbinfo);
15181         else
15182                 dumpTableSchema(fout, tbinfo);
15183
15184         /* Handle the ACL here */
15185         namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
15186         if (tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15187         {
15188                 const char *objtype =
15189                 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" : "TABLE";
15190
15191                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15192                                 objtype, namecopy, NULL,
15193                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15194                                 tbinfo->relacl, tbinfo->rrelacl,
15195                                 tbinfo->initrelacl, tbinfo->initrrelacl);
15196         }
15197
15198         /*
15199          * Handle column ACLs, if any.  Note: we pull these with a separate query
15200          * rather than trying to fetch them during getTableAttrs, so that we won't
15201          * miss ACLs on system columns.
15202          */
15203         if (fout->remoteVersion >= 80400 && tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15204         {
15205                 PQExpBuffer query = createPQExpBuffer();
15206                 PGresult   *res;
15207                 int                     i;
15208
15209                 if (fout->remoteVersion >= 90600)
15210                 {
15211                         PQExpBuffer acl_subquery = createPQExpBuffer();
15212                         PQExpBuffer racl_subquery = createPQExpBuffer();
15213                         PQExpBuffer initacl_subquery = createPQExpBuffer();
15214                         PQExpBuffer initracl_subquery = createPQExpBuffer();
15215
15216                         buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
15217                                                         initracl_subquery, "at.attacl", "c.relowner", "'c'",
15218                                                         dopt->binary_upgrade);
15219
15220                         appendPQExpBuffer(query,
15221                                                           "SELECT at.attname, "
15222                                                           "%s AS attacl, "
15223                                                           "%s AS rattacl, "
15224                                                           "%s AS initattacl, "
15225                                                           "%s AS initrattacl "
15226                                                           "FROM pg_catalog.pg_attribute at "
15227                                                           "JOIN pg_catalog.pg_class c ON (at.attrelid = c.oid) "
15228                                                           "LEFT JOIN pg_catalog.pg_init_privs pip ON "
15229                                                           "(at.attrelid = pip.objoid "
15230                                                           "AND pip.classoid = 'pg_catalog.pg_class'::pg_catalog.regclass "
15231                                                           "AND at.attnum = pip.objsubid) "
15232                                                           "WHERE at.attrelid = '%u'::pg_catalog.oid AND "
15233                                                           "NOT at.attisdropped "
15234                                                           "AND ("
15235                                                           "%s IS NOT NULL OR "
15236                                                           "%s IS NOT NULL OR "
15237                                                           "%s IS NOT NULL OR "
15238                                                           "%s IS NOT NULL)"
15239                                                           "ORDER BY at.attnum",
15240                                                           acl_subquery->data,
15241                                                           racl_subquery->data,
15242                                                           initacl_subquery->data,
15243                                                           initracl_subquery->data,
15244                                                           tbinfo->dobj.catId.oid,
15245                                                           acl_subquery->data,
15246                                                           racl_subquery->data,
15247                                                           initacl_subquery->data,
15248                                                           initracl_subquery->data);
15249
15250                         destroyPQExpBuffer(acl_subquery);
15251                         destroyPQExpBuffer(racl_subquery);
15252                         destroyPQExpBuffer(initacl_subquery);
15253                         destroyPQExpBuffer(initracl_subquery);
15254                 }
15255                 else
15256                 {
15257                         appendPQExpBuffer(query,
15258                                                           "SELECT attname, attacl, NULL as rattacl, "
15259                                                           "NULL AS initattacl, NULL AS initrattacl "
15260                                                           "FROM pg_catalog.pg_attribute "
15261                                                           "WHERE attrelid = '%u'::pg_catalog.oid AND NOT attisdropped "
15262                                                           "AND attacl IS NOT NULL "
15263                                                           "ORDER BY attnum",
15264                                                           tbinfo->dobj.catId.oid);
15265                 }
15266
15267                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15268
15269                 for (i = 0; i < PQntuples(res); i++)
15270                 {
15271                         char       *attname = PQgetvalue(res, i, 0);
15272                         char       *attacl = PQgetvalue(res, i, 1);
15273                         char       *rattacl = PQgetvalue(res, i, 2);
15274                         char       *initattacl = PQgetvalue(res, i, 3);
15275                         char       *initrattacl = PQgetvalue(res, i, 4);
15276                         char       *attnamecopy;
15277
15278                         attnamecopy = pg_strdup(fmtId(attname));
15279                         /* Column's GRANT type is always TABLE */
15280                         dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15281                                         "TABLE", namecopy, attnamecopy,
15282                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
15283                                         attacl, rattacl, initattacl, initrattacl);
15284                         free(attnamecopy);
15285                 }
15286                 PQclear(res);
15287                 destroyPQExpBuffer(query);
15288         }
15289
15290         free(namecopy);
15291
15292         return;
15293 }
15294
15295 /*
15296  * Create the AS clause for a view or materialized view. The semicolon is
15297  * stripped because a materialized view must add a WITH NO DATA clause.
15298  *
15299  * This returns a new buffer which must be freed by the caller.
15300  */
15301 static PQExpBuffer
15302 createViewAsClause(Archive *fout, TableInfo *tbinfo)
15303 {
15304         PQExpBuffer query = createPQExpBuffer();
15305         PQExpBuffer result = createPQExpBuffer();
15306         PGresult   *res;
15307         int                     len;
15308
15309         /* Fetch the view definition */
15310         appendPQExpBuffer(query,
15311                                           "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
15312                                           tbinfo->dobj.catId.oid);
15313
15314         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15315
15316         if (PQntuples(res) != 1)
15317         {
15318                 if (PQntuples(res) < 1)
15319                         exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
15320                                                   tbinfo->dobj.name);
15321                 else
15322                         exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
15323                                                   tbinfo->dobj.name);
15324         }
15325
15326         len = PQgetlength(res, 0, 0);
15327
15328         if (len == 0)
15329                 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
15330                                           tbinfo->dobj.name);
15331
15332         /* Strip off the trailing semicolon so that other things may follow. */
15333         Assert(PQgetvalue(res, 0, 0)[len - 1] == ';');
15334         appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
15335
15336         PQclear(res);
15337         destroyPQExpBuffer(query);
15338
15339         return result;
15340 }
15341
15342 /*
15343  * Create a dummy AS clause for a view.  This is used when the real view
15344  * definition has to be postponed because of circular dependencies.
15345  * We must duplicate the view's external properties -- column names and types
15346  * (including collation) -- so that it works for subsequent references.
15347  *
15348  * This returns a new buffer which must be freed by the caller.
15349  */
15350 static PQExpBuffer
15351 createDummyViewAsClause(Archive *fout, TableInfo *tbinfo)
15352 {
15353         PQExpBuffer result = createPQExpBuffer();
15354         int                     j;
15355
15356         appendPQExpBufferStr(result, "SELECT");
15357
15358         for (j = 0; j < tbinfo->numatts; j++)
15359         {
15360                 if (j > 0)
15361                         appendPQExpBufferChar(result, ',');
15362                 appendPQExpBufferStr(result, "\n    ");
15363
15364                 appendPQExpBuffer(result, "NULL::%s", tbinfo->atttypnames[j]);
15365
15366                 /*
15367                  * Must add collation if not default for the type, because CREATE OR
15368                  * REPLACE VIEW won't change it
15369                  */
15370                 if (OidIsValid(tbinfo->attcollation[j]))
15371                 {
15372                         CollInfo   *coll;
15373
15374                         coll = findCollationByOid(tbinfo->attcollation[j]);
15375                         if (coll)
15376                                 appendPQExpBuffer(result, " COLLATE %s",
15377                                                                   fmtQualifiedDumpable(coll));
15378                 }
15379
15380                 appendPQExpBuffer(result, " AS %s", fmtId(tbinfo->attnames[j]));
15381         }
15382
15383         return result;
15384 }
15385
15386 /*
15387  * dumpTableSchema
15388  *        write the declaration (not data) of one user-defined table or view
15389  */
15390 static void
15391 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
15392 {
15393         DumpOptions *dopt = fout->dopt;
15394         PQExpBuffer q = createPQExpBuffer();
15395         PQExpBuffer delq = createPQExpBuffer();
15396         char       *qrelname;
15397         char       *qualrelname;
15398         int                     numParents;
15399         TableInfo **parents;
15400         int                     actual_atts;    /* number of attrs in this CREATE statement */
15401         const char *reltypename;
15402         char       *storage;
15403         char       *srvname;
15404         char       *ftoptions;
15405         int                     j,
15406                                 k;
15407
15408         qrelname = pg_strdup(fmtId(tbinfo->dobj.name));
15409         qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
15410
15411         if (dopt->binary_upgrade)
15412                 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
15413                                                                                                 tbinfo->dobj.catId.oid);
15414
15415         /* Is it a table or a view? */
15416         if (tbinfo->relkind == RELKIND_VIEW)
15417         {
15418                 PQExpBuffer result;
15419
15420                 /*
15421                  * Note: keep this code in sync with the is_view case in dumpRule()
15422                  */
15423
15424                 reltypename = "VIEW";
15425
15426                 appendPQExpBuffer(delq, "DROP VIEW %s;\n", qualrelname);
15427
15428                 if (dopt->binary_upgrade)
15429                         binary_upgrade_set_pg_class_oids(fout, q,
15430                                                                                          tbinfo->dobj.catId.oid, false);
15431
15432                 appendPQExpBuffer(q, "CREATE VIEW %s", qualrelname);
15433
15434                 if (tbinfo->dummy_view)
15435                         result = createDummyViewAsClause(fout, tbinfo);
15436                 else
15437                 {
15438                         if (nonemptyReloptions(tbinfo->reloptions))
15439                         {
15440                                 appendPQExpBufferStr(q, " WITH (");
15441                                 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15442                                 appendPQExpBufferChar(q, ')');
15443                         }
15444                         result = createViewAsClause(fout, tbinfo);
15445                 }
15446                 appendPQExpBuffer(q, " AS\n%s", result->data);
15447                 destroyPQExpBuffer(result);
15448
15449                 if (tbinfo->checkoption != NULL && !tbinfo->dummy_view)
15450                         appendPQExpBuffer(q, "\n  WITH %s CHECK OPTION", tbinfo->checkoption);
15451                 appendPQExpBufferStr(q, ";\n");
15452         }
15453         else
15454         {
15455                 switch (tbinfo->relkind)
15456                 {
15457                         case RELKIND_FOREIGN_TABLE:
15458                                 {
15459                                         PQExpBuffer query = createPQExpBuffer();
15460                                         PGresult   *res;
15461                                         int                     i_srvname;
15462                                         int                     i_ftoptions;
15463
15464                                         reltypename = "FOREIGN TABLE";
15465
15466                                         /* retrieve name of foreign server and generic options */
15467                                         appendPQExpBuffer(query,
15468                                                                           "SELECT fs.srvname, "
15469                                                                           "pg_catalog.array_to_string(ARRAY("
15470                                                                           "SELECT pg_catalog.quote_ident(option_name) || "
15471                                                                           "' ' || pg_catalog.quote_literal(option_value) "
15472                                                                           "FROM pg_catalog.pg_options_to_table(ftoptions) "
15473                                                                           "ORDER BY option_name"
15474                                                                           "), E',\n    ') AS ftoptions "
15475                                                                           "FROM pg_catalog.pg_foreign_table ft "
15476                                                                           "JOIN pg_catalog.pg_foreign_server fs "
15477                                                                           "ON (fs.oid = ft.ftserver) "
15478                                                                           "WHERE ft.ftrelid = '%u'",
15479                                                                           tbinfo->dobj.catId.oid);
15480                                         res = ExecuteSqlQueryForSingleRow(fout, query->data);
15481                                         i_srvname = PQfnumber(res, "srvname");
15482                                         i_ftoptions = PQfnumber(res, "ftoptions");
15483                                         srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
15484                                         ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
15485                                         PQclear(res);
15486                                         destroyPQExpBuffer(query);
15487                                         break;
15488                                 }
15489                         case RELKIND_MATVIEW:
15490                                 reltypename = "MATERIALIZED VIEW";
15491                                 srvname = NULL;
15492                                 ftoptions = NULL;
15493                                 break;
15494                         default:
15495                                 reltypename = "TABLE";
15496                                 srvname = NULL;
15497                                 ftoptions = NULL;
15498                 }
15499
15500                 numParents = tbinfo->numParents;
15501                 parents = tbinfo->parents;
15502
15503                 appendPQExpBuffer(delq, "DROP %s %s;\n", reltypename, qualrelname);
15504
15505                 if (dopt->binary_upgrade)
15506                         binary_upgrade_set_pg_class_oids(fout, q,
15507                                                                                          tbinfo->dobj.catId.oid, false);
15508
15509                 appendPQExpBuffer(q, "CREATE %s%s %s",
15510                                                   tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
15511                                                   "UNLOGGED " : "",
15512                                                   reltypename,
15513                                                   qualrelname);
15514
15515                 /*
15516                  * Attach to type, if reloftype; except in case of a binary upgrade,
15517                  * we dump the table normally and attach it to the type afterward.
15518                  */
15519                 if (tbinfo->reloftype && !dopt->binary_upgrade)
15520                         appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
15521
15522                 /*
15523                  * If the table is a partition, dump it as such; except in the case of
15524                  * a binary upgrade, we dump the table normally and attach it to the
15525                  * parent afterward.
15526                  */
15527                 if (tbinfo->ispartition && !dopt->binary_upgrade)
15528                 {
15529                         TableInfo  *parentRel = tbinfo->parents[0];
15530
15531                         /*
15532                          * With partitions, unlike inheritance, there can only be one
15533                          * parent.
15534                          */
15535                         if (tbinfo->numParents != 1)
15536                                 exit_horribly(NULL, "invalid number of parents %d for table \"%s\"\n",
15537                                                           tbinfo->numParents, tbinfo->dobj.name);
15538
15539                         appendPQExpBuffer(q, " PARTITION OF %s",
15540                                                           fmtQualifiedDumpable(parentRel));
15541                 }
15542
15543                 if (tbinfo->relkind != RELKIND_MATVIEW)
15544                 {
15545                         /* Dump the attributes */
15546                         actual_atts = 0;
15547                         for (j = 0; j < tbinfo->numatts; j++)
15548                         {
15549                                 /*
15550                                  * Normally, dump if it's locally defined in this table, and
15551                                  * not dropped.  But for binary upgrade, we'll dump all the
15552                                  * columns, and then fix up the dropped and nonlocal cases
15553                                  * below.
15554                                  */
15555                                 if (shouldPrintColumn(dopt, tbinfo, j))
15556                                 {
15557                                         /*
15558                                          * Default value --- suppress if to be printed separately.
15559                                          */
15560                                         bool            has_default = (tbinfo->attrdefs[j] != NULL &&
15561                                                                                            !tbinfo->attrdefs[j]->separate);
15562
15563                                         /*
15564                                          * Not Null constraint --- suppress if inherited, except
15565                                          * in binary-upgrade case where that won't work.
15566                                          */
15567                                         bool            has_notnull = (tbinfo->notnull[j] &&
15568                                                                                            (!tbinfo->inhNotNull[j] ||
15569                                                                                                 dopt->binary_upgrade));
15570
15571                                         /*
15572                                          * Skip column if fully defined by reloftype or the
15573                                          * partition parent.
15574                                          */
15575                                         if ((tbinfo->reloftype || tbinfo->ispartition) &&
15576                                                 !has_default && !has_notnull && !dopt->binary_upgrade)
15577                                                 continue;
15578
15579                                         /* Format properly if not first attr */
15580                                         if (actual_atts == 0)
15581                                                 appendPQExpBufferStr(q, " (");
15582                                         else
15583                                                 appendPQExpBufferChar(q, ',');
15584                                         appendPQExpBufferStr(q, "\n    ");
15585                                         actual_atts++;
15586
15587                                         /* Attribute name */
15588                                         appendPQExpBufferStr(q, fmtId(tbinfo->attnames[j]));
15589
15590                                         if (tbinfo->attisdropped[j])
15591                                         {
15592                                                 /*
15593                                                  * ALTER TABLE DROP COLUMN clears
15594                                                  * pg_attribute.atttypid, so we will not have gotten a
15595                                                  * valid type name; insert INTEGER as a stopgap. We'll
15596                                                  * clean things up later.
15597                                                  */
15598                                                 appendPQExpBufferStr(q, " INTEGER /* dummy */");
15599                                                 /* Skip all the rest, too */
15600                                                 continue;
15601                                         }
15602
15603                                         /*
15604                                          * Attribute type
15605                                          *
15606                                          * In binary-upgrade mode, we always include the type. If
15607                                          * we aren't in binary-upgrade mode, then we skip the type
15608                                          * when creating a typed table ('OF type_name') or a
15609                                          * partition ('PARTITION OF'), since the type comes from
15610                                          * the parent/partitioned table.
15611                                          */
15612                                         if (dopt->binary_upgrade || (!tbinfo->reloftype && !tbinfo->ispartition))
15613                                         {
15614                                                 appendPQExpBuffer(q, " %s",
15615                                                                                   tbinfo->atttypnames[j]);
15616                                         }
15617
15618                                         /* Add collation if not default for the type */
15619                                         if (OidIsValid(tbinfo->attcollation[j]))
15620                                         {
15621                                                 CollInfo   *coll;
15622
15623                                                 coll = findCollationByOid(tbinfo->attcollation[j]);
15624                                                 if (coll)
15625                                                         appendPQExpBuffer(q, " COLLATE %s",
15626                                                                                           fmtQualifiedDumpable(coll));
15627                                         }
15628
15629                                         if (has_default)
15630                                                 appendPQExpBuffer(q, " DEFAULT %s",
15631                                                                                   tbinfo->attrdefs[j]->adef_expr);
15632
15633                                         if (has_notnull)
15634                                                 appendPQExpBufferStr(q, " NOT NULL");
15635                                 }
15636                         }
15637
15638                         /*
15639                          * Add non-inherited CHECK constraints, if any.
15640                          */
15641                         for (j = 0; j < tbinfo->ncheck; j++)
15642                         {
15643                                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
15644
15645                                 if (constr->separate || !constr->conislocal)
15646                                         continue;
15647
15648                                 if (actual_atts == 0)
15649                                         appendPQExpBufferStr(q, " (\n    ");
15650                                 else
15651                                         appendPQExpBufferStr(q, ",\n    ");
15652
15653                                 appendPQExpBuffer(q, "CONSTRAINT %s ",
15654                                                                   fmtId(constr->dobj.name));
15655                                 appendPQExpBufferStr(q, constr->condef);
15656
15657                                 actual_atts++;
15658                         }
15659
15660                         if (actual_atts)
15661                                 appendPQExpBufferStr(q, "\n)");
15662                         else if (!((tbinfo->reloftype || tbinfo->ispartition) &&
15663                                            !dopt->binary_upgrade))
15664                         {
15665                                 /*
15666                                  * We must have a parenthesized attribute list, even though
15667                                  * empty, when not using the OF TYPE or PARTITION OF syntax.
15668                                  */
15669                                 appendPQExpBufferStr(q, " (\n)");
15670                         }
15671
15672                         if (tbinfo->ispartition && !dopt->binary_upgrade)
15673                         {
15674                                 appendPQExpBufferChar(q, '\n');
15675                                 appendPQExpBufferStr(q, tbinfo->partbound);
15676                         }
15677
15678                         /* Emit the INHERITS clause, except if this is a partition. */
15679                         if (numParents > 0 &&
15680                                 !tbinfo->ispartition &&
15681                                 !dopt->binary_upgrade)
15682                         {
15683                                 appendPQExpBufferStr(q, "\nINHERITS (");
15684                                 for (k = 0; k < numParents; k++)
15685                                 {
15686                                         TableInfo  *parentRel = parents[k];
15687
15688                                         if (k > 0)
15689                                                 appendPQExpBufferStr(q, ", ");
15690                                         appendPQExpBufferStr(q, fmtQualifiedDumpable(parentRel));
15691                                 }
15692                                 appendPQExpBufferChar(q, ')');
15693                         }
15694
15695                         if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15696                                 appendPQExpBuffer(q, "\nPARTITION BY %s", tbinfo->partkeydef);
15697
15698                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
15699                                 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
15700                 }
15701
15702                 if (nonemptyReloptions(tbinfo->reloptions) ||
15703                         nonemptyReloptions(tbinfo->toast_reloptions))
15704                 {
15705                         bool            addcomma = false;
15706
15707                         appendPQExpBufferStr(q, "\nWITH (");
15708                         if (nonemptyReloptions(tbinfo->reloptions))
15709                         {
15710                                 addcomma = true;
15711                                 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15712                         }
15713                         if (nonemptyReloptions(tbinfo->toast_reloptions))
15714                         {
15715                                 if (addcomma)
15716                                         appendPQExpBufferStr(q, ", ");
15717                                 appendReloptionsArrayAH(q, tbinfo->toast_reloptions, "toast.",
15718                                                                                 fout);
15719                         }
15720                         appendPQExpBufferChar(q, ')');
15721                 }
15722
15723                 /* Dump generic options if any */
15724                 if (ftoptions && ftoptions[0])
15725                         appendPQExpBuffer(q, "\nOPTIONS (\n    %s\n)", ftoptions);
15726
15727                 /*
15728                  * For materialized views, create the AS clause just like a view. At
15729                  * this point, we always mark the view as not populated.
15730                  */
15731                 if (tbinfo->relkind == RELKIND_MATVIEW)
15732                 {
15733                         PQExpBuffer result;
15734
15735                         result = createViewAsClause(fout, tbinfo);
15736                         appendPQExpBuffer(q, " AS\n%s\n  WITH NO DATA;\n",
15737                                                           result->data);
15738                         destroyPQExpBuffer(result);
15739                 }
15740                 else
15741                         appendPQExpBufferStr(q, ";\n");
15742
15743                 /*
15744                  * in binary upgrade mode, update the catalog with any missing values
15745                  * that might be present.
15746                  */
15747                 if (dopt->binary_upgrade)
15748                 {
15749                         for (j = 0; j < tbinfo->numatts; j++)
15750                         {
15751                                 if (tbinfo->attmissingval[j][0] != '\0')
15752                                 {
15753                                         appendPQExpBufferStr(q, "\n-- set missing value.\n");
15754                                         appendPQExpBufferStr(q,
15755                                                                                  "SELECT pg_catalog.binary_upgrade_set_missing_value(");
15756                                         appendStringLiteralAH(q, qualrelname, fout);
15757                                         appendPQExpBufferStr(q, "::pg_catalog.regclass,");
15758                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15759                                         appendPQExpBufferStr(q, ",");
15760                                         appendStringLiteralAH(q, tbinfo->attmissingval[j], fout);
15761                                         appendPQExpBufferStr(q, ");\n\n");
15762                                 }
15763                         }
15764                 }
15765
15766                 /*
15767                  * To create binary-compatible heap files, we have to ensure the same
15768                  * physical column order, including dropped columns, as in the
15769                  * original.  Therefore, we create dropped columns above and drop them
15770                  * here, also updating their attlen/attalign values so that the
15771                  * dropped column can be skipped properly.  (We do not bother with
15772                  * restoring the original attbyval setting.)  Also, inheritance
15773                  * relationships are set up by doing ALTER TABLE INHERIT rather than
15774                  * using an INHERITS clause --- the latter would possibly mess up the
15775                  * column order.  That also means we have to take care about setting
15776                  * attislocal correctly, plus fix up any inherited CHECK constraints.
15777                  * Analogously, we set up typed tables using ALTER TABLE / OF here.
15778                  *
15779                  * We process foreign and partitioned tables here, even though they
15780                  * lack heap storage, because they can participate in inheritance
15781                  * relationships and we want this stuff to be consistent across the
15782                  * inheritance tree.  We can exclude indexes, toast tables, sequences
15783                  * and matviews, even though they have storage, because we don't
15784                  * support altering or dropping columns in them, nor can they be part
15785                  * of inheritance trees.
15786                  */
15787                 if (dopt->binary_upgrade &&
15788                         (tbinfo->relkind == RELKIND_RELATION ||
15789                          tbinfo->relkind == RELKIND_FOREIGN_TABLE ||
15790                          tbinfo->relkind == RELKIND_PARTITIONED_TABLE))
15791                 {
15792                         for (j = 0; j < tbinfo->numatts; j++)
15793                         {
15794                                 if (tbinfo->attisdropped[j])
15795                                 {
15796                                         appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate dropped column.\n");
15797                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
15798                                                                           "SET attlen = %d, "
15799                                                                           "attalign = '%c', attbyval = false\n"
15800                                                                           "WHERE attname = ",
15801                                                                           tbinfo->attlen[j],
15802                                                                           tbinfo->attalign[j]);
15803                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15804                                         appendPQExpBufferStr(q, "\n  AND attrelid = ");
15805                                         appendStringLiteralAH(q, qualrelname, fout);
15806                                         appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15807
15808                                         if (tbinfo->relkind == RELKIND_RELATION ||
15809                                                 tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15810                                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15811                                                                                   qualrelname);
15812                                         else
15813                                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE ONLY %s ",
15814                                                                                   qualrelname);
15815                                         appendPQExpBuffer(q, "DROP COLUMN %s;\n",
15816                                                                           fmtId(tbinfo->attnames[j]));
15817                                 }
15818                                 else if (!tbinfo->attislocal[j])
15819                                 {
15820                                         appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate inherited column.\n");
15821                                         appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_attribute\n"
15822                                                                                  "SET attislocal = false\n"
15823                                                                                  "WHERE attname = ");
15824                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15825                                         appendPQExpBufferStr(q, "\n  AND attrelid = ");
15826                                         appendStringLiteralAH(q, qualrelname, fout);
15827                                         appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15828                                 }
15829                         }
15830
15831                         for (k = 0; k < tbinfo->ncheck; k++)
15832                         {
15833                                 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
15834
15835                                 if (constr->separate || constr->conislocal)
15836                                         continue;
15837
15838                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inherited constraint.\n");
15839                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15840                                                                   qualrelname);
15841                                 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
15842                                                                   fmtId(constr->dobj.name));
15843                                 appendPQExpBuffer(q, "%s;\n", constr->condef);
15844                                 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_constraint\n"
15845                                                                          "SET conislocal = false\n"
15846                                                                          "WHERE contype = 'c' AND conname = ");
15847                                 appendStringLiteralAH(q, constr->dobj.name, fout);
15848                                 appendPQExpBufferStr(q, "\n  AND conrelid = ");
15849                                 appendStringLiteralAH(q, qualrelname, fout);
15850                                 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15851                         }
15852
15853                         if (numParents > 0)
15854                         {
15855                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inheritance and partitioning this way.\n");
15856                                 for (k = 0; k < numParents; k++)
15857                                 {
15858                                         TableInfo  *parentRel = parents[k];
15859
15860                                         /* In the partitioning case, we alter the parent */
15861                                         if (tbinfo->ispartition)
15862                                                 appendPQExpBuffer(q,
15863                                                                                   "ALTER TABLE ONLY %s ATTACH PARTITION ",
15864                                                                                   fmtQualifiedDumpable(parentRel));
15865                                         else
15866                                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
15867                                                                                   qualrelname);
15868
15869                                         /* Partition needs specifying the bounds */
15870                                         if (tbinfo->ispartition)
15871                                                 appendPQExpBuffer(q, "%s %s;\n",
15872                                                                                   qualrelname,
15873                                                                                   tbinfo->partbound);
15874                                         else
15875                                                 appendPQExpBuffer(q, "%s;\n",
15876                                                                                   fmtQualifiedDumpable(parentRel));
15877                                 }
15878                         }
15879
15880                         if (tbinfo->reloftype)
15881                         {
15882                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up typed tables this way.\n");
15883                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
15884                                                                   qualrelname,
15885                                                                   tbinfo->reloftype);
15886                         }
15887                 }
15888
15889                 /*
15890                  * In binary_upgrade mode, arrange to restore the old relfrozenxid and
15891                  * relminmxid of all vacuumable relations.  (While vacuum.c processes
15892                  * TOAST tables semi-independently, here we see them only as children
15893                  * of other relations; so this "if" lacks RELKIND_TOASTVALUE, and the
15894                  * child toast table is handled below.)
15895                  */
15896                 if (dopt->binary_upgrade &&
15897                         (tbinfo->relkind == RELKIND_RELATION ||
15898                          tbinfo->relkind == RELKIND_MATVIEW))
15899                 {
15900                         appendPQExpBufferStr(q, "\n-- For binary upgrade, set heap's relfrozenxid and relminmxid\n");
15901                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
15902                                                           "SET relfrozenxid = '%u', relminmxid = '%u'\n"
15903                                                           "WHERE oid = ",
15904                                                           tbinfo->frozenxid, tbinfo->minmxid);
15905                         appendStringLiteralAH(q, qualrelname, fout);
15906                         appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15907
15908                         if (tbinfo->toast_oid)
15909                         {
15910                                 /*
15911                                  * The toast table will have the same OID at restore, so we
15912                                  * can safely target it by OID.
15913                                  */
15914                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, set toast's relfrozenxid and relminmxid\n");
15915                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
15916                                                                   "SET relfrozenxid = '%u', relminmxid = '%u'\n"
15917                                                                   "WHERE oid = '%u';\n",
15918                                                                   tbinfo->toast_frozenxid,
15919                                                                   tbinfo->toast_minmxid, tbinfo->toast_oid);
15920                         }
15921                 }
15922
15923                 /*
15924                  * In binary_upgrade mode, restore matviews' populated status by
15925                  * poking pg_class directly.  This is pretty ugly, but we can't use
15926                  * REFRESH MATERIALIZED VIEW since it's possible that some underlying
15927                  * matview is not populated even though this matview is; in any case,
15928                  * we want to transfer the matview's heap storage, not run REFRESH.
15929                  */
15930                 if (dopt->binary_upgrade && tbinfo->relkind == RELKIND_MATVIEW &&
15931                         tbinfo->relispopulated)
15932                 {
15933                         appendPQExpBufferStr(q, "\n-- For binary upgrade, mark materialized view as populated\n");
15934                         appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_class\n"
15935                                                                  "SET relispopulated = 't'\n"
15936                                                                  "WHERE oid = ");
15937                         appendStringLiteralAH(q, qualrelname, fout);
15938                         appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15939                 }
15940
15941                 /*
15942                  * Dump additional per-column properties that we can't handle in the
15943                  * main CREATE TABLE command.
15944                  */
15945                 for (j = 0; j < tbinfo->numatts; j++)
15946                 {
15947                         /* None of this applies to dropped columns */
15948                         if (tbinfo->attisdropped[j])
15949                                 continue;
15950
15951                         /*
15952                          * If we didn't dump the column definition explicitly above, and
15953                          * it is NOT NULL and did not inherit that property from a parent,
15954                          * we have to mark it separately.
15955                          */
15956                         if (!shouldPrintColumn(dopt, tbinfo, j) &&
15957                                 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
15958                         {
15959                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15960                                                                   qualrelname);
15961                                 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
15962                                                                   fmtId(tbinfo->attnames[j]));
15963                         }
15964
15965                         /*
15966                          * Dump per-column statistics information. We only issue an ALTER
15967                          * TABLE statement if the attstattarget entry for this column is
15968                          * non-negative (i.e. it's not the default value)
15969                          */
15970                         if (tbinfo->attstattarget[j] >= 0)
15971                         {
15972                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15973                                                                   qualrelname);
15974                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15975                                                                   fmtId(tbinfo->attnames[j]));
15976                                 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
15977                                                                   tbinfo->attstattarget[j]);
15978                         }
15979
15980                         /*
15981                          * Dump per-column storage information.  The statement is only
15982                          * dumped if the storage has been changed from the type's default.
15983                          */
15984                         if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
15985                         {
15986                                 switch (tbinfo->attstorage[j])
15987                                 {
15988                                         case 'p':
15989                                                 storage = "PLAIN";
15990                                                 break;
15991                                         case 'e':
15992                                                 storage = "EXTERNAL";
15993                                                 break;
15994                                         case 'm':
15995                                                 storage = "MAIN";
15996                                                 break;
15997                                         case 'x':
15998                                                 storage = "EXTENDED";
15999                                                 break;
16000                                         default:
16001                                                 storage = NULL;
16002                                 }
16003
16004                                 /*
16005                                  * Only dump the statement if it's a storage type we recognize
16006                                  */
16007                                 if (storage != NULL)
16008                                 {
16009                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16010                                                                           qualrelname);
16011                                         appendPQExpBuffer(q, "ALTER COLUMN %s ",
16012                                                                           fmtId(tbinfo->attnames[j]));
16013                                         appendPQExpBuffer(q, "SET STORAGE %s;\n",
16014                                                                           storage);
16015                                 }
16016                         }
16017
16018                         /*
16019                          * Dump per-column attributes.
16020                          */
16021                         if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
16022                         {
16023                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16024                                                                   qualrelname);
16025                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16026                                                                   fmtId(tbinfo->attnames[j]));
16027                                 appendPQExpBuffer(q, "SET (%s);\n",
16028                                                                   tbinfo->attoptions[j]);
16029                         }
16030
16031                         /*
16032                          * Dump per-column fdw options.
16033                          */
16034                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
16035                                 tbinfo->attfdwoptions[j] &&
16036                                 tbinfo->attfdwoptions[j][0] != '\0')
16037                         {
16038                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
16039                                                                   qualrelname);
16040                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
16041                                                                   fmtId(tbinfo->attnames[j]));
16042                                 appendPQExpBuffer(q, "OPTIONS (\n    %s\n);\n",
16043                                                                   tbinfo->attfdwoptions[j]);
16044                         }
16045                 }
16046         }
16047
16048         /*
16049          * dump properties we only have ALTER TABLE syntax for
16050          */
16051         if ((tbinfo->relkind == RELKIND_RELATION ||
16052                  tbinfo->relkind == RELKIND_PARTITIONED_TABLE ||
16053                  tbinfo->relkind == RELKIND_MATVIEW) &&
16054                 tbinfo->relreplident != REPLICA_IDENTITY_DEFAULT)
16055         {
16056                 if (tbinfo->relreplident == REPLICA_IDENTITY_INDEX)
16057                 {
16058                         /* nothing to do, will be set when the index is dumped */
16059                 }
16060                 else if (tbinfo->relreplident == REPLICA_IDENTITY_NOTHING)
16061                 {
16062                         appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY NOTHING;\n",
16063                                                           qualrelname);
16064                 }
16065                 else if (tbinfo->relreplident == REPLICA_IDENTITY_FULL)
16066                 {
16067                         appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY FULL;\n",
16068                                                           qualrelname);
16069                 }
16070         }
16071
16072         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE && tbinfo->hasoids)
16073                 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s SET WITH OIDS;\n",
16074                                                   qualrelname);
16075
16076         if (tbinfo->forcerowsec)
16077                 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s FORCE ROW LEVEL SECURITY;\n",
16078                                                   qualrelname);
16079
16080         if (dopt->binary_upgrade)
16081                 binary_upgrade_extension_member(q, &tbinfo->dobj,
16082                                                                                 reltypename, qrelname,
16083                                                                                 tbinfo->dobj.namespace->dobj.name);
16084
16085         if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16086                 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
16087                                          tbinfo->dobj.name,
16088                                          tbinfo->dobj.namespace->dobj.name,
16089                                          (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
16090                                          tbinfo->rolname,
16091                                          (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
16092                                          reltypename,
16093                                          tbinfo->postponed_def ?
16094                                          SECTION_POST_DATA : SECTION_PRE_DATA,
16095                                          q->data, delq->data, NULL,
16096                                          NULL, 0,
16097                                          NULL, NULL);
16098
16099
16100         /* Dump Table Comments */
16101         if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16102                 dumpTableComment(fout, tbinfo, reltypename);
16103
16104         /* Dump Table Security Labels */
16105         if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16106                 dumpTableSecLabel(fout, tbinfo, reltypename);
16107
16108         /* Dump comments on inlined table constraints */
16109         for (j = 0; j < tbinfo->ncheck; j++)
16110         {
16111                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
16112
16113                 if (constr->separate || !constr->conislocal)
16114                         continue;
16115
16116                 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16117                         dumpTableConstraintComment(fout, constr);
16118         }
16119
16120         destroyPQExpBuffer(q);
16121         destroyPQExpBuffer(delq);
16122         free(qrelname);
16123         free(qualrelname);
16124 }
16125
16126 /*
16127  * dumpAttrDef --- dump an attribute's default-value declaration
16128  */
16129 static void
16130 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
16131 {
16132         DumpOptions *dopt = fout->dopt;
16133         TableInfo  *tbinfo = adinfo->adtable;
16134         int                     adnum = adinfo->adnum;
16135         PQExpBuffer q;
16136         PQExpBuffer delq;
16137         char       *qualrelname;
16138         char       *tag;
16139
16140         /* Skip if table definition not to be dumped */
16141         if (!tbinfo->dobj.dump || dopt->dataOnly)
16142                 return;
16143
16144         /* Skip if not "separate"; it was dumped in the table's definition */
16145         if (!adinfo->separate)
16146                 return;
16147
16148         q = createPQExpBuffer();
16149         delq = createPQExpBuffer();
16150
16151         qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
16152
16153         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
16154                                           qualrelname);
16155         appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
16156                                           fmtId(tbinfo->attnames[adnum - 1]),
16157                                           adinfo->adef_expr);
16158
16159         appendPQExpBuffer(delq, "ALTER TABLE %s ",
16160                                           qualrelname);
16161         appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
16162                                           fmtId(tbinfo->attnames[adnum - 1]));
16163
16164         tag = psprintf("%s %s", tbinfo->dobj.name, tbinfo->attnames[adnum - 1]);
16165
16166         if (adinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16167                 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
16168                                          tag,
16169                                          tbinfo->dobj.namespace->dobj.name,
16170                                          NULL,
16171                                          tbinfo->rolname,
16172                                          false, "DEFAULT", SECTION_PRE_DATA,
16173                                          q->data, delq->data, NULL,
16174                                          NULL, 0,
16175                                          NULL, NULL);
16176
16177         free(tag);
16178         destroyPQExpBuffer(q);
16179         destroyPQExpBuffer(delq);
16180         free(qualrelname);
16181 }
16182
16183 /*
16184  * getAttrName: extract the correct name for an attribute
16185  *
16186  * The array tblInfo->attnames[] only provides names of user attributes;
16187  * if a system attribute number is supplied, we have to fake it.
16188  * We also do a little bit of bounds checking for safety's sake.
16189  */
16190 static const char *
16191 getAttrName(int attrnum, TableInfo *tblInfo)
16192 {
16193         if (attrnum > 0 && attrnum <= tblInfo->numatts)
16194                 return tblInfo->attnames[attrnum - 1];
16195         switch (attrnum)
16196         {
16197                 case SelfItemPointerAttributeNumber:
16198                         return "ctid";
16199                 case ObjectIdAttributeNumber:
16200                         return "oid";
16201                 case MinTransactionIdAttributeNumber:
16202                         return "xmin";
16203                 case MinCommandIdAttributeNumber:
16204                         return "cmin";
16205                 case MaxTransactionIdAttributeNumber:
16206                         return "xmax";
16207                 case MaxCommandIdAttributeNumber:
16208                         return "cmax";
16209                 case TableOidAttributeNumber:
16210                         return "tableoid";
16211         }
16212         exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
16213                                   attrnum, tblInfo->dobj.name);
16214         return NULL;                            /* keep compiler quiet */
16215 }
16216
16217 /*
16218  * dumpIndex
16219  *        write out to fout a user-defined index
16220  */
16221 static void
16222 dumpIndex(Archive *fout, IndxInfo *indxinfo)
16223 {
16224         DumpOptions *dopt = fout->dopt;
16225         TableInfo  *tbinfo = indxinfo->indextable;
16226         bool            is_constraint = (indxinfo->indexconstraint != 0);
16227         PQExpBuffer q;
16228         PQExpBuffer delq;
16229         char       *qindxname;
16230
16231         if (dopt->dataOnly)
16232                 return;
16233
16234         q = createPQExpBuffer();
16235         delq = createPQExpBuffer();
16236
16237         qindxname = pg_strdup(fmtId(indxinfo->dobj.name));
16238
16239         /*
16240          * If there's an associated constraint, don't dump the index per se, but
16241          * do dump any comment for it.  (This is safe because dependency ordering
16242          * will have ensured the constraint is emitted first.)  Note that the
16243          * emitted comment has to be shown as depending on the constraint, not the
16244          * index, in such cases.
16245          */
16246         if (!is_constraint)
16247         {
16248                 if (dopt->binary_upgrade)
16249                         binary_upgrade_set_pg_class_oids(fout, q,
16250                                                                                          indxinfo->dobj.catId.oid, true);
16251
16252                 /* Plain secondary index */
16253                 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
16254
16255                 /*
16256                  * Append ALTER TABLE commands as needed to set properties that we
16257                  * only have ALTER TABLE syntax for.  Keep this in sync with the
16258                  * similar code in dumpConstraint!
16259                  */
16260
16261                 /* If the index is clustered, we need to record that. */
16262                 if (indxinfo->indisclustered)
16263                 {
16264                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16265                                                           fmtQualifiedDumpable(tbinfo));
16266                         /* index name is not qualified in this syntax */
16267                         appendPQExpBuffer(q, " ON %s;\n",
16268                                                           qindxname);
16269                 }
16270
16271                 /* If the index defines identity, we need to record that. */
16272                 if (indxinfo->indisreplident)
16273                 {
16274                         appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
16275                                                           fmtQualifiedDumpable(tbinfo));
16276                         /* index name is not qualified in this syntax */
16277                         appendPQExpBuffer(q, " INDEX %s;\n",
16278                                                           qindxname);
16279                 }
16280
16281                 appendPQExpBuffer(delq, "DROP INDEX %s;\n",
16282                                                   fmtQualifiedDumpable(indxinfo));
16283
16284                 if (indxinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16285                         ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
16286                                                  indxinfo->dobj.name,
16287                                                  tbinfo->dobj.namespace->dobj.name,
16288                                                  indxinfo->tablespace,
16289                                                  tbinfo->rolname, false,
16290                                                  "INDEX", SECTION_POST_DATA,
16291                                                  q->data, delq->data, NULL,
16292                                                  NULL, 0,
16293                                                  NULL, NULL);
16294         }
16295
16296         /* Dump Index Comments */
16297         if (indxinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16298                 dumpComment(fout, "INDEX", qindxname,
16299                                         tbinfo->dobj.namespace->dobj.name,
16300                                         tbinfo->rolname,
16301                                         indxinfo->dobj.catId, 0,
16302                                         is_constraint ? indxinfo->indexconstraint :
16303                                         indxinfo->dobj.dumpId);
16304
16305         destroyPQExpBuffer(q);
16306         destroyPQExpBuffer(delq);
16307         free(qindxname);
16308 }
16309
16310 /*
16311  * dumpIndexAttach
16312  *        write out to fout a partitioned-index attachment clause
16313  */
16314 static void
16315 dumpIndexAttach(Archive *fout, IndexAttachInfo *attachinfo)
16316 {
16317         if (fout->dopt->dataOnly)
16318                 return;
16319
16320         if (attachinfo->partitionIdx->dobj.dump & DUMP_COMPONENT_DEFINITION)
16321         {
16322                 PQExpBuffer q = createPQExpBuffer();
16323
16324                 appendPQExpBuffer(q, "\nALTER INDEX %s ",
16325                                                   fmtQualifiedDumpable(attachinfo->parentIdx));
16326                 appendPQExpBuffer(q, "ATTACH PARTITION %s;\n",
16327                                                   fmtQualifiedDumpable(attachinfo->partitionIdx));
16328
16329                 ArchiveEntry(fout, attachinfo->dobj.catId, attachinfo->dobj.dumpId,
16330                                          attachinfo->dobj.name,
16331                                          NULL, NULL,
16332                                          "",
16333                                          false, "INDEX ATTACH", SECTION_POST_DATA,
16334                                          q->data, "", NULL,
16335                                          NULL, 0,
16336                                          NULL, NULL);
16337
16338                 destroyPQExpBuffer(q);
16339         }
16340 }
16341
16342 /*
16343  * dumpStatisticsExt
16344  *        write out to fout an extended statistics object
16345  */
16346 static void
16347 dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo)
16348 {
16349         DumpOptions *dopt = fout->dopt;
16350         PQExpBuffer q;
16351         PQExpBuffer delq;
16352         PQExpBuffer query;
16353         char       *qstatsextname;
16354         PGresult   *res;
16355         char       *stxdef;
16356
16357         /* Skip if not to be dumped */
16358         if (!statsextinfo->dobj.dump || dopt->dataOnly)
16359                 return;
16360
16361         q = createPQExpBuffer();
16362         delq = createPQExpBuffer();
16363         query = createPQExpBuffer();
16364
16365         qstatsextname = pg_strdup(fmtId(statsextinfo->dobj.name));
16366
16367         appendPQExpBuffer(query, "SELECT "
16368                                           "pg_catalog.pg_get_statisticsobjdef('%u'::pg_catalog.oid)",
16369                                           statsextinfo->dobj.catId.oid);
16370
16371         res = ExecuteSqlQueryForSingleRow(fout, query->data);
16372
16373         stxdef = PQgetvalue(res, 0, 0);
16374
16375         /* Result of pg_get_statisticsobjdef is complete except for semicolon */
16376         appendPQExpBuffer(q, "%s;\n", stxdef);
16377
16378         appendPQExpBuffer(delq, "DROP STATISTICS %s;\n",
16379                                           fmtQualifiedDumpable(statsextinfo));
16380
16381         if (statsextinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16382                 ArchiveEntry(fout, statsextinfo->dobj.catId,
16383                                          statsextinfo->dobj.dumpId,
16384                                          statsextinfo->dobj.name,
16385                                          statsextinfo->dobj.namespace->dobj.name,
16386                                          NULL,
16387                                          statsextinfo->rolname, false,
16388                                          "STATISTICS", SECTION_POST_DATA,
16389                                          q->data, delq->data, NULL,
16390                                          NULL, 0,
16391                                          NULL, NULL);
16392
16393         /* Dump Statistics Comments */
16394         if (statsextinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16395                 dumpComment(fout, "STATISTICS", qstatsextname,
16396                                         statsextinfo->dobj.namespace->dobj.name,
16397                                         statsextinfo->rolname,
16398                                         statsextinfo->dobj.catId, 0,
16399                                         statsextinfo->dobj.dumpId);
16400
16401         PQclear(res);
16402         destroyPQExpBuffer(q);
16403         destroyPQExpBuffer(delq);
16404         destroyPQExpBuffer(query);
16405         free(qstatsextname);
16406 }
16407
16408 /*
16409  * dumpConstraint
16410  *        write out to fout a user-defined constraint
16411  */
16412 static void
16413 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
16414 {
16415         DumpOptions *dopt = fout->dopt;
16416         TableInfo  *tbinfo = coninfo->contable;
16417         PQExpBuffer q;
16418         PQExpBuffer delq;
16419         char       *tag = NULL;
16420
16421         /* Skip if not to be dumped */
16422         if (!coninfo->dobj.dump || dopt->dataOnly)
16423                 return;
16424
16425         q = createPQExpBuffer();
16426         delq = createPQExpBuffer();
16427
16428         if (coninfo->contype == 'p' ||
16429                 coninfo->contype == 'u' ||
16430                 coninfo->contype == 'x')
16431         {
16432                 /* Index-related constraint */
16433                 IndxInfo   *indxinfo;
16434                 int                     k;
16435
16436                 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
16437
16438                 if (indxinfo == NULL)
16439                         exit_horribly(NULL, "missing index for constraint \"%s\"\n",
16440                                                   coninfo->dobj.name);
16441
16442                 if (dopt->binary_upgrade)
16443                         binary_upgrade_set_pg_class_oids(fout, q,
16444                                                                                          indxinfo->dobj.catId.oid, true);
16445
16446                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
16447                                                   fmtQualifiedDumpable(tbinfo));
16448                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s ",
16449                                                   fmtId(coninfo->dobj.name));
16450
16451                 if (coninfo->condef)
16452                 {
16453                         /* pg_get_constraintdef should have provided everything */
16454                         appendPQExpBuffer(q, "%s;\n", coninfo->condef);
16455                 }
16456                 else
16457                 {
16458                         appendPQExpBuffer(q, "%s (",
16459                                                           coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
16460                         for (k = 0; k < indxinfo->indnkeyattrs; k++)
16461                         {
16462                                 int                     indkey = (int) indxinfo->indkeys[k];
16463                                 const char *attname;
16464
16465                                 if (indkey == InvalidAttrNumber)
16466                                         break;
16467                                 attname = getAttrName(indkey, tbinfo);
16468
16469                                 appendPQExpBuffer(q, "%s%s",
16470                                                                   (k == 0) ? "" : ", ",
16471                                                                   fmtId(attname));
16472                         }
16473
16474                         if (indxinfo->indnkeyattrs < indxinfo->indnattrs)
16475                                 appendPQExpBuffer(q, ") INCLUDE (");
16476
16477                         for (k = indxinfo->indnkeyattrs; k < indxinfo->indnattrs; k++)
16478                         {
16479                                 int                     indkey = (int) indxinfo->indkeys[k];
16480                                 const char *attname;
16481
16482                                 if (indkey == InvalidAttrNumber)
16483                                         break;
16484                                 attname = getAttrName(indkey, tbinfo);
16485
16486                                 appendPQExpBuffer(q, "%s%s",
16487                                                                   (k == indxinfo->indnkeyattrs) ? "" : ", ",
16488                                                                   fmtId(attname));
16489                         }
16490
16491                         appendPQExpBufferChar(q, ')');
16492
16493                         if (nonemptyReloptions(indxinfo->indreloptions))
16494                         {
16495                                 appendPQExpBufferStr(q, " WITH (");
16496                                 appendReloptionsArrayAH(q, indxinfo->indreloptions, "", fout);
16497                                 appendPQExpBufferChar(q, ')');
16498                         }
16499
16500                         if (coninfo->condeferrable)
16501                         {
16502                                 appendPQExpBufferStr(q, " DEFERRABLE");
16503                                 if (coninfo->condeferred)
16504                                         appendPQExpBufferStr(q, " INITIALLY DEFERRED");
16505                         }
16506
16507                         appendPQExpBufferStr(q, ";\n");
16508                 }
16509
16510                 /*
16511                  * Append ALTER TABLE commands as needed to set properties that we
16512                  * only have ALTER TABLE syntax for.  Keep this in sync with the
16513                  * similar code in dumpIndex!
16514                  */
16515
16516                 /* If the index is clustered, we need to record that. */
16517                 if (indxinfo->indisclustered)
16518                 {
16519                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16520                                                           fmtQualifiedDumpable(tbinfo));
16521                         /* index name is not qualified in this syntax */
16522                         appendPQExpBuffer(q, " ON %s;\n",
16523                                                           fmtId(indxinfo->dobj.name));
16524                 }
16525
16526                 /* If the index defines identity, we need to record that. */
16527                 if (indxinfo->indisreplident)
16528                 {
16529                         appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
16530                                                           fmtQualifiedDumpable(tbinfo));
16531                         /* index name is not qualified in this syntax */
16532                         appendPQExpBuffer(q, " INDEX %s;\n",
16533                                                           fmtId(indxinfo->dobj.name));
16534                 }
16535
16536                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s ",
16537                                                   fmtQualifiedDumpable(tbinfo));
16538                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16539                                                   fmtId(coninfo->dobj.name));
16540
16541                 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16542
16543                 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16544                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16545                                                  tag,
16546                                                  tbinfo->dobj.namespace->dobj.name,
16547                                                  indxinfo->tablespace,
16548                                                  tbinfo->rolname, false,
16549                                                  "CONSTRAINT", SECTION_POST_DATA,
16550                                                  q->data, delq->data, NULL,
16551                                                  NULL, 0,
16552                                                  NULL, NULL);
16553         }
16554         else if (coninfo->contype == 'f')
16555         {
16556                 char       *only;
16557
16558                 /*
16559                  * Foreign keys on partitioned tables are always declared as
16560                  * inheriting to partitions; for all other cases, emit them as
16561                  * applying ONLY directly to the named table, because that's how they
16562                  * work for regular inherited tables.
16563                  */
16564                 only = tbinfo->relkind == RELKIND_PARTITIONED_TABLE ? "" : "ONLY ";
16565
16566                 /*
16567                  * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
16568                  * current table data is not processed
16569                  */
16570                 appendPQExpBuffer(q, "ALTER TABLE %s%s\n",
16571                                                   only, fmtQualifiedDumpable(tbinfo));
16572                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
16573                                                   fmtId(coninfo->dobj.name),
16574                                                   coninfo->condef);
16575
16576                 appendPQExpBuffer(delq, "ALTER TABLE %s%s ",
16577                                                   only, fmtQualifiedDumpable(tbinfo));
16578                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16579                                                   fmtId(coninfo->dobj.name));
16580
16581                 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16582
16583                 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16584                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16585                                                  tag,
16586                                                  tbinfo->dobj.namespace->dobj.name,
16587                                                  NULL,
16588                                                  tbinfo->rolname, false,
16589                                                  "FK CONSTRAINT", SECTION_POST_DATA,
16590                                                  q->data, delq->data, NULL,
16591                                                  NULL, 0,
16592                                                  NULL, NULL);
16593         }
16594         else if (coninfo->contype == 'c' && tbinfo)
16595         {
16596                 /* CHECK constraint on a table */
16597
16598                 /* Ignore if not to be dumped separately, or if it was inherited */
16599                 if (coninfo->separate && coninfo->conislocal)
16600                 {
16601                         /* not ONLY since we want it to propagate to children */
16602                         appendPQExpBuffer(q, "ALTER TABLE %s\n",
16603                                                           fmtQualifiedDumpable(tbinfo));
16604                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
16605                                                           fmtId(coninfo->dobj.name),
16606                                                           coninfo->condef);
16607
16608                         appendPQExpBuffer(delq, "ALTER TABLE %s ",
16609                                                           fmtQualifiedDumpable(tbinfo));
16610                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16611                                                           fmtId(coninfo->dobj.name));
16612
16613                         tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16614
16615                         if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16616                                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16617                                                          tag,
16618                                                          tbinfo->dobj.namespace->dobj.name,
16619                                                          NULL,
16620                                                          tbinfo->rolname, false,
16621                                                          "CHECK CONSTRAINT", SECTION_POST_DATA,
16622                                                          q->data, delq->data, NULL,
16623                                                          NULL, 0,
16624                                                          NULL, NULL);
16625                 }
16626         }
16627         else if (coninfo->contype == 'c' && tbinfo == NULL)
16628         {
16629                 /* CHECK constraint on a domain */
16630                 TypeInfo   *tyinfo = coninfo->condomain;
16631
16632                 /* Ignore if not to be dumped separately */
16633                 if (coninfo->separate)
16634                 {
16635                         appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
16636                                                           fmtQualifiedDumpable(tyinfo));
16637                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
16638                                                           fmtId(coninfo->dobj.name),
16639                                                           coninfo->condef);
16640
16641                         appendPQExpBuffer(delq, "ALTER DOMAIN %s ",
16642                                                           fmtQualifiedDumpable(tyinfo));
16643                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16644                                                           fmtId(coninfo->dobj.name));
16645
16646                         tag = psprintf("%s %s", tyinfo->dobj.name, coninfo->dobj.name);
16647
16648                         if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16649                                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16650                                                          tag,
16651                                                          tyinfo->dobj.namespace->dobj.name,
16652                                                          NULL,
16653                                                          tyinfo->rolname, false,
16654                                                          "CHECK CONSTRAINT", SECTION_POST_DATA,
16655                                                          q->data, delq->data, NULL,
16656                                                          NULL, 0,
16657                                                          NULL, NULL);
16658                 }
16659         }
16660         else
16661         {
16662                 exit_horribly(NULL, "unrecognized constraint type: %c\n",
16663                                           coninfo->contype);
16664         }
16665
16666         /* Dump Constraint Comments --- only works for table constraints */
16667         if (tbinfo && coninfo->separate &&
16668                 coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16669                 dumpTableConstraintComment(fout, coninfo);
16670
16671         free(tag);
16672         destroyPQExpBuffer(q);
16673         destroyPQExpBuffer(delq);
16674 }
16675
16676 /*
16677  * dumpTableConstraintComment --- dump a constraint's comment if any
16678  *
16679  * This is split out because we need the function in two different places
16680  * depending on whether the constraint is dumped as part of CREATE TABLE
16681  * or as a separate ALTER command.
16682  */
16683 static void
16684 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
16685 {
16686         TableInfo  *tbinfo = coninfo->contable;
16687         PQExpBuffer conprefix = createPQExpBuffer();
16688         char       *qtabname;
16689
16690         qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
16691
16692         appendPQExpBuffer(conprefix, "CONSTRAINT %s ON",
16693                                           fmtId(coninfo->dobj.name));
16694
16695         if (coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16696                 dumpComment(fout, conprefix->data, qtabname,
16697                                         tbinfo->dobj.namespace->dobj.name,
16698                                         tbinfo->rolname,
16699                                         coninfo->dobj.catId, 0,
16700                                         coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
16701
16702         destroyPQExpBuffer(conprefix);
16703         free(qtabname);
16704 }
16705
16706 /*
16707  * findLastBuiltinOid_V71 -
16708  *
16709  * find the last built in oid
16710  *
16711  * For 7.1 through 8.0, we do this by retrieving datlastsysoid from the
16712  * pg_database entry for the current database.  (Note: current_database()
16713  * requires 7.3; pg_dump requires 8.0 now.)
16714  */
16715 static Oid
16716 findLastBuiltinOid_V71(Archive *fout)
16717 {
16718         PGresult   *res;
16719         Oid                     last_oid;
16720
16721         res = ExecuteSqlQueryForSingleRow(fout,
16722                                                                           "SELECT datlastsysoid FROM pg_database WHERE datname = current_database()");
16723         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
16724         PQclear(res);
16725
16726         return last_oid;
16727 }
16728
16729 /*
16730  * dumpSequence
16731  *        write the declaration (not data) of one user-defined sequence
16732  */
16733 static void
16734 dumpSequence(Archive *fout, TableInfo *tbinfo)
16735 {
16736         DumpOptions *dopt = fout->dopt;
16737         PGresult   *res;
16738         char       *startv,
16739                            *incby,
16740                            *maxv,
16741                            *minv,
16742                            *cache,
16743                            *seqtype;
16744         bool            cycled;
16745         bool            is_ascending;
16746         int64           default_minv,
16747                                 default_maxv;
16748         char            bufm[32],
16749                                 bufx[32];
16750         PQExpBuffer query = createPQExpBuffer();
16751         PQExpBuffer delqry = createPQExpBuffer();
16752         char       *qseqname;
16753
16754         qseqname = pg_strdup(fmtId(tbinfo->dobj.name));
16755
16756         if (fout->remoteVersion >= 100000)
16757         {
16758                 appendPQExpBuffer(query,
16759                                                   "SELECT format_type(seqtypid, NULL), "
16760                                                   "seqstart, seqincrement, "
16761                                                   "seqmax, seqmin, "
16762                                                   "seqcache, seqcycle "
16763                                                   "FROM pg_catalog.pg_sequence "
16764                                                   "WHERE seqrelid = '%u'::oid",
16765                                                   tbinfo->dobj.catId.oid);
16766         }
16767         else if (fout->remoteVersion >= 80400)
16768         {
16769                 /*
16770                  * Before PostgreSQL 10, sequence metadata is in the sequence itself.
16771                  *
16772                  * Note: it might seem that 'bigint' potentially needs to be
16773                  * schema-qualified, but actually that's a keyword.
16774                  */
16775                 appendPQExpBuffer(query,
16776                                                   "SELECT 'bigint' AS sequence_type, "
16777                                                   "start_value, increment_by, max_value, min_value, "
16778                                                   "cache_value, is_cycled FROM %s",
16779                                                   fmtQualifiedDumpable(tbinfo));
16780         }
16781         else
16782         {
16783                 appendPQExpBuffer(query,
16784                                                   "SELECT 'bigint' AS sequence_type, "
16785                                                   "0 AS start_value, increment_by, max_value, min_value, "
16786                                                   "cache_value, is_cycled FROM %s",
16787                                                   fmtQualifiedDumpable(tbinfo));
16788         }
16789
16790         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
16791
16792         if (PQntuples(res) != 1)
16793         {
16794                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
16795                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
16796                                                                  PQntuples(res)),
16797                                   tbinfo->dobj.name, PQntuples(res));
16798                 exit_nicely(1);
16799         }
16800
16801         seqtype = PQgetvalue(res, 0, 0);
16802         startv = PQgetvalue(res, 0, 1);
16803         incby = PQgetvalue(res, 0, 2);
16804         maxv = PQgetvalue(res, 0, 3);
16805         minv = PQgetvalue(res, 0, 4);
16806         cache = PQgetvalue(res, 0, 5);
16807         cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
16808
16809         /* Calculate default limits for a sequence of this type */
16810         is_ascending = (incby[0] != '-');
16811         if (strcmp(seqtype, "smallint") == 0)
16812         {
16813                 default_minv = is_ascending ? 1 : PG_INT16_MIN;
16814                 default_maxv = is_ascending ? PG_INT16_MAX : -1;
16815         }
16816         else if (strcmp(seqtype, "integer") == 0)
16817         {
16818                 default_minv = is_ascending ? 1 : PG_INT32_MIN;
16819                 default_maxv = is_ascending ? PG_INT32_MAX : -1;
16820         }
16821         else if (strcmp(seqtype, "bigint") == 0)
16822         {
16823                 default_minv = is_ascending ? 1 : PG_INT64_MIN;
16824                 default_maxv = is_ascending ? PG_INT64_MAX : -1;
16825         }
16826         else
16827         {
16828                 exit_horribly(NULL, "unrecognized sequence type: %s\n", seqtype);
16829                 default_minv = default_maxv = 0;        /* keep compiler quiet */
16830         }
16831
16832         /*
16833          * 64-bit strtol() isn't very portable, so convert the limits to strings
16834          * and compare that way.
16835          */
16836         snprintf(bufm, sizeof(bufm), INT64_FORMAT, default_minv);
16837         snprintf(bufx, sizeof(bufx), INT64_FORMAT, default_maxv);
16838
16839         /* Don't print minv/maxv if they match the respective default limit */
16840         if (strcmp(minv, bufm) == 0)
16841                 minv = NULL;
16842         if (strcmp(maxv, bufx) == 0)
16843                 maxv = NULL;
16844
16845         /*
16846          * Identity sequences are not to be dropped separately.
16847          */
16848         if (!tbinfo->is_identity_sequence)
16849         {
16850                 appendPQExpBuffer(delqry, "DROP SEQUENCE %s;\n",
16851                                                   fmtQualifiedDumpable(tbinfo));
16852         }
16853
16854         resetPQExpBuffer(query);
16855
16856         if (dopt->binary_upgrade)
16857         {
16858                 binary_upgrade_set_pg_class_oids(fout, query,
16859                                                                                  tbinfo->dobj.catId.oid, false);
16860                 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
16861                                                                                                 tbinfo->dobj.catId.oid);
16862         }
16863
16864         if (tbinfo->is_identity_sequence)
16865         {
16866                 TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
16867
16868                 appendPQExpBuffer(query,
16869                                                   "ALTER TABLE %s ",
16870                                                   fmtQualifiedDumpable(owning_tab));
16871                 appendPQExpBuffer(query,
16872                                                   "ALTER COLUMN %s ADD GENERATED ",
16873                                                   fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16874                 if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_ALWAYS)
16875                         appendPQExpBuffer(query, "ALWAYS");
16876                 else if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_BY_DEFAULT)
16877                         appendPQExpBuffer(query, "BY DEFAULT");
16878                 appendPQExpBuffer(query, " AS IDENTITY (\n    SEQUENCE NAME %s\n",
16879                                                   fmtQualifiedDumpable(tbinfo));
16880         }
16881         else
16882         {
16883                 appendPQExpBuffer(query,
16884                                                   "CREATE SEQUENCE %s\n",
16885                                                   fmtQualifiedDumpable(tbinfo));
16886
16887                 if (strcmp(seqtype, "bigint") != 0)
16888                         appendPQExpBuffer(query, "    AS %s\n", seqtype);
16889         }
16890
16891         if (fout->remoteVersion >= 80400)
16892                 appendPQExpBuffer(query, "    START WITH %s\n", startv);
16893
16894         appendPQExpBuffer(query, "    INCREMENT BY %s\n", incby);
16895
16896         if (minv)
16897                 appendPQExpBuffer(query, "    MINVALUE %s\n", minv);
16898         else
16899                 appendPQExpBufferStr(query, "    NO MINVALUE\n");
16900
16901         if (maxv)
16902                 appendPQExpBuffer(query, "    MAXVALUE %s\n", maxv);
16903         else
16904                 appendPQExpBufferStr(query, "    NO MAXVALUE\n");
16905
16906         appendPQExpBuffer(query,
16907                                           "    CACHE %s%s",
16908                                           cache, (cycled ? "\n    CYCLE" : ""));
16909
16910         if (tbinfo->is_identity_sequence)
16911                 appendPQExpBufferStr(query, "\n);\n");
16912         else
16913                 appendPQExpBufferStr(query, ";\n");
16914
16915         /* binary_upgrade:      no need to clear TOAST table oid */
16916
16917         if (dopt->binary_upgrade)
16918                 binary_upgrade_extension_member(query, &tbinfo->dobj,
16919                                                                                 "SEQUENCE", qseqname,
16920                                                                                 tbinfo->dobj.namespace->dobj.name);
16921
16922         if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16923                 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
16924                                          tbinfo->dobj.name,
16925                                          tbinfo->dobj.namespace->dobj.name,
16926                                          NULL,
16927                                          tbinfo->rolname,
16928                                          false, "SEQUENCE", SECTION_PRE_DATA,
16929                                          query->data, delqry->data, NULL,
16930                                          NULL, 0,
16931                                          NULL, NULL);
16932
16933         /*
16934          * If the sequence is owned by a table column, emit the ALTER for it as a
16935          * separate TOC entry immediately following the sequence's own entry. It's
16936          * OK to do this rather than using full sorting logic, because the
16937          * dependency that tells us it's owned will have forced the table to be
16938          * created first.  We can't just include the ALTER in the TOC entry
16939          * because it will fail if we haven't reassigned the sequence owner to
16940          * match the table's owner.
16941          *
16942          * We need not schema-qualify the table reference because both sequence
16943          * and table must be in the same schema.
16944          */
16945         if (OidIsValid(tbinfo->owning_tab) && !tbinfo->is_identity_sequence)
16946         {
16947                 TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
16948
16949                 if (owning_tab == NULL)
16950                         exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
16951                                                   tbinfo->owning_tab, tbinfo->dobj.catId.oid);
16952
16953                 if (owning_tab->dobj.dump & DUMP_COMPONENT_DEFINITION)
16954                 {
16955                         resetPQExpBuffer(query);
16956                         appendPQExpBuffer(query, "ALTER SEQUENCE %s",
16957                                                           fmtQualifiedDumpable(tbinfo));
16958                         appendPQExpBuffer(query, " OWNED BY %s",
16959                                                           fmtQualifiedDumpable(owning_tab));
16960                         appendPQExpBuffer(query, ".%s;\n",
16961                                                           fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16962
16963                         if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16964                                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
16965                                                          tbinfo->dobj.name,
16966                                                          tbinfo->dobj.namespace->dobj.name,
16967                                                          NULL,
16968                                                          tbinfo->rolname,
16969                                                          false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
16970                                                          query->data, "", NULL,
16971                                                          &(tbinfo->dobj.dumpId), 1,
16972                                                          NULL, NULL);
16973                 }
16974         }
16975
16976         /* Dump Sequence Comments and Security Labels */
16977         if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16978                 dumpComment(fout, "SEQUENCE", qseqname,
16979                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16980                                         tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
16981
16982         if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16983                 dumpSecLabel(fout, "SEQUENCE", qseqname,
16984                                          tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16985                                          tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
16986
16987         PQclear(res);
16988
16989         destroyPQExpBuffer(query);
16990         destroyPQExpBuffer(delqry);
16991         free(qseqname);
16992 }
16993
16994 /*
16995  * dumpSequenceData
16996  *        write the data of one user-defined sequence
16997  */
16998 static void
16999 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
17000 {
17001         TableInfo  *tbinfo = tdinfo->tdtable;
17002         PGresult   *res;
17003         char       *last;
17004         bool            called;
17005         PQExpBuffer query = createPQExpBuffer();
17006
17007         appendPQExpBuffer(query,
17008                                           "SELECT last_value, is_called FROM %s",
17009                                           fmtQualifiedDumpable(tbinfo));
17010
17011         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17012
17013         if (PQntuples(res) != 1)
17014         {
17015                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
17016                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
17017                                                                  PQntuples(res)),
17018                                   tbinfo->dobj.name, PQntuples(res));
17019                 exit_nicely(1);
17020         }
17021
17022         last = PQgetvalue(res, 0, 0);
17023         called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
17024
17025         resetPQExpBuffer(query);
17026         appendPQExpBufferStr(query, "SELECT pg_catalog.setval(");
17027         appendStringLiteralAH(query, fmtQualifiedDumpable(tbinfo), fout);
17028         appendPQExpBuffer(query, ", %s, %s);\n",
17029                                           last, (called ? "true" : "false"));
17030
17031         if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
17032                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
17033                                          tbinfo->dobj.name,
17034                                          tbinfo->dobj.namespace->dobj.name,
17035                                          NULL,
17036                                          tbinfo->rolname,
17037                                          false, "SEQUENCE SET", SECTION_DATA,
17038                                          query->data, "", NULL,
17039                                          &(tbinfo->dobj.dumpId), 1,
17040                                          NULL, NULL);
17041
17042         PQclear(res);
17043
17044         destroyPQExpBuffer(query);
17045 }
17046
17047 /*
17048  * dumpTrigger
17049  *        write the declaration of one user-defined table trigger
17050  */
17051 static void
17052 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
17053 {
17054         DumpOptions *dopt = fout->dopt;
17055         TableInfo  *tbinfo = tginfo->tgtable;
17056         PQExpBuffer query;
17057         PQExpBuffer delqry;
17058         PQExpBuffer trigprefix;
17059         char       *qtabname;
17060         char       *tgargs;
17061         size_t          lentgargs;
17062         const char *p;
17063         int                     findx;
17064         char       *tag;
17065
17066         /*
17067          * we needn't check dobj.dump because TriggerInfo wouldn't have been
17068          * created in the first place for non-dumpable triggers
17069          */
17070         if (dopt->dataOnly)
17071                 return;
17072
17073         query = createPQExpBuffer();
17074         delqry = createPQExpBuffer();
17075         trigprefix = createPQExpBuffer();
17076
17077         qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
17078
17079         appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
17080                                           fmtId(tginfo->dobj.name));
17081         appendPQExpBuffer(delqry, "ON %s;\n",
17082                                           fmtQualifiedDumpable(tbinfo));
17083
17084         if (tginfo->tgdef)
17085         {
17086                 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
17087         }
17088         else
17089         {
17090                 if (tginfo->tgisconstraint)
17091                 {
17092                         appendPQExpBufferStr(query, "CREATE CONSTRAINT TRIGGER ");
17093                         appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
17094                 }
17095                 else
17096                 {
17097                         appendPQExpBufferStr(query, "CREATE TRIGGER ");
17098                         appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
17099                 }
17100                 appendPQExpBufferStr(query, "\n    ");
17101
17102                 /* Trigger type */
17103                 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
17104                         appendPQExpBufferStr(query, "BEFORE");
17105                 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
17106                         appendPQExpBufferStr(query, "AFTER");
17107                 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
17108                         appendPQExpBufferStr(query, "INSTEAD OF");
17109                 else
17110                 {
17111                         write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
17112                         exit_nicely(1);
17113                 }
17114
17115                 findx = 0;
17116                 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
17117                 {
17118                         appendPQExpBufferStr(query, " INSERT");
17119                         findx++;
17120                 }
17121                 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
17122                 {
17123                         if (findx > 0)
17124                                 appendPQExpBufferStr(query, " OR DELETE");
17125                         else
17126                                 appendPQExpBufferStr(query, " DELETE");
17127                         findx++;
17128                 }
17129                 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
17130                 {
17131                         if (findx > 0)
17132                                 appendPQExpBufferStr(query, " OR UPDATE");
17133                         else
17134                                 appendPQExpBufferStr(query, " UPDATE");
17135                         findx++;
17136                 }
17137                 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
17138                 {
17139                         if (findx > 0)
17140                                 appendPQExpBufferStr(query, " OR TRUNCATE");
17141                         else
17142                                 appendPQExpBufferStr(query, " TRUNCATE");
17143                         findx++;
17144                 }
17145                 appendPQExpBuffer(query, " ON %s\n",
17146                                                   fmtQualifiedDumpable(tbinfo));
17147
17148                 if (tginfo->tgisconstraint)
17149                 {
17150                         if (OidIsValid(tginfo->tgconstrrelid))
17151                         {
17152                                 /* regclass output is already quoted */
17153                                 appendPQExpBuffer(query, "    FROM %s\n    ",
17154                                                                   tginfo->tgconstrrelname);
17155                         }
17156                         if (!tginfo->tgdeferrable)
17157                                 appendPQExpBufferStr(query, "NOT ");
17158                         appendPQExpBufferStr(query, "DEFERRABLE INITIALLY ");
17159                         if (tginfo->tginitdeferred)
17160                                 appendPQExpBufferStr(query, "DEFERRED\n");
17161                         else
17162                                 appendPQExpBufferStr(query, "IMMEDIATE\n");
17163                 }
17164
17165                 if (TRIGGER_FOR_ROW(tginfo->tgtype))
17166                         appendPQExpBufferStr(query, "    FOR EACH ROW\n    ");
17167                 else
17168                         appendPQExpBufferStr(query, "    FOR EACH STATEMENT\n    ");
17169
17170                 /* regproc output is already sufficiently quoted */
17171                 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
17172                                                   tginfo->tgfname);
17173
17174                 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
17175                                                                                   &lentgargs);
17176                 p = tgargs;
17177                 for (findx = 0; findx < tginfo->tgnargs; findx++)
17178                 {
17179                         /* find the embedded null that terminates this trigger argument */
17180                         size_t          tlen = strlen(p);
17181
17182                         if (p + tlen >= tgargs + lentgargs)
17183                         {
17184                                 /* hm, not found before end of bytea value... */
17185                                 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
17186                                                   tginfo->tgargs,
17187                                                   tginfo->dobj.name,
17188                                                   tbinfo->dobj.name);
17189                                 exit_nicely(1);
17190                         }
17191
17192                         if (findx > 0)
17193                                 appendPQExpBufferStr(query, ", ");
17194                         appendStringLiteralAH(query, p, fout);
17195                         p += tlen + 1;
17196                 }
17197                 free(tgargs);
17198                 appendPQExpBufferStr(query, ");\n");
17199         }
17200
17201         if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
17202         {
17203                 appendPQExpBuffer(query, "\nALTER TABLE %s ",
17204                                                   fmtQualifiedDumpable(tbinfo));
17205                 switch (tginfo->tgenabled)
17206                 {
17207                         case 'D':
17208                         case 'f':
17209                                 appendPQExpBufferStr(query, "DISABLE");
17210                                 break;
17211                         case 'A':
17212                                 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17213                                 break;
17214                         case 'R':
17215                                 appendPQExpBufferStr(query, "ENABLE REPLICA");
17216                                 break;
17217                         default:
17218                                 appendPQExpBufferStr(query, "ENABLE");
17219                                 break;
17220                 }
17221                 appendPQExpBuffer(query, " TRIGGER %s;\n",
17222                                                   fmtId(tginfo->dobj.name));
17223         }
17224
17225         appendPQExpBuffer(trigprefix, "TRIGGER %s ON",
17226                                           fmtId(tginfo->dobj.name));
17227
17228         tag = psprintf("%s %s", tbinfo->dobj.name, tginfo->dobj.name);
17229
17230         if (tginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17231                 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
17232                                          tag,
17233                                          tbinfo->dobj.namespace->dobj.name,
17234                                          NULL,
17235                                          tbinfo->rolname, false,
17236                                          "TRIGGER", SECTION_POST_DATA,
17237                                          query->data, delqry->data, NULL,
17238                                          NULL, 0,
17239                                          NULL, NULL);
17240
17241         if (tginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17242                 dumpComment(fout, trigprefix->data, qtabname,
17243                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17244                                         tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
17245
17246         free(tag);
17247         destroyPQExpBuffer(query);
17248         destroyPQExpBuffer(delqry);
17249         destroyPQExpBuffer(trigprefix);
17250         free(qtabname);
17251 }
17252
17253 /*
17254  * dumpEventTrigger
17255  *        write the declaration of one user-defined event trigger
17256  */
17257 static void
17258 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
17259 {
17260         DumpOptions *dopt = fout->dopt;
17261         PQExpBuffer query;
17262         PQExpBuffer delqry;
17263         char       *qevtname;
17264
17265         /* Skip if not to be dumped */
17266         if (!evtinfo->dobj.dump || dopt->dataOnly)
17267                 return;
17268
17269         query = createPQExpBuffer();
17270         delqry = createPQExpBuffer();
17271
17272         qevtname = pg_strdup(fmtId(evtinfo->dobj.name));
17273
17274         appendPQExpBufferStr(query, "CREATE EVENT TRIGGER ");
17275         appendPQExpBufferStr(query, qevtname);
17276         appendPQExpBufferStr(query, " ON ");
17277         appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
17278
17279         if (strcmp("", evtinfo->evttags) != 0)
17280         {
17281                 appendPQExpBufferStr(query, "\n         WHEN TAG IN (");
17282                 appendPQExpBufferStr(query, evtinfo->evttags);
17283                 appendPQExpBufferChar(query, ')');
17284         }
17285
17286         appendPQExpBufferStr(query, "\n   EXECUTE PROCEDURE ");
17287         appendPQExpBufferStr(query, evtinfo->evtfname);
17288         appendPQExpBufferStr(query, "();\n");
17289
17290         if (evtinfo->evtenabled != 'O')
17291         {
17292                 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
17293                                                   qevtname);
17294                 switch (evtinfo->evtenabled)
17295                 {
17296                         case 'D':
17297                                 appendPQExpBufferStr(query, "DISABLE");
17298                                 break;
17299                         case 'A':
17300                                 appendPQExpBufferStr(query, "ENABLE ALWAYS");
17301                                 break;
17302                         case 'R':
17303                                 appendPQExpBufferStr(query, "ENABLE REPLICA");
17304                                 break;
17305                         default:
17306                                 appendPQExpBufferStr(query, "ENABLE");
17307                                 break;
17308                 }
17309                 appendPQExpBufferStr(query, ";\n");
17310         }
17311
17312         appendPQExpBuffer(delqry, "DROP EVENT TRIGGER %s;\n",
17313                                           qevtname);
17314
17315         if (dopt->binary_upgrade)
17316                 binary_upgrade_extension_member(query, &evtinfo->dobj,
17317                                                                                 "EVENT TRIGGER", qevtname, NULL);
17318
17319         if (evtinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17320                 ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
17321                                          evtinfo->dobj.name, NULL, NULL,
17322                                          evtinfo->evtowner, false,
17323                                          "EVENT TRIGGER", SECTION_POST_DATA,
17324                                          query->data, delqry->data, NULL,
17325                                          NULL, 0,
17326                                          NULL, NULL);
17327
17328         if (evtinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17329                 dumpComment(fout, "EVENT TRIGGER", qevtname,
17330                                         NULL, evtinfo->evtowner,
17331                                         evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
17332
17333         destroyPQExpBuffer(query);
17334         destroyPQExpBuffer(delqry);
17335         free(qevtname);
17336 }
17337
17338 /*
17339  * dumpRule
17340  *              Dump a rule
17341  */
17342 static void
17343 dumpRule(Archive *fout, RuleInfo *rinfo)
17344 {
17345         DumpOptions *dopt = fout->dopt;
17346         TableInfo  *tbinfo = rinfo->ruletable;
17347         bool            is_view;
17348         PQExpBuffer query;
17349         PQExpBuffer cmd;
17350         PQExpBuffer delcmd;
17351         PQExpBuffer ruleprefix;
17352         char       *qtabname;
17353         PGresult   *res;
17354         char       *tag;
17355
17356         /* Skip if not to be dumped */
17357         if (!rinfo->dobj.dump || dopt->dataOnly)
17358                 return;
17359
17360         /*
17361          * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
17362          * we do not want to dump it as a separate object.
17363          */
17364         if (!rinfo->separate)
17365                 return;
17366
17367         /*
17368          * If it's an ON SELECT rule, we want to print it as a view definition,
17369          * instead of a rule.
17370          */
17371         is_view = (rinfo->ev_type == '1' && rinfo->is_instead);
17372
17373         query = createPQExpBuffer();
17374         cmd = createPQExpBuffer();
17375         delcmd = createPQExpBuffer();
17376         ruleprefix = createPQExpBuffer();
17377
17378         qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
17379
17380         if (is_view)
17381         {
17382                 PQExpBuffer result;
17383
17384                 /*
17385                  * We need OR REPLACE here because we'll be replacing a dummy view.
17386                  * Otherwise this should look largely like the regular view dump code.
17387                  */
17388                 appendPQExpBuffer(cmd, "CREATE OR REPLACE VIEW %s",
17389                                                   fmtQualifiedDumpable(tbinfo));
17390                 if (nonemptyReloptions(tbinfo->reloptions))
17391                 {
17392                         appendPQExpBufferStr(cmd, " WITH (");
17393                         appendReloptionsArrayAH(cmd, tbinfo->reloptions, "", fout);
17394                         appendPQExpBufferChar(cmd, ')');
17395                 }
17396                 result = createViewAsClause(fout, tbinfo);
17397                 appendPQExpBuffer(cmd, " AS\n%s", result->data);
17398                 destroyPQExpBuffer(result);
17399                 if (tbinfo->checkoption != NULL)
17400                         appendPQExpBuffer(cmd, "\n  WITH %s CHECK OPTION",
17401                                                           tbinfo->checkoption);
17402                 appendPQExpBufferStr(cmd, ";\n");
17403         }
17404         else
17405         {
17406                 /* In the rule case, just print pg_get_ruledef's result verbatim */
17407                 appendPQExpBuffer(query,
17408                                                   "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid)",
17409                                                   rinfo->dobj.catId.oid);
17410
17411                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17412
17413                 if (PQntuples(res) != 1)
17414                 {
17415                         write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
17416                                           rinfo->dobj.name, tbinfo->dobj.name);
17417                         exit_nicely(1);
17418                 }
17419
17420                 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
17421
17422                 PQclear(res);
17423         }
17424
17425         /*
17426          * Add the command to alter the rules replication firing semantics if it
17427          * differs from the default.
17428          */
17429         if (rinfo->ev_enabled != 'O')
17430         {
17431                 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtQualifiedDumpable(tbinfo));
17432                 switch (rinfo->ev_enabled)
17433                 {
17434                         case 'A':
17435                                 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
17436                                                                   fmtId(rinfo->dobj.name));
17437                                 break;
17438                         case 'R':
17439                                 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
17440                                                                   fmtId(rinfo->dobj.name));
17441                                 break;
17442                         case 'D':
17443                                 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
17444                                                                   fmtId(rinfo->dobj.name));
17445                                 break;
17446                 }
17447         }
17448
17449         if (is_view)
17450         {
17451                 /*
17452                  * We can't DROP a view's ON SELECT rule.  Instead, use CREATE OR
17453                  * REPLACE VIEW to replace the rule with something with minimal
17454                  * dependencies.
17455                  */
17456                 PQExpBuffer result;
17457
17458                 appendPQExpBuffer(delcmd, "CREATE OR REPLACE VIEW %s",
17459                                                   fmtQualifiedDumpable(tbinfo));
17460                 result = createDummyViewAsClause(fout, tbinfo);
17461                 appendPQExpBuffer(delcmd, " AS\n%s;\n", result->data);
17462                 destroyPQExpBuffer(result);
17463         }
17464         else
17465         {
17466                 appendPQExpBuffer(delcmd, "DROP RULE %s ",
17467                                                   fmtId(rinfo->dobj.name));
17468                 appendPQExpBuffer(delcmd, "ON %s;\n",
17469                                                   fmtQualifiedDumpable(tbinfo));
17470         }
17471
17472         appendPQExpBuffer(ruleprefix, "RULE %s ON",
17473                                           fmtId(rinfo->dobj.name));
17474
17475         tag = psprintf("%s %s", tbinfo->dobj.name, rinfo->dobj.name);
17476
17477         if (rinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17478                 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
17479                                          tag,
17480                                          tbinfo->dobj.namespace->dobj.name,
17481                                          NULL,
17482                                          tbinfo->rolname, false,
17483                                          "RULE", SECTION_POST_DATA,
17484                                          cmd->data, delcmd->data, NULL,
17485                                          NULL, 0,
17486                                          NULL, NULL);
17487
17488         /* Dump rule comments */
17489         if (rinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17490                 dumpComment(fout, ruleprefix->data, qtabname,
17491                                         tbinfo->dobj.namespace->dobj.name,
17492                                         tbinfo->rolname,
17493                                         rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
17494
17495         free(tag);
17496         destroyPQExpBuffer(query);
17497         destroyPQExpBuffer(cmd);
17498         destroyPQExpBuffer(delcmd);
17499         destroyPQExpBuffer(ruleprefix);
17500         free(qtabname);
17501 }
17502
17503 /*
17504  * getExtensionMembership --- obtain extension membership data
17505  *
17506  * We need to identify objects that are extension members as soon as they're
17507  * loaded, so that we can correctly determine whether they need to be dumped.
17508  * Generally speaking, extension member objects will get marked as *not* to
17509  * be dumped, as they will be recreated by the single CREATE EXTENSION
17510  * command.  However, in binary upgrade mode we still need to dump the members
17511  * individually.
17512  */
17513 void
17514 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
17515                                            int numExtensions)
17516 {
17517         PQExpBuffer query;
17518         PGresult   *res;
17519         int                     ntups,
17520                                 nextmembers,
17521                                 i;
17522         int                     i_classid,
17523                                 i_objid,
17524                                 i_refobjid;
17525         ExtensionMemberId *extmembers;
17526         ExtensionInfo *ext;
17527
17528         /* Nothing to do if no extensions */
17529         if (numExtensions == 0)
17530                 return;
17531
17532         query = createPQExpBuffer();
17533
17534         /* refclassid constraint is redundant but may speed the search */
17535         appendPQExpBufferStr(query, "SELECT "
17536                                                  "classid, objid, refobjid "
17537                                                  "FROM pg_depend "
17538                                                  "WHERE refclassid = 'pg_extension'::regclass "
17539                                                  "AND deptype = 'e' "
17540                                                  "ORDER BY 3");
17541
17542         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17543
17544         ntups = PQntuples(res);
17545
17546         i_classid = PQfnumber(res, "classid");
17547         i_objid = PQfnumber(res, "objid");
17548         i_refobjid = PQfnumber(res, "refobjid");
17549
17550         extmembers = (ExtensionMemberId *) pg_malloc(ntups * sizeof(ExtensionMemberId));
17551         nextmembers = 0;
17552
17553         /*
17554          * Accumulate data into extmembers[].
17555          *
17556          * Since we ordered the SELECT by referenced ID, we can expect that
17557          * multiple entries for the same extension will appear together; this
17558          * saves on searches.
17559          */
17560         ext = NULL;
17561
17562         for (i = 0; i < ntups; i++)
17563         {
17564                 CatalogId       objId;
17565                 Oid                     extId;
17566
17567                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17568                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17569                 extId = atooid(PQgetvalue(res, i, i_refobjid));
17570
17571                 if (ext == NULL ||
17572                         ext->dobj.catId.oid != extId)
17573                         ext = findExtensionByOid(extId);
17574
17575                 if (ext == NULL)
17576                 {
17577                         /* shouldn't happen */
17578                         fprintf(stderr, "could not find referenced extension %u\n", extId);
17579                         continue;
17580                 }
17581
17582                 extmembers[nextmembers].catId = objId;
17583                 extmembers[nextmembers].ext = ext;
17584                 nextmembers++;
17585         }
17586
17587         PQclear(res);
17588
17589         /* Remember the data for use later */
17590         setExtensionMembership(extmembers, nextmembers);
17591
17592         destroyPQExpBuffer(query);
17593 }
17594
17595 /*
17596  * processExtensionTables --- deal with extension configuration tables
17597  *
17598  * There are two parts to this process:
17599  *
17600  * 1. Identify and create dump records for extension configuration tables.
17601  *
17602  *        Extensions can mark tables as "configuration", which means that the user
17603  *        is able and expected to modify those tables after the extension has been
17604  *        loaded.  For these tables, we dump out only the data- the structure is
17605  *        expected to be handled at CREATE EXTENSION time, including any indexes or
17606  *        foreign keys, which brings us to-
17607  *
17608  * 2. Record FK dependencies between configuration tables.
17609  *
17610  *        Due to the FKs being created at CREATE EXTENSION time and therefore before
17611  *        the data is loaded, we have to work out what the best order for reloading
17612  *        the data is, to avoid FK violations when the tables are restored.  This is
17613  *        not perfect- we can't handle circular dependencies and if any exist they
17614  *        will cause an invalid dump to be produced (though at least all of the data
17615  *        is included for a user to manually restore).  This is currently documented
17616  *        but perhaps we can provide a better solution in the future.
17617  */
17618 void
17619 processExtensionTables(Archive *fout, ExtensionInfo extinfo[],
17620                                            int numExtensions)
17621 {
17622         DumpOptions *dopt = fout->dopt;
17623         PQExpBuffer query;
17624         PGresult   *res;
17625         int                     ntups,
17626                                 i;
17627         int                     i_conrelid,
17628                                 i_confrelid;
17629
17630         /* Nothing to do if no extensions */
17631         if (numExtensions == 0)
17632                 return;
17633
17634         /*
17635          * Identify extension configuration tables and create TableDataInfo
17636          * objects for them, ensuring their data will be dumped even though the
17637          * tables themselves won't be.
17638          *
17639          * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
17640          * user data in a configuration table is treated like schema data. This
17641          * seems appropriate since system data in a config table would get
17642          * reloaded by CREATE EXTENSION.
17643          */
17644         for (i = 0; i < numExtensions; i++)
17645         {
17646                 ExtensionInfo *curext = &(extinfo[i]);
17647                 char       *extconfig = curext->extconfig;
17648                 char       *extcondition = curext->extcondition;
17649                 char      **extconfigarray = NULL;
17650                 char      **extconditionarray = NULL;
17651                 int                     nconfigitems;
17652                 int                     nconditionitems;
17653
17654                 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
17655                         parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
17656                         nconfigitems == nconditionitems)
17657                 {
17658                         int                     j;
17659
17660                         for (j = 0; j < nconfigitems; j++)
17661                         {
17662                                 TableInfo  *configtbl;
17663                                 Oid                     configtbloid = atooid(extconfigarray[j]);
17664                                 bool            dumpobj =
17665                                 curext->dobj.dump & DUMP_COMPONENT_DEFINITION;
17666
17667                                 configtbl = findTableByOid(configtbloid);
17668                                 if (configtbl == NULL)
17669                                         continue;
17670
17671                                 /*
17672                                  * Tables of not-to-be-dumped extensions shouldn't be dumped
17673                                  * unless the table or its schema is explicitly included
17674                                  */
17675                                 if (!(curext->dobj.dump & DUMP_COMPONENT_DEFINITION))
17676                                 {
17677                                         /* check table explicitly requested */
17678                                         if (table_include_oids.head != NULL &&
17679                                                 simple_oid_list_member(&table_include_oids,
17680                                                                                            configtbloid))
17681                                                 dumpobj = true;
17682
17683                                         /* check table's schema explicitly requested */
17684                                         if (configtbl->dobj.namespace->dobj.dump &
17685                                                 DUMP_COMPONENT_DATA)
17686                                                 dumpobj = true;
17687                                 }
17688
17689                                 /* check table excluded by an exclusion switch */
17690                                 if (table_exclude_oids.head != NULL &&
17691                                         simple_oid_list_member(&table_exclude_oids,
17692                                                                                    configtbloid))
17693                                         dumpobj = false;
17694
17695                                 /* check schema excluded by an exclusion switch */
17696                                 if (simple_oid_list_member(&schema_exclude_oids,
17697                                                                                    configtbl->dobj.namespace->dobj.catId.oid))
17698                                         dumpobj = false;
17699
17700                                 if (dumpobj)
17701                                 {
17702                                         /*
17703                                          * Note: config tables are dumped without OIDs regardless
17704                                          * of the --oids setting.  This is because row filtering
17705                                          * conditions aren't compatible with dumping OIDs.
17706                                          */
17707                                         makeTableDataInfo(dopt, configtbl, false);
17708                                         if (configtbl->dataObj != NULL)
17709                                         {
17710                                                 if (strlen(extconditionarray[j]) > 0)
17711                                                         configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
17712                                         }
17713                                 }
17714                         }
17715                 }
17716                 if (extconfigarray)
17717                         free(extconfigarray);
17718                 if (extconditionarray)
17719                         free(extconditionarray);
17720         }
17721
17722         /*
17723          * Now that all the TableInfoData objects have been created for all the
17724          * extensions, check their FK dependencies and register them to try and
17725          * dump the data out in an order that they can be restored in.
17726          *
17727          * Note that this is not a problem for user tables as their FKs are
17728          * recreated after the data has been loaded.
17729          */
17730
17731         query = createPQExpBuffer();
17732
17733         printfPQExpBuffer(query,
17734                                           "SELECT conrelid, confrelid "
17735                                           "FROM pg_constraint "
17736                                           "JOIN pg_depend ON (objid = confrelid) "
17737                                           "WHERE contype = 'f' "
17738                                           "AND refclassid = 'pg_extension'::regclass "
17739                                           "AND classid = 'pg_class'::regclass;");
17740
17741         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17742         ntups = PQntuples(res);
17743
17744         i_conrelid = PQfnumber(res, "conrelid");
17745         i_confrelid = PQfnumber(res, "confrelid");
17746
17747         /* Now get the dependencies and register them */
17748         for (i = 0; i < ntups; i++)
17749         {
17750                 Oid                     conrelid,
17751                                         confrelid;
17752                 TableInfo  *reftable,
17753                                    *contable;
17754
17755                 conrelid = atooid(PQgetvalue(res, i, i_conrelid));
17756                 confrelid = atooid(PQgetvalue(res, i, i_confrelid));
17757                 contable = findTableByOid(conrelid);
17758                 reftable = findTableByOid(confrelid);
17759
17760                 if (reftable == NULL ||
17761                         reftable->dataObj == NULL ||
17762                         contable == NULL ||
17763                         contable->dataObj == NULL)
17764                         continue;
17765
17766                 /*
17767                  * Make referencing TABLE_DATA object depend on the referenced table's
17768                  * TABLE_DATA object.
17769                  */
17770                 addObjectDependency(&contable->dataObj->dobj,
17771                                                         reftable->dataObj->dobj.dumpId);
17772         }
17773         PQclear(res);
17774         destroyPQExpBuffer(query);
17775 }
17776
17777 /*
17778  * getDependencies --- obtain available dependency data
17779  */
17780 static void
17781 getDependencies(Archive *fout)
17782 {
17783         PQExpBuffer query;
17784         PGresult   *res;
17785         int                     ntups,
17786                                 i;
17787         int                     i_classid,
17788                                 i_objid,
17789                                 i_refclassid,
17790                                 i_refobjid,
17791                                 i_deptype;
17792         DumpableObject *dobj,
17793                            *refdobj;
17794
17795         if (g_verbose)
17796                 write_msg(NULL, "reading dependency data\n");
17797
17798         query = createPQExpBuffer();
17799
17800         /*
17801          * PIN dependencies aren't interesting, and EXTENSION dependencies were
17802          * already processed by getExtensionMembership.
17803          */
17804         appendPQExpBufferStr(query, "SELECT "
17805                                                  "classid, objid, refclassid, refobjid, deptype "
17806                                                  "FROM pg_depend "
17807                                                  "WHERE deptype != 'p' AND deptype != 'e' "
17808                                                  "ORDER BY 1,2");
17809
17810         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17811
17812         ntups = PQntuples(res);
17813
17814         i_classid = PQfnumber(res, "classid");
17815         i_objid = PQfnumber(res, "objid");
17816         i_refclassid = PQfnumber(res, "refclassid");
17817         i_refobjid = PQfnumber(res, "refobjid");
17818         i_deptype = PQfnumber(res, "deptype");
17819
17820         /*
17821          * Since we ordered the SELECT by referencing ID, we can expect that
17822          * multiple entries for the same object will appear together; this saves
17823          * on searches.
17824          */
17825         dobj = NULL;
17826
17827         for (i = 0; i < ntups; i++)
17828         {
17829                 CatalogId       objId;
17830                 CatalogId       refobjId;
17831                 char            deptype;
17832
17833                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17834                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17835                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
17836                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
17837                 deptype = *(PQgetvalue(res, i, i_deptype));
17838
17839                 if (dobj == NULL ||
17840                         dobj->catId.tableoid != objId.tableoid ||
17841                         dobj->catId.oid != objId.oid)
17842                         dobj = findObjectByCatalogId(objId);
17843
17844                 /*
17845                  * Failure to find objects mentioned in pg_depend is not unexpected,
17846                  * since for example we don't collect info about TOAST tables.
17847                  */
17848                 if (dobj == NULL)
17849                 {
17850 #ifdef NOT_USED
17851                         fprintf(stderr, "no referencing object %u %u\n",
17852                                         objId.tableoid, objId.oid);
17853 #endif
17854                         continue;
17855                 }
17856
17857                 refdobj = findObjectByCatalogId(refobjId);
17858
17859                 if (refdobj == NULL)
17860                 {
17861 #ifdef NOT_USED
17862                         fprintf(stderr, "no referenced object %u %u\n",
17863                                         refobjId.tableoid, refobjId.oid);
17864 #endif
17865                         continue;
17866                 }
17867
17868                 /*
17869                  * Ordinarily, table rowtypes have implicit dependencies on their
17870                  * tables.  However, for a composite type the implicit dependency goes
17871                  * the other way in pg_depend; which is the right thing for DROP but
17872                  * it doesn't produce the dependency ordering we need. So in that one
17873                  * case, we reverse the direction of the dependency.
17874                  */
17875                 if (deptype == 'i' &&
17876                         dobj->objType == DO_TABLE &&
17877                         refdobj->objType == DO_TYPE)
17878                         addObjectDependency(refdobj, dobj->dumpId);
17879                 else
17880                         /* normal case */
17881                         addObjectDependency(dobj, refdobj->dumpId);
17882         }
17883
17884         PQclear(res);
17885
17886         destroyPQExpBuffer(query);
17887 }
17888
17889
17890 /*
17891  * createBoundaryObjects - create dummy DumpableObjects to represent
17892  * dump section boundaries.
17893  */
17894 static DumpableObject *
17895 createBoundaryObjects(void)
17896 {
17897         DumpableObject *dobjs;
17898
17899         dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
17900
17901         dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
17902         dobjs[0].catId = nilCatalogId;
17903         AssignDumpId(dobjs + 0);
17904         dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
17905
17906         dobjs[1].objType = DO_POST_DATA_BOUNDARY;
17907         dobjs[1].catId = nilCatalogId;
17908         AssignDumpId(dobjs + 1);
17909         dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
17910
17911         return dobjs;
17912 }
17913
17914 /*
17915  * addBoundaryDependencies - add dependencies as needed to enforce the dump
17916  * section boundaries.
17917  */
17918 static void
17919 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
17920                                                 DumpableObject *boundaryObjs)
17921 {
17922         DumpableObject *preDataBound = boundaryObjs + 0;
17923         DumpableObject *postDataBound = boundaryObjs + 1;
17924         int                     i;
17925
17926         for (i = 0; i < numObjs; i++)
17927         {
17928                 DumpableObject *dobj = dobjs[i];
17929
17930                 /*
17931                  * The classification of object types here must match the SECTION_xxx
17932                  * values assigned during subsequent ArchiveEntry calls!
17933                  */
17934                 switch (dobj->objType)
17935                 {
17936                         case DO_NAMESPACE:
17937                         case DO_EXTENSION:
17938                         case DO_TYPE:
17939                         case DO_SHELL_TYPE:
17940                         case DO_FUNC:
17941                         case DO_AGG:
17942                         case DO_OPERATOR:
17943                         case DO_ACCESS_METHOD:
17944                         case DO_OPCLASS:
17945                         case DO_OPFAMILY:
17946                         case DO_COLLATION:
17947                         case DO_CONVERSION:
17948                         case DO_TABLE:
17949                         case DO_ATTRDEF:
17950                         case DO_PROCLANG:
17951                         case DO_CAST:
17952                         case DO_DUMMY_TYPE:
17953                         case DO_TSPARSER:
17954                         case DO_TSDICT:
17955                         case DO_TSTEMPLATE:
17956                         case DO_TSCONFIG:
17957                         case DO_FDW:
17958                         case DO_FOREIGN_SERVER:
17959                         case DO_TRANSFORM:
17960                         case DO_BLOB:
17961                                 /* Pre-data objects: must come before the pre-data boundary */
17962                                 addObjectDependency(preDataBound, dobj->dumpId);
17963                                 break;
17964                         case DO_TABLE_DATA:
17965                         case DO_SEQUENCE_SET:
17966                         case DO_BLOB_DATA:
17967                                 /* Data objects: must come between the boundaries */
17968                                 addObjectDependency(dobj, preDataBound->dumpId);
17969                                 addObjectDependency(postDataBound, dobj->dumpId);
17970                                 break;
17971                         case DO_INDEX:
17972                         case DO_INDEX_ATTACH:
17973                         case DO_STATSEXT:
17974                         case DO_REFRESH_MATVIEW:
17975                         case DO_TRIGGER:
17976                         case DO_EVENT_TRIGGER:
17977                         case DO_DEFAULT_ACL:
17978                         case DO_POLICY:
17979                         case DO_PUBLICATION:
17980                         case DO_PUBLICATION_REL:
17981                         case DO_SUBSCRIPTION:
17982                                 /* Post-data objects: must come after the post-data boundary */
17983                                 addObjectDependency(dobj, postDataBound->dumpId);
17984                                 break;
17985                         case DO_RULE:
17986                                 /* Rules are post-data, but only if dumped separately */
17987                                 if (((RuleInfo *) dobj)->separate)
17988                                         addObjectDependency(dobj, postDataBound->dumpId);
17989                                 break;
17990                         case DO_CONSTRAINT:
17991                         case DO_FK_CONSTRAINT:
17992                                 /* Constraints are post-data, but only if dumped separately */
17993                                 if (((ConstraintInfo *) dobj)->separate)
17994                                         addObjectDependency(dobj, postDataBound->dumpId);
17995                                 break;
17996                         case DO_PRE_DATA_BOUNDARY:
17997                                 /* nothing to do */
17998                                 break;
17999                         case DO_POST_DATA_BOUNDARY:
18000                                 /* must come after the pre-data boundary */
18001                                 addObjectDependency(dobj, preDataBound->dumpId);
18002                                 break;
18003                 }
18004         }
18005 }
18006
18007
18008 /*
18009  * BuildArchiveDependencies - create dependency data for archive TOC entries
18010  *
18011  * The raw dependency data obtained by getDependencies() is not terribly
18012  * useful in an archive dump, because in many cases there are dependency
18013  * chains linking through objects that don't appear explicitly in the dump.
18014  * For example, a view will depend on its _RETURN rule while the _RETURN rule
18015  * will depend on other objects --- but the rule will not appear as a separate
18016  * object in the dump.  We need to adjust the view's dependencies to include
18017  * whatever the rule depends on that is included in the dump.
18018  *
18019  * Just to make things more complicated, there are also "special" dependencies
18020  * such as the dependency of a TABLE DATA item on its TABLE, which we must
18021  * not rearrange because pg_restore knows that TABLE DATA only depends on
18022  * its table.  In these cases we must leave the dependencies strictly as-is
18023  * even if they refer to not-to-be-dumped objects.
18024  *
18025  * To handle this, the convention is that "special" dependencies are created
18026  * during ArchiveEntry calls, and an archive TOC item that has any such
18027  * entries will not be touched here.  Otherwise, we recursively search the
18028  * DumpableObject data structures to build the correct dependencies for each
18029  * archive TOC item.
18030  */
18031 static void
18032 BuildArchiveDependencies(Archive *fout)
18033 {
18034         ArchiveHandle *AH = (ArchiveHandle *) fout;
18035         TocEntry   *te;
18036
18037         /* Scan all TOC entries in the archive */
18038         for (te = AH->toc->next; te != AH->toc; te = te->next)
18039         {
18040                 DumpableObject *dobj;
18041                 DumpId     *dependencies;
18042                 int                     nDeps;
18043                 int                     allocDeps;
18044
18045                 /* No need to process entries that will not be dumped */
18046                 if (te->reqs == 0)
18047                         continue;
18048                 /* Ignore entries that already have "special" dependencies */
18049                 if (te->nDeps > 0)
18050                         continue;
18051                 /* Otherwise, look up the item's original DumpableObject, if any */
18052                 dobj = findObjectByDumpId(te->dumpId);
18053                 if (dobj == NULL)
18054                         continue;
18055                 /* No work if it has no dependencies */
18056                 if (dobj->nDeps <= 0)
18057                         continue;
18058                 /* Set up work array */
18059                 allocDeps = 64;
18060                 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
18061                 nDeps = 0;
18062                 /* Recursively find all dumpable dependencies */
18063                 findDumpableDependencies(AH, dobj,
18064                                                                  &dependencies, &nDeps, &allocDeps);
18065                 /* And save 'em ... */
18066                 if (nDeps > 0)
18067                 {
18068                         dependencies = (DumpId *) pg_realloc(dependencies,
18069                                                                                                  nDeps * sizeof(DumpId));
18070                         te->dependencies = dependencies;
18071                         te->nDeps = nDeps;
18072                 }
18073                 else
18074                         free(dependencies);
18075         }
18076 }
18077
18078 /* Recursive search subroutine for BuildArchiveDependencies */
18079 static void
18080 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
18081                                                  DumpId **dependencies, int *nDeps, int *allocDeps)
18082 {
18083         int                     i;
18084
18085         /*
18086          * Ignore section boundary objects: if we search through them, we'll
18087          * report lots of bogus dependencies.
18088          */
18089         if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
18090                 dobj->objType == DO_POST_DATA_BOUNDARY)
18091                 return;
18092
18093         for (i = 0; i < dobj->nDeps; i++)
18094         {
18095                 DumpId          depid = dobj->dependencies[i];
18096
18097                 if (TocIDRequired(AH, depid) != 0)
18098                 {
18099                         /* Object will be dumped, so just reference it as a dependency */
18100                         if (*nDeps >= *allocDeps)
18101                         {
18102                                 *allocDeps *= 2;
18103                                 *dependencies = (DumpId *) pg_realloc(*dependencies,
18104                                                                                                           *allocDeps * sizeof(DumpId));
18105                         }
18106                         (*dependencies)[*nDeps] = depid;
18107                         (*nDeps)++;
18108                 }
18109                 else
18110                 {
18111                         /*
18112                          * Object will not be dumped, so recursively consider its deps. We
18113                          * rely on the assumption that sortDumpableObjects already broke
18114                          * any dependency loops, else we might recurse infinitely.
18115                          */
18116                         DumpableObject *otherdobj = findObjectByDumpId(depid);
18117
18118                         if (otherdobj)
18119                                 findDumpableDependencies(AH, otherdobj,
18120                                                                                  dependencies, nDeps, allocDeps);
18121                 }
18122         }
18123 }
18124
18125
18126 /*
18127  * getFormattedTypeName - retrieve a nicely-formatted type name for the
18128  * given type OID.
18129  *
18130  * This does not guarantee to schema-qualify the output, so it should not
18131  * be used to create the target object name for CREATE or ALTER commands.
18132  *
18133  * TODO: there might be some value in caching the results.
18134  */
18135 static char *
18136 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
18137 {
18138         char       *result;
18139         PQExpBuffer query;
18140         PGresult   *res;
18141
18142         if (oid == 0)
18143         {
18144                 if ((opts & zeroAsOpaque) != 0)
18145                         return pg_strdup(g_opaque_type);
18146                 else if ((opts & zeroAsAny) != 0)
18147                         return pg_strdup("'any'");
18148                 else if ((opts & zeroAsStar) != 0)
18149                         return pg_strdup("*");
18150                 else if ((opts & zeroAsNone) != 0)
18151                         return pg_strdup("NONE");
18152         }
18153
18154         query = createPQExpBuffer();
18155         appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
18156                                           oid);
18157
18158         res = ExecuteSqlQueryForSingleRow(fout, query->data);
18159
18160         /* result of format_type is already quoted */
18161         result = pg_strdup(PQgetvalue(res, 0, 0));
18162
18163         PQclear(res);
18164         destroyPQExpBuffer(query);
18165
18166         return result;
18167 }
18168
18169 /*
18170  * Return a column list clause for the given relation.
18171  *
18172  * Special case: if there are no undropped columns in the relation, return
18173  * "", not an invalid "()" column list.
18174  */
18175 static const char *
18176 fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer)
18177 {
18178         int                     numatts = ti->numatts;
18179         char      **attnames = ti->attnames;
18180         bool       *attisdropped = ti->attisdropped;
18181         bool            needComma;
18182         int                     i;
18183
18184         appendPQExpBufferChar(buffer, '(');
18185         needComma = false;
18186         for (i = 0; i < numatts; i++)
18187         {
18188                 if (attisdropped[i])
18189                         continue;
18190                 if (needComma)
18191                         appendPQExpBufferStr(buffer, ", ");
18192                 appendPQExpBufferStr(buffer, fmtId(attnames[i]));
18193                 needComma = true;
18194         }
18195
18196         if (!needComma)
18197                 return "";                              /* no undropped columns */
18198
18199         appendPQExpBufferChar(buffer, ')');
18200         return buffer->data;
18201 }
18202
18203 /*
18204  * Check if a reloptions array is nonempty.
18205  */
18206 static bool
18207 nonemptyReloptions(const char *reloptions)
18208 {
18209         /* Don't want to print it if it's just "{}" */
18210         return (reloptions != NULL && strlen(reloptions) > 2);
18211 }
18212
18213 /*
18214  * Format a reloptions array and append it to the given buffer.
18215  *
18216  * "prefix" is prepended to the option names; typically it's "" or "toast.".
18217  */
18218 static void
18219 appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
18220                                                 const char *prefix, Archive *fout)
18221 {
18222         bool            res;
18223
18224         res = appendReloptionsArray(buffer, reloptions, prefix, fout->encoding,
18225                                                                 fout->std_strings);
18226         if (!res)
18227                 write_msg(NULL, "WARNING: could not parse reloptions array\n");
18228 }