]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_dump.c
Fix function comment for dumpACL()
[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-2017, 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_am.h"
46 #include "catalog/pg_attribute.h"
47 #include "catalog/pg_cast.h"
48 #include "catalog/pg_class.h"
49 #include "catalog/pg_default_acl.h"
50 #include "catalog/pg_largeobject.h"
51 #include "catalog/pg_largeobject_metadata.h"
52 #include "catalog/pg_proc.h"
53 #include "catalog/pg_trigger.h"
54 #include "catalog/pg_type.h"
55 #include "libpq/libpq-fs.h"
56
57 #include "dumputils.h"
58 #include "parallel.h"
59 #include "pg_backup_db.h"
60 #include "pg_backup_utils.h"
61 #include "pg_dump.h"
62 #include "fe_utils/string_utils.h"
63
64
65 typedef struct
66 {
67         const char *descr;                      /* comment for an object */
68         Oid                     classoid;               /* object class (catalog OID) */
69         Oid                     objoid;                 /* object OID */
70         int                     objsubid;               /* subobject (table column #) */
71 } CommentItem;
72
73 typedef struct
74 {
75         const char *provider;           /* label provider of this security label */
76         const char *label;                      /* security label for an object */
77         Oid                     classoid;               /* object class (catalog OID) */
78         Oid                     objoid;                 /* object OID */
79         int                     objsubid;               /* subobject (table column #) */
80 } SecLabelItem;
81
82 typedef enum OidOptions
83 {
84         zeroAsOpaque = 1,
85         zeroAsAny = 2,
86         zeroAsStar = 4,
87         zeroAsNone = 8
88 } OidOptions;
89
90 /* global decls */
91 bool            g_verbose;                      /* User wants verbose narration of our
92                                                                  * activities. */
93 static bool dosync = true;              /* Issue fsync() to make dump durable on disk. */
94
95 /* subquery used to convert user ID (eg, datdba) to user name */
96 static const char *username_subquery;
97
98 /*
99  * For 8.0 and earlier servers, pulled from pg_database, for 8.1+ we use
100  * FirstNormalObjectId - 1.
101  */
102 static Oid      g_last_builtin_oid; /* value of the last builtin oid */
103
104 /* The specified names/patterns should to match at least one entity */
105 static int      strict_names = 0;
106
107 /*
108  * Object inclusion/exclusion lists
109  *
110  * The string lists record the patterns given by command-line switches,
111  * which we then convert to lists of OIDs of matching objects.
112  */
113 static SimpleStringList schema_include_patterns = {NULL, NULL};
114 static SimpleOidList schema_include_oids = {NULL, NULL};
115 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
116 static SimpleOidList schema_exclude_oids = {NULL, NULL};
117
118 static SimpleStringList table_include_patterns = {NULL, NULL};
119 static SimpleOidList table_include_oids = {NULL, NULL};
120 static SimpleStringList table_exclude_patterns = {NULL, NULL};
121 static SimpleOidList table_exclude_oids = {NULL, NULL};
122 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
123 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
124
125
126 char            g_opaque_type[10];      /* name for the opaque type */
127
128 /* placeholders for the delimiters for comments */
129 char            g_comment_start[10];
130 char            g_comment_end[10];
131
132 static const CatalogId nilCatalogId = {0, 0};
133
134 static void help(const char *progname);
135 static void setup_connection(Archive *AH,
136                                  const char *dumpencoding, const char *dumpsnapshot,
137                                  char *use_role);
138 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
139 static void expand_schema_name_patterns(Archive *fout,
140                                                         SimpleStringList *patterns,
141                                                         SimpleOidList *oids,
142                                                         bool strict_names);
143 static void expand_table_name_patterns(Archive *fout,
144                                                    SimpleStringList *patterns,
145                                                    SimpleOidList *oids,
146                                                    bool strict_names);
147 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid);
148 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
149 static void refreshMatViewData(Archive *fout, TableDataInfo *tdinfo);
150 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
151 static void dumpComment(Archive *fout, const char *target,
152                         const char *namespace, const char *owner,
153                         CatalogId catalogId, int subid, DumpId dumpId);
154 static int findComments(Archive *fout, Oid classoid, Oid objoid,
155                          CommentItem **items);
156 static int      collectComments(Archive *fout, CommentItem **items);
157 static void dumpSecLabel(Archive *fout, const char *target,
158                          const char *namespace, const char *owner,
159                          CatalogId catalogId, int subid, DumpId dumpId);
160 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
161                           SecLabelItem **items);
162 static int      collectSecLabels(Archive *fout, SecLabelItem **items);
163 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
164 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
165 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
166 static void dumpType(Archive *fout, TypeInfo *tyinfo);
167 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
168 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
169 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
170 static void dumpUndefinedType(Archive *fout, TypeInfo *tyinfo);
171 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
172 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
173 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
174 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
175 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
176 static void dumpFunc(Archive *fout, FuncInfo *finfo);
177 static void dumpCast(Archive *fout, CastInfo *cast);
178 static void dumpTransform(Archive *fout, TransformInfo *transform);
179 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
180 static void dumpAccessMethod(Archive *fout, AccessMethodInfo *oprinfo);
181 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
182 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
183 static void dumpCollation(Archive *fout, CollInfo *collinfo);
184 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
185 static void dumpRule(Archive *fout, RuleInfo *rinfo);
186 static void dumpAgg(Archive *fout, AggInfo *agginfo);
187 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
188 static void dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo);
189 static void dumpTable(Archive *fout, TableInfo *tbinfo);
190 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
191 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
192 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
193 static void dumpSequenceData(Archive *fout, TableDataInfo *tdinfo);
194 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
195 static void dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo);
196 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
197 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
198 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
199 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
200 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
201 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
202 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
203 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
204 static void dumpUserMappings(Archive *fout,
205                                  const char *servername, const char *namespace,
206                                  const char *owner, CatalogId catalogId, DumpId dumpId);
207 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
208
209 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
210                 const char *type, const char *name, const char *subname,
211                 const char *tag, const char *nspname, const char *owner,
212                 const char *acls, const char *racls,
213                 const char *initacls, const char *initracls);
214
215 static void getDependencies(Archive *fout);
216 static void BuildArchiveDependencies(Archive *fout);
217 static void findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
218                                                  DumpId **dependencies, int *nDeps, int *allocDeps);
219
220 static DumpableObject *createBoundaryObjects(void);
221 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
222                                                 DumpableObject *boundaryObjs);
223
224 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
225 static void getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, bool oids, char relkind);
226 static void makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo, bool oids);
227 static void buildMatViewRefreshDependencies(Archive *fout);
228 static void getTableDataFKConstraints(void);
229 static char *format_function_arguments(FuncInfo *finfo, char *funcargs,
230                                                   bool is_agg);
231 static char *format_function_arguments_old(Archive *fout,
232                                                           FuncInfo *finfo, int nallargs,
233                                                           char **allargtypes,
234                                                           char **argmodes,
235                                                           char **argnames);
236 static char *format_function_signature(Archive *fout,
237                                                   FuncInfo *finfo, bool honor_quotes);
238 static char *convertRegProcReference(Archive *fout,
239                                                 const char *proc);
240 static char *convertOperatorReference(Archive *fout, const char *opr);
241 static char *convertTSFunction(Archive *fout, Oid funcOid);
242 static Oid      findLastBuiltinOid_V71(Archive *fout, const char *);
243 static void selectSourceSchema(Archive *fout, const char *schemaName);
244 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
245 static void getBlobs(Archive *fout);
246 static void dumpBlob(Archive *fout, BlobInfo *binfo);
247 static int      dumpBlobs(Archive *fout, void *arg);
248 static void dumpPolicy(Archive *fout, PolicyInfo *polinfo);
249 static void dumpPublication(Archive *fout, PublicationInfo *pubinfo);
250 static void dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo);
251 static void dumpSubscription(Archive *fout, SubscriptionInfo *subinfo);
252 static void dumpDatabase(Archive *AH);
253 static void dumpEncoding(Archive *AH);
254 static void dumpStdStrings(Archive *AH);
255 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
256                                                                                  PQExpBuffer upgrade_buffer, Oid pg_type_oid);
257 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
258                                                                                 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
259 static void binary_upgrade_set_pg_class_oids(Archive *fout,
260                                                                  PQExpBuffer upgrade_buffer,
261                                                                  Oid pg_class_oid, bool is_index);
262 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
263                                                                 DumpableObject *dobj,
264                                                                 const char *objlabel);
265 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
266 static const char *fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer);
267 static bool nonemptyReloptions(const char *reloptions);
268 static void appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
269                                                 const char *prefix, Archive *fout);
270 static char *get_synchronized_snapshot(Archive *fout);
271 static void setupDumpWorker(Archive *AHX);
272
273
274 int
275 main(int argc, char **argv)
276 {
277         int                     c;
278         const char *filename = NULL;
279         const char *format = "p";
280         TableInfo  *tblinfo;
281         int                     numTables;
282         DumpableObject **dobjs;
283         int                     numObjs;
284         DumpableObject *boundaryObjs;
285         int                     i;
286         int                     optindex;
287         RestoreOptions *ropt;
288         Archive    *fout;                       /* the script file */
289         const char *dumpencoding = NULL;
290         const char *dumpsnapshot = NULL;
291         char       *use_role = NULL;
292         int                     numWorkers = 1;
293         trivalue        prompt_password = TRI_DEFAULT;
294         int                     compressLevel = -1;
295         int                     plainText = 0;
296         ArchiveFormat archiveFormat = archUnknown;
297         ArchiveMode archiveMode;
298
299         static DumpOptions dopt;
300
301         static struct option long_options[] = {
302                 {"data-only", no_argument, NULL, 'a'},
303                 {"blobs", no_argument, NULL, 'b'},
304                 {"no-blobs", no_argument, NULL, 'B'},
305                 {"clean", no_argument, NULL, 'c'},
306                 {"create", no_argument, NULL, 'C'},
307                 {"dbname", required_argument, NULL, 'd'},
308                 {"file", required_argument, NULL, 'f'},
309                 {"format", required_argument, NULL, 'F'},
310                 {"host", required_argument, NULL, 'h'},
311                 {"jobs", 1, NULL, 'j'},
312                 {"no-reconnect", no_argument, NULL, 'R'},
313                 {"oids", no_argument, NULL, 'o'},
314                 {"no-owner", no_argument, NULL, 'O'},
315                 {"port", required_argument, NULL, 'p'},
316                 {"schema", required_argument, NULL, 'n'},
317                 {"exclude-schema", required_argument, NULL, 'N'},
318                 {"schema-only", no_argument, NULL, 's'},
319                 {"superuser", required_argument, NULL, 'S'},
320                 {"table", required_argument, NULL, 't'},
321                 {"exclude-table", required_argument, NULL, 'T'},
322                 {"no-password", no_argument, NULL, 'w'},
323                 {"password", no_argument, NULL, 'W'},
324                 {"username", required_argument, NULL, 'U'},
325                 {"verbose", no_argument, NULL, 'v'},
326                 {"no-privileges", no_argument, NULL, 'x'},
327                 {"no-acl", no_argument, NULL, 'x'},
328                 {"compress", required_argument, NULL, 'Z'},
329                 {"encoding", required_argument, NULL, 'E'},
330                 {"help", no_argument, NULL, '?'},
331                 {"version", no_argument, NULL, 'V'},
332
333                 /*
334                  * the following options don't have an equivalent short option letter
335                  */
336                 {"attribute-inserts", no_argument, &dopt.column_inserts, 1},
337                 {"binary-upgrade", no_argument, &dopt.binary_upgrade, 1},
338                 {"column-inserts", no_argument, &dopt.column_inserts, 1},
339                 {"disable-dollar-quoting", no_argument, &dopt.disable_dollar_quoting, 1},
340                 {"disable-triggers", no_argument, &dopt.disable_triggers, 1},
341                 {"enable-row-security", no_argument, &dopt.enable_row_security, 1},
342                 {"exclude-table-data", required_argument, NULL, 4},
343                 {"if-exists", no_argument, &dopt.if_exists, 1},
344                 {"inserts", no_argument, &dopt.dump_inserts, 1},
345                 {"lock-wait-timeout", required_argument, NULL, 2},
346                 {"no-tablespaces", no_argument, &dopt.outputNoTablespaces, 1},
347                 {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
348                 {"role", required_argument, NULL, 3},
349                 {"section", required_argument, NULL, 5},
350                 {"serializable-deferrable", no_argument, &dopt.serializable_deferrable, 1},
351                 {"snapshot", required_argument, NULL, 6},
352                 {"strict-names", no_argument, &strict_names, 1},
353                 {"use-set-session-authorization", no_argument, &dopt.use_setsessauth, 1},
354                 {"no-publications", no_argument, &dopt.no_publications, 1},
355                 {"no-security-labels", no_argument, &dopt.no_security_labels, 1},
356                 {"no-synchronized-snapshots", no_argument, &dopt.no_synchronized_snapshots, 1},
357                 {"no-unlogged-table-data", no_argument, &dopt.no_unlogged_table_data, 1},
358                 {"no-subscriptions", no_argument, &dopt.no_subscriptions, 1},
359                 {"no-sync", no_argument, NULL, 7},
360
361                 {NULL, 0, NULL, 0}
362         };
363
364         set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
365
366         /*
367          * Initialize what we need for parallel execution, especially for thread
368          * support on Windows.
369          */
370         init_parallel_dump_utils();
371
372         g_verbose = false;
373
374         strcpy(g_comment_start, "-- ");
375         g_comment_end[0] = '\0';
376         strcpy(g_opaque_type, "opaque");
377
378         progname = get_progname(argv[0]);
379
380         if (argc > 1)
381         {
382                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
383                 {
384                         help(progname);
385                         exit_nicely(0);
386                 }
387                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
388                 {
389                         puts("pg_dump (PostgreSQL) " PG_VERSION);
390                         exit_nicely(0);
391                 }
392         }
393
394         InitDumpOptions(&dopt);
395
396         while ((c = getopt_long(argc, argv, "abBcCd:E:f:F:h:j:n:N:oOp:RsS:t:T:U:vwWxZ:",
397                                                         long_options, &optindex)) != -1)
398         {
399                 switch (c)
400                 {
401                         case 'a':                       /* Dump data only */
402                                 dopt.dataOnly = true;
403                                 break;
404
405                         case 'b':                       /* Dump blobs */
406                                 dopt.outputBlobs = true;
407                                 break;
408
409                         case 'B':                       /* Don't dump blobs */
410                                 dopt.dontOutputBlobs = true;
411                                 break;
412
413                         case 'c':                       /* clean (i.e., drop) schema prior to create */
414                                 dopt.outputClean = 1;
415                                 break;
416
417                         case 'C':                       /* Create DB */
418                                 dopt.outputCreateDB = 1;
419                                 break;
420
421                         case 'd':                       /* database name */
422                                 dopt.dbname = pg_strdup(optarg);
423                                 break;
424
425                         case 'E':                       /* Dump encoding */
426                                 dumpencoding = pg_strdup(optarg);
427                                 break;
428
429                         case 'f':
430                                 filename = pg_strdup(optarg);
431                                 break;
432
433                         case 'F':
434                                 format = pg_strdup(optarg);
435                                 break;
436
437                         case 'h':                       /* server host */
438                                 dopt.pghost = pg_strdup(optarg);
439                                 break;
440
441                         case 'j':                       /* number of dump jobs */
442                                 numWorkers = atoi(optarg);
443                                 break;
444
445                         case 'n':                       /* include schema(s) */
446                                 simple_string_list_append(&schema_include_patterns, optarg);
447                                 dopt.include_everything = false;
448                                 break;
449
450                         case 'N':                       /* exclude schema(s) */
451                                 simple_string_list_append(&schema_exclude_patterns, optarg);
452                                 break;
453
454                         case 'o':                       /* Dump oids */
455                                 dopt.oids = true;
456                                 break;
457
458                         case 'O':                       /* Don't reconnect to match owner */
459                                 dopt.outputNoOwner = 1;
460                                 break;
461
462                         case 'p':                       /* server port */
463                                 dopt.pgport = pg_strdup(optarg);
464                                 break;
465
466                         case 'R':
467                                 /* no-op, still accepted for backwards compatibility */
468                                 break;
469
470                         case 's':                       /* dump schema only */
471                                 dopt.schemaOnly = true;
472                                 break;
473
474                         case 'S':                       /* Username for superuser in plain text output */
475                                 dopt.outputSuperuser = pg_strdup(optarg);
476                                 break;
477
478                         case 't':                       /* include table(s) */
479                                 simple_string_list_append(&table_include_patterns, optarg);
480                                 dopt.include_everything = false;
481                                 break;
482
483                         case 'T':                       /* exclude table(s) */
484                                 simple_string_list_append(&table_exclude_patterns, optarg);
485                                 break;
486
487                         case 'U':
488                                 dopt.username = pg_strdup(optarg);
489                                 break;
490
491                         case 'v':                       /* verbose */
492                                 g_verbose = true;
493                                 break;
494
495                         case 'w':
496                                 prompt_password = TRI_NO;
497                                 break;
498
499                         case 'W':
500                                 prompt_password = TRI_YES;
501                                 break;
502
503                         case 'x':                       /* skip ACL dump */
504                                 dopt.aclsSkip = true;
505                                 break;
506
507                         case 'Z':                       /* Compression Level */
508                                 compressLevel = atoi(optarg);
509                                 if (compressLevel < 0 || compressLevel > 9)
510                                 {
511                                         write_msg(NULL, "compression level must be in range 0..9\n");
512                                         exit_nicely(1);
513                                 }
514                                 break;
515
516                         case 0:
517                                 /* This covers the long options. */
518                                 break;
519
520                         case 2:                         /* lock-wait-timeout */
521                                 dopt.lockWaitTimeout = pg_strdup(optarg);
522                                 break;
523
524                         case 3:                         /* SET ROLE */
525                                 use_role = pg_strdup(optarg);
526                                 break;
527
528                         case 4:                         /* exclude table(s) data */
529                                 simple_string_list_append(&tabledata_exclude_patterns, optarg);
530                                 break;
531
532                         case 5:                         /* section */
533                                 set_dump_section(optarg, &dopt.dumpSections);
534                                 break;
535
536                         case 6:                         /* snapshot */
537                                 dumpsnapshot = pg_strdup(optarg);
538                                 break;
539
540                         case 7:                         /* no-sync */
541                                 dosync = false;
542                                 break;
543
544                         default:
545                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
546                                 exit_nicely(1);
547                 }
548         }
549
550         /*
551          * Non-option argument specifies database name as long as it wasn't
552          * already specified with -d / --dbname
553          */
554         if (optind < argc && dopt.dbname == NULL)
555                 dopt.dbname = argv[optind++];
556
557         /* Complain if any arguments remain */
558         if (optind < argc)
559         {
560                 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
561                                 progname, argv[optind]);
562                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
563                                 progname);
564                 exit_nicely(1);
565         }
566
567         /* --column-inserts implies --inserts */
568         if (dopt.column_inserts)
569                 dopt.dump_inserts = 1;
570
571         /*
572          * Binary upgrade mode implies dumping sequence data even in schema-only
573          * mode.  This is not exposed as a separate option, but kept separate
574          * internally for clarity.
575          */
576         if (dopt.binary_upgrade)
577                 dopt.sequence_data = 1;
578
579         if (dopt.dataOnly && dopt.schemaOnly)
580         {
581                 write_msg(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
582                 exit_nicely(1);
583         }
584
585         if (dopt.dataOnly && dopt.outputClean)
586         {
587                 write_msg(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
588                 exit_nicely(1);
589         }
590
591         if (dopt.dump_inserts && dopt.oids)
592         {
593                 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
594                 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
595                 exit_nicely(1);
596         }
597
598         if (dopt.if_exists && !dopt.outputClean)
599                 exit_horribly(NULL, "option --if-exists requires option -c/--clean\n");
600
601         /* Identify archive format to emit */
602         archiveFormat = parseArchiveFormat(format, &archiveMode);
603
604         /* archiveFormat specific setup */
605         if (archiveFormat == archNull)
606                 plainText = 1;
607
608         /* Custom and directory formats are compressed by default, others not */
609         if (compressLevel == -1)
610         {
611 #ifdef HAVE_LIBZ
612                 if (archiveFormat == archCustom || archiveFormat == archDirectory)
613                         compressLevel = Z_DEFAULT_COMPRESSION;
614                 else
615 #endif
616                         compressLevel = 0;
617         }
618
619 #ifndef HAVE_LIBZ
620         if (compressLevel != 0)
621                 write_msg(NULL, "WARNING: requested compression not available in this "
622                                   "installation -- archive will be uncompressed\n");
623         compressLevel = 0;
624 #endif
625
626         /*
627          * On Windows we can only have at most MAXIMUM_WAIT_OBJECTS (= 64 usually)
628          * parallel jobs because that's the maximum limit for the
629          * WaitForMultipleObjects() call.
630          */
631         if (numWorkers <= 0
632 #ifdef WIN32
633                 || numWorkers > MAXIMUM_WAIT_OBJECTS
634 #endif
635                 )
636                 exit_horribly(NULL, "invalid number of parallel jobs\n");
637
638         /* Parallel backup only in the directory archive format so far */
639         if (archiveFormat != archDirectory && numWorkers > 1)
640                 exit_horribly(NULL, "parallel backup only supported by the directory format\n");
641
642         /* Open the output file */
643         fout = CreateArchive(filename, archiveFormat, compressLevel, dosync,
644                                                  archiveMode, setupDumpWorker);
645
646         /* Make dump options accessible right away */
647         SetArchiveOptions(fout, &dopt, NULL);
648
649         /* Register the cleanup hook */
650         on_exit_close_archive(fout);
651
652         /* Let the archiver know how noisy to be */
653         fout->verbose = g_verbose;
654
655         /*
656          * We allow the server to be back to 8.0, and up to any minor release of
657          * our own major version.  (See also version check in pg_dumpall.c.)
658          */
659         fout->minRemoteVersion = 80000;
660         fout->maxRemoteVersion = (PG_VERSION_NUM / 100) * 100 + 99;
661
662         fout->numWorkers = numWorkers;
663
664         /*
665          * Open the database using the Archiver, so it knows about it. Errors mean
666          * death.
667          */
668         ConnectDatabase(fout, dopt.dbname, dopt.pghost, dopt.pgport, dopt.username, prompt_password);
669         setup_connection(fout, dumpencoding, dumpsnapshot, use_role);
670
671         /*
672          * Disable security label support if server version < v9.1.x (prevents
673          * access to nonexistent pg_seclabel catalog)
674          */
675         if (fout->remoteVersion < 90100)
676                 dopt.no_security_labels = 1;
677
678         /*
679          * On hot standby slaves, never try to dump unlogged table data, since it
680          * will just throw an error.
681          */
682         if (fout->isStandby)
683                 dopt.no_unlogged_table_data = true;
684
685         /* Select the appropriate subquery to convert user IDs to names */
686         if (fout->remoteVersion >= 80100)
687                 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
688         else
689                 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
690
691         /* check the version for the synchronized snapshots feature */
692         if (numWorkers > 1 && fout->remoteVersion < 90200
693                 && !dopt.no_synchronized_snapshots)
694                 exit_horribly(NULL,
695                                           "Synchronized snapshots are not supported by this server version.\n"
696                                           "Run with --no-synchronized-snapshots instead if you do not need\n"
697                                           "synchronized snapshots.\n");
698
699         /* check the version when a snapshot is explicitly specified by user */
700         if (dumpsnapshot && fout->remoteVersion < 90200)
701                 exit_horribly(NULL,
702                                           "Exported snapshots are not supported by this server version.\n");
703
704         /*
705          * Find the last built-in OID, if needed (prior to 8.1)
706          *
707          * With 8.1 and above, we can just use FirstNormalObjectId - 1.
708          */
709         if (fout->remoteVersion < 80100)
710                 g_last_builtin_oid = findLastBuiltinOid_V71(fout,
711                                                                                                         PQdb(GetConnection(fout)));
712         else
713                 g_last_builtin_oid = FirstNormalObjectId - 1;
714
715         if (g_verbose)
716                 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
717
718         /* Expand schema selection patterns into OID lists */
719         if (schema_include_patterns.head != NULL)
720         {
721                 expand_schema_name_patterns(fout, &schema_include_patterns,
722                                                                         &schema_include_oids,
723                                                                         strict_names);
724                 if (schema_include_oids.head == NULL)
725                         exit_horribly(NULL, "no matching schemas were found\n");
726         }
727         expand_schema_name_patterns(fout, &schema_exclude_patterns,
728                                                                 &schema_exclude_oids,
729                                                                 false);
730         /* non-matching exclusion patterns aren't an error */
731
732         /* Expand table selection patterns into OID lists */
733         if (table_include_patterns.head != NULL)
734         {
735                 expand_table_name_patterns(fout, &table_include_patterns,
736                                                                    &table_include_oids,
737                                                                    strict_names);
738                 if (table_include_oids.head == NULL)
739                         exit_horribly(NULL, "no matching tables were found\n");
740         }
741         expand_table_name_patterns(fout, &table_exclude_patterns,
742                                                            &table_exclude_oids,
743                                                            false);
744
745         expand_table_name_patterns(fout, &tabledata_exclude_patterns,
746                                                            &tabledata_exclude_oids,
747                                                            false);
748
749         /* non-matching exclusion patterns aren't an error */
750
751         /*
752          * Dumping blobs is the default for dumps where an inclusion switch is not
753          * used (an "include everything" dump).  -B can be used to exclude blobs
754          * from those dumps.  -b can be used to include blobs even when an
755          * inclusion switch is used.
756          *
757          * -s means "schema only" and blobs are data, not schema, so we never
758          * include blobs when -s is used.
759          */
760         if (dopt.include_everything && !dopt.schemaOnly && !dopt.dontOutputBlobs)
761                 dopt.outputBlobs = true;
762
763         /*
764          * Now scan the database and create DumpableObject structs for all the
765          * objects we intend to dump.
766          */
767         tblinfo = getSchemaData(fout, &numTables);
768
769         if (fout->remoteVersion < 80400)
770                 guessConstraintInheritance(tblinfo, numTables);
771
772         if (!dopt.schemaOnly)
773         {
774                 getTableData(&dopt, tblinfo, numTables, dopt.oids, 0);
775                 buildMatViewRefreshDependencies(fout);
776                 if (dopt.dataOnly)
777                         getTableDataFKConstraints();
778         }
779
780         if (dopt.schemaOnly && dopt.sequence_data)
781                 getTableData(&dopt, tblinfo, numTables, dopt.oids, RELKIND_SEQUENCE);
782
783         /*
784          * In binary-upgrade mode, we do not have to worry about the actual blob
785          * data or the associated metadata that resides in the pg_largeobject and
786          * pg_largeobject_metadata tables, respectivly.
787          *
788          * However, we do need to collect blob information as there may be
789          * comments or other information on blobs that we do need to dump out.
790          */
791         if (dopt.outputBlobs || dopt.binary_upgrade)
792                 getBlobs(fout);
793
794         /*
795          * Collect dependency data to assist in ordering the objects.
796          */
797         getDependencies(fout);
798
799         /* Lastly, create dummy objects to represent the section boundaries */
800         boundaryObjs = createBoundaryObjects();
801
802         /* Get pointers to all the known DumpableObjects */
803         getDumpableObjects(&dobjs, &numObjs);
804
805         /*
806          * Add dummy dependencies to enforce the dump section ordering.
807          */
808         addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
809
810         /*
811          * Sort the objects into a safe dump order (no forward references).
812          *
813          * We rely on dependency information to help us determine a safe order, so
814          * the initial sort is mostly for cosmetic purposes: we sort by name to
815          * ensure that logically identical schemas will dump identically.
816          */
817         sortDumpableObjectsByTypeName(dobjs, numObjs);
818
819         /* If we do a parallel dump, we want the largest tables to go first */
820         if (archiveFormat == archDirectory && numWorkers > 1)
821                 sortDataAndIndexObjectsBySize(dobjs, numObjs);
822
823         sortDumpableObjects(dobjs, numObjs,
824                                                 boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
825
826         /*
827          * Create archive TOC entries for all the objects to be dumped, in a safe
828          * order.
829          */
830
831         /* First the special ENCODING and STDSTRINGS entries. */
832         dumpEncoding(fout);
833         dumpStdStrings(fout);
834
835         /* The database item is always next, unless we don't want it at all */
836         if (dopt.include_everything && !dopt.dataOnly)
837                 dumpDatabase(fout);
838
839         /* Now the rearrangeable objects. */
840         for (i = 0; i < numObjs; i++)
841                 dumpDumpableObject(fout, dobjs[i]);
842
843         /*
844          * Set up options info to ensure we dump what we want.
845          */
846         ropt = NewRestoreOptions();
847         ropt->filename = filename;
848
849         /* if you change this list, see dumpOptionsFromRestoreOptions */
850         ropt->dropSchema = dopt.outputClean;
851         ropt->dataOnly = dopt.dataOnly;
852         ropt->schemaOnly = dopt.schemaOnly;
853         ropt->if_exists = dopt.if_exists;
854         ropt->column_inserts = dopt.column_inserts;
855         ropt->dumpSections = dopt.dumpSections;
856         ropt->aclsSkip = dopt.aclsSkip;
857         ropt->superuser = dopt.outputSuperuser;
858         ropt->createDB = dopt.outputCreateDB;
859         ropt->noOwner = dopt.outputNoOwner;
860         ropt->noTablespace = dopt.outputNoTablespaces;
861         ropt->disable_triggers = dopt.disable_triggers;
862         ropt->use_setsessauth = dopt.use_setsessauth;
863         ropt->disable_dollar_quoting = dopt.disable_dollar_quoting;
864         ropt->dump_inserts = dopt.dump_inserts;
865         ropt->no_publications = dopt.no_publications;
866         ropt->no_security_labels = dopt.no_security_labels;
867         ropt->no_subscriptions = dopt.no_subscriptions;
868         ropt->lockWaitTimeout = dopt.lockWaitTimeout;
869         ropt->include_everything = dopt.include_everything;
870         ropt->enable_row_security = dopt.enable_row_security;
871         ropt->sequence_data = dopt.sequence_data;
872         ropt->binary_upgrade = dopt.binary_upgrade;
873
874         if (compressLevel == -1)
875                 ropt->compression = 0;
876         else
877                 ropt->compression = compressLevel;
878
879         ropt->suppressDumpWarnings = true;      /* We've already shown them */
880
881         SetArchiveOptions(fout, &dopt, ropt);
882
883         /* Mark which entries should be output */
884         ProcessArchiveRestoreOptions(fout);
885
886         /*
887          * The archive's TOC entries are now marked as to which ones will actually
888          * be output, so we can set up their dependency lists properly. This isn't
889          * necessary for plain-text output, though.
890          */
891         if (!plainText)
892                 BuildArchiveDependencies(fout);
893
894         /*
895          * And finally we can do the actual output.
896          *
897          * Note: for non-plain-text output formats, the output file is written
898          * inside CloseArchive().  This is, um, bizarre; but not worth changing
899          * right now.
900          */
901         if (plainText)
902                 RestoreArchive(fout);
903
904         CloseArchive(fout);
905
906         exit_nicely(0);
907 }
908
909
910 static void
911 help(const char *progname)
912 {
913         printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
914         printf(_("Usage:\n"));
915         printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
916
917         printf(_("\nGeneral options:\n"));
918         printf(_("  -f, --file=FILENAME          output file or directory name\n"));
919         printf(_("  -F, --format=c|d|t|p         output file format (custom, directory, tar,\n"
920                          "                               plain text (default))\n"));
921         printf(_("  -j, --jobs=NUM               use this many parallel jobs to dump\n"));
922         printf(_("  -v, --verbose                verbose mode\n"));
923         printf(_("  -V, --version                output version information, then exit\n"));
924         printf(_("  -Z, --compress=0-9           compression level for compressed formats\n"));
925         printf(_("  --lock-wait-timeout=TIMEOUT  fail after waiting TIMEOUT for a table lock\n"));
926         printf(_("  --no-sync                    do not wait for changes to be written safely to disk\n"));
927         printf(_("  -?, --help                   show this help, then exit\n"));
928
929         printf(_("\nOptions controlling the output content:\n"));
930         printf(_("  -a, --data-only              dump only the data, not the schema\n"));
931         printf(_("  -b, --blobs                  include large objects in dump\n"));
932         printf(_("  -B, --no-blobs               exclude large objects in dump\n"));
933         printf(_("  -c, --clean                  clean (drop) database objects before recreating\n"));
934         printf(_("  -C, --create                 include commands to create database in dump\n"));
935         printf(_("  -E, --encoding=ENCODING      dump the data in encoding ENCODING\n"));
936         printf(_("  -n, --schema=SCHEMA          dump the named schema(s) only\n"));
937         printf(_("  -N, --exclude-schema=SCHEMA  do NOT dump the named schema(s)\n"));
938         printf(_("  -o, --oids                   include OIDs in dump\n"));
939         printf(_("  -O, --no-owner               skip restoration of object ownership in\n"
940                          "                               plain-text format\n"));
941         printf(_("  -s, --schema-only            dump only the schema, no data\n"));
942         printf(_("  -S, --superuser=NAME         superuser user name to use in plain-text format\n"));
943         printf(_("  -t, --table=TABLE            dump the named table(s) only\n"));
944         printf(_("  -T, --exclude-table=TABLE    do NOT dump the named table(s)\n"));
945         printf(_("  -x, --no-privileges          do not dump privileges (grant/revoke)\n"));
946         printf(_("  --binary-upgrade             for use by upgrade utilities only\n"));
947         printf(_("  --column-inserts             dump data as INSERT commands with column names\n"));
948         printf(_("  --disable-dollar-quoting     disable dollar quoting, use SQL standard quoting\n"));
949         printf(_("  --disable-triggers           disable triggers during data-only restore\n"));
950         printf(_("  --enable-row-security        enable row security (dump only content user has\n"
951                          "                               access to)\n"));
952         printf(_("  --exclude-table-data=TABLE   do NOT dump data for the named table(s)\n"));
953         printf(_("  --if-exists                  use IF EXISTS when dropping objects\n"));
954         printf(_("  --inserts                    dump data as INSERT commands, rather than COPY\n"));
955         printf(_("  --no-publications            do not dump publications\n"));
956         printf(_("  --no-security-labels         do not dump security label assignments\n"));
957         printf(_("  --no-subscriptions           do not dump subscriptions\n"));
958         printf(_("  --no-synchronized-snapshots  do not use synchronized snapshots in parallel jobs\n"));
959         printf(_("  --no-tablespaces             do not dump tablespace assignments\n"));
960         printf(_("  --no-unlogged-table-data     do not dump unlogged table data\n"));
961         printf(_("  --quote-all-identifiers      quote all identifiers, even if not key words\n"));
962         printf(_("  --section=SECTION            dump named section (pre-data, data, or post-data)\n"));
963         printf(_("  --serializable-deferrable    wait until the dump can run without anomalies\n"));
964         printf(_("  --snapshot=SNAPSHOT          use given snapshot for the dump\n"));
965         printf(_("  --strict-names               require table and/or schema include patterns to\n"
966                          "                               match at least one entity each\n"));
967         printf(_("  --use-set-session-authorization\n"
968                          "                               use SET SESSION AUTHORIZATION commands instead of\n"
969                          "                               ALTER OWNER commands to set ownership\n"));
970
971         printf(_("\nConnection options:\n"));
972         printf(_("  -d, --dbname=DBNAME      database to dump\n"));
973         printf(_("  -h, --host=HOSTNAME      database server host or socket directory\n"));
974         printf(_("  -p, --port=PORT          database server port number\n"));
975         printf(_("  -U, --username=NAME      connect as specified database user\n"));
976         printf(_("  -w, --no-password        never prompt for password\n"));
977         printf(_("  -W, --password           force password prompt (should happen automatically)\n"));
978         printf(_("  --role=ROLENAME          do SET ROLE before dump\n"));
979
980         printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
981                          "variable value is used.\n\n"));
982         printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
983 }
984
985 static void
986 setup_connection(Archive *AH, const char *dumpencoding,
987                                  const char *dumpsnapshot, char *use_role)
988 {
989         DumpOptions *dopt = AH->dopt;
990         PGconn     *conn = GetConnection(AH);
991         const char *std_strings;
992
993         /*
994          * Set the client encoding if requested.
995          */
996         if (dumpencoding)
997         {
998                 if (PQsetClientEncoding(conn, dumpencoding) < 0)
999                         exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
1000                                                   dumpencoding);
1001         }
1002
1003         /*
1004          * Get the active encoding and the standard_conforming_strings setting, so
1005          * we know how to escape strings.
1006          */
1007         AH->encoding = PQclientEncoding(conn);
1008
1009         std_strings = PQparameterStatus(conn, "standard_conforming_strings");
1010         AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
1011
1012         /*
1013          * Set the role if requested.  In a parallel dump worker, we'll be passed
1014          * use_role == NULL, but AH->use_role is already set (if user specified it
1015          * originally) and we should use that.
1016          */
1017         if (!use_role && AH->use_role)
1018                 use_role = AH->use_role;
1019
1020         /* Set the role if requested */
1021         if (use_role && AH->remoteVersion >= 80100)
1022         {
1023                 PQExpBuffer query = createPQExpBuffer();
1024
1025                 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
1026                 ExecuteSqlStatement(AH, query->data);
1027                 destroyPQExpBuffer(query);
1028
1029                 /* save it for possible later use by parallel workers */
1030                 if (!AH->use_role)
1031                         AH->use_role = pg_strdup(use_role);
1032         }
1033
1034         /* Set the datestyle to ISO to ensure the dump's portability */
1035         ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
1036
1037         /* Likewise, avoid using sql_standard intervalstyle */
1038         if (AH->remoteVersion >= 80400)
1039                 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
1040
1041         /*
1042          * Set extra_float_digits so that we can dump float data exactly (given
1043          * correctly implemented float I/O code, anyway)
1044          */
1045         if (AH->remoteVersion >= 90000)
1046                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
1047         else
1048                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
1049
1050         /*
1051          * If synchronized scanning is supported, disable it, to prevent
1052          * unpredictable changes in row ordering across a dump and reload.
1053          */
1054         if (AH->remoteVersion >= 80300)
1055                 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
1056
1057         /*
1058          * Disable timeouts if supported.
1059          */
1060         ExecuteSqlStatement(AH, "SET statement_timeout = 0");
1061         if (AH->remoteVersion >= 90300)
1062                 ExecuteSqlStatement(AH, "SET lock_timeout = 0");
1063         if (AH->remoteVersion >= 90600)
1064                 ExecuteSqlStatement(AH, "SET idle_in_transaction_session_timeout = 0");
1065
1066         /*
1067          * Quote all identifiers, if requested.
1068          */
1069         if (quote_all_identifiers && AH->remoteVersion >= 90100)
1070                 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
1071
1072         /*
1073          * Adjust row-security mode, if supported.
1074          */
1075         if (AH->remoteVersion >= 90500)
1076         {
1077                 if (dopt->enable_row_security)
1078                         ExecuteSqlStatement(AH, "SET row_security = on");
1079                 else
1080                         ExecuteSqlStatement(AH, "SET row_security = off");
1081         }
1082
1083         /*
1084          * Start transaction-snapshot mode transaction to dump consistent data.
1085          */
1086         ExecuteSqlStatement(AH, "BEGIN");
1087         if (AH->remoteVersion >= 90100)
1088         {
1089                 /*
1090                  * To support the combination of serializable_deferrable with the jobs
1091                  * option we use REPEATABLE READ for the worker connections that are
1092                  * passed a snapshot.  As long as the snapshot is acquired in a
1093                  * SERIALIZABLE, READ ONLY, DEFERRABLE transaction, its use within a
1094                  * REPEATABLE READ transaction provides the appropriate integrity
1095                  * guarantees.  This is a kluge, but safe for back-patching.
1096                  */
1097                 if (dopt->serializable_deferrable && AH->sync_snapshot_id == NULL)
1098                         ExecuteSqlStatement(AH,
1099                                                                 "SET TRANSACTION ISOLATION LEVEL "
1100                                                                 "SERIALIZABLE, READ ONLY, DEFERRABLE");
1101                 else
1102                         ExecuteSqlStatement(AH,
1103                                                                 "SET TRANSACTION ISOLATION LEVEL "
1104                                                                 "REPEATABLE READ, READ ONLY");
1105         }
1106         else
1107         {
1108                 ExecuteSqlStatement(AH,
1109                                                         "SET TRANSACTION ISOLATION LEVEL "
1110                                                         "SERIALIZABLE, READ ONLY");
1111         }
1112
1113         /*
1114          * If user specified a snapshot to use, select that.  In a parallel dump
1115          * worker, we'll be passed dumpsnapshot == NULL, but AH->sync_snapshot_id
1116          * is already set (if the server can handle it) and we should use that.
1117          */
1118         if (dumpsnapshot)
1119                 AH->sync_snapshot_id = pg_strdup(dumpsnapshot);
1120
1121         if (AH->sync_snapshot_id)
1122         {
1123                 PQExpBuffer query = createPQExpBuffer();
1124
1125                 appendPQExpBuffer(query, "SET TRANSACTION SNAPSHOT ");
1126                 appendStringLiteralConn(query, AH->sync_snapshot_id, conn);
1127                 ExecuteSqlStatement(AH, query->data);
1128                 destroyPQExpBuffer(query);
1129         }
1130         else if (AH->numWorkers > 1 &&
1131                          AH->remoteVersion >= 90200 &&
1132                          !dopt->no_synchronized_snapshots)
1133         {
1134                 if (AH->isStandby)
1135                         exit_horribly(NULL,
1136                                                   "Synchronized snapshots are not supported on standby servers.\n"
1137                                                   "Run with --no-synchronized-snapshots instead if you do not need\n"
1138                                                   "synchronized snapshots.\n");
1139
1140
1141                 AH->sync_snapshot_id = get_synchronized_snapshot(AH);
1142         }
1143 }
1144
1145 /* Set up connection for a parallel worker process */
1146 static void
1147 setupDumpWorker(Archive *AH)
1148 {
1149         /*
1150          * We want to re-select all the same values the master connection is
1151          * using.  We'll have inherited directly-usable values in
1152          * AH->sync_snapshot_id and AH->use_role, but we need to translate the
1153          * inherited encoding value back to a string to pass to setup_connection.
1154          */
1155         setup_connection(AH,
1156                                          pg_encoding_to_char(AH->encoding),
1157                                          NULL,
1158                                          NULL);
1159 }
1160
1161 static char *
1162 get_synchronized_snapshot(Archive *fout)
1163 {
1164         char       *query = "SELECT pg_catalog.pg_export_snapshot()";
1165         char       *result;
1166         PGresult   *res;
1167
1168         res = ExecuteSqlQueryForSingleRow(fout, query);
1169         result = pg_strdup(PQgetvalue(res, 0, 0));
1170         PQclear(res);
1171
1172         return result;
1173 }
1174
1175 static ArchiveFormat
1176 parseArchiveFormat(const char *format, ArchiveMode *mode)
1177 {
1178         ArchiveFormat archiveFormat;
1179
1180         *mode = archModeWrite;
1181
1182         if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
1183         {
1184                 /* This is used by pg_dumpall, and is not documented */
1185                 archiveFormat = archNull;
1186                 *mode = archModeAppend;
1187         }
1188         else if (pg_strcasecmp(format, "c") == 0)
1189                 archiveFormat = archCustom;
1190         else if (pg_strcasecmp(format, "custom") == 0)
1191                 archiveFormat = archCustom;
1192         else if (pg_strcasecmp(format, "d") == 0)
1193                 archiveFormat = archDirectory;
1194         else if (pg_strcasecmp(format, "directory") == 0)
1195                 archiveFormat = archDirectory;
1196         else if (pg_strcasecmp(format, "p") == 0)
1197                 archiveFormat = archNull;
1198         else if (pg_strcasecmp(format, "plain") == 0)
1199                 archiveFormat = archNull;
1200         else if (pg_strcasecmp(format, "t") == 0)
1201                 archiveFormat = archTar;
1202         else if (pg_strcasecmp(format, "tar") == 0)
1203                 archiveFormat = archTar;
1204         else
1205                 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
1206         return archiveFormat;
1207 }
1208
1209 /*
1210  * Find the OIDs of all schemas matching the given list of patterns,
1211  * and append them to the given OID list.
1212  */
1213 static void
1214 expand_schema_name_patterns(Archive *fout,
1215                                                         SimpleStringList *patterns,
1216                                                         SimpleOidList *oids,
1217                                                         bool strict_names)
1218 {
1219         PQExpBuffer query;
1220         PGresult   *res;
1221         SimpleStringListCell *cell;
1222         int                     i;
1223
1224         if (patterns->head == NULL)
1225                 return;                                 /* nothing to do */
1226
1227         query = createPQExpBuffer();
1228
1229         /*
1230          * The loop below runs multiple SELECTs might sometimes result in
1231          * duplicate entries in the OID list, but we don't care.
1232          */
1233
1234         for (cell = patterns->head; cell; cell = cell->next)
1235         {
1236                 appendPQExpBuffer(query,
1237                                                   "SELECT oid FROM pg_catalog.pg_namespace n\n");
1238                 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1239                                                           false, NULL, "n.nspname", NULL, NULL);
1240
1241                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1242                 if (strict_names && PQntuples(res) == 0)
1243                         exit_horribly(NULL, "no matching schemas were found for pattern \"%s\"\n", cell->val);
1244
1245                 for (i = 0; i < PQntuples(res); i++)
1246                 {
1247                         simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1248                 }
1249
1250                 PQclear(res);
1251                 resetPQExpBuffer(query);
1252         }
1253
1254         destroyPQExpBuffer(query);
1255 }
1256
1257 /*
1258  * Find the OIDs of all tables matching the given list of patterns,
1259  * and append them to the given OID list.
1260  */
1261 static void
1262 expand_table_name_patterns(Archive *fout,
1263                                                    SimpleStringList *patterns, SimpleOidList *oids,
1264                                                    bool strict_names)
1265 {
1266         PQExpBuffer query;
1267         PGresult   *res;
1268         SimpleStringListCell *cell;
1269         int                     i;
1270
1271         if (patterns->head == NULL)
1272                 return;                                 /* nothing to do */
1273
1274         query = createPQExpBuffer();
1275
1276         /*
1277          * this might sometimes result in duplicate entries in the OID list, but
1278          * we don't care.
1279          */
1280
1281         for (cell = patterns->head; cell; cell = cell->next)
1282         {
1283                 appendPQExpBuffer(query,
1284                                                   "SELECT c.oid"
1285                                                   "\nFROM pg_catalog.pg_class c"
1286                                                   "\n     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1287                                                   "\nWHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c')\n",
1288                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1289                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
1290                                                   RELKIND_PARTITIONED_TABLE);
1291                 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1292                                                           false, "n.nspname", "c.relname", NULL,
1293                                                           "pg_catalog.pg_table_is_visible(c.oid)");
1294
1295                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1296                 if (strict_names && PQntuples(res) == 0)
1297                         exit_horribly(NULL, "no matching tables were found for pattern \"%s\"\n", cell->val);
1298
1299                 for (i = 0; i < PQntuples(res); i++)
1300                 {
1301                         simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1302                 }
1303
1304                 PQclear(res);
1305                 resetPQExpBuffer(query);
1306         }
1307
1308         destroyPQExpBuffer(query);
1309 }
1310
1311 /*
1312  * checkExtensionMembership
1313  *              Determine whether object is an extension member, and if so,
1314  *              record an appropriate dependency and set the object's dump flag.
1315  *
1316  * It's important to call this for each object that could be an extension
1317  * member.  Generally, we integrate this with determining the object's
1318  * to-be-dumped-ness, since extension membership overrides other rules for that.
1319  *
1320  * Returns true if object is an extension member, else false.
1321  */
1322 static bool
1323 checkExtensionMembership(DumpableObject *dobj, Archive *fout)
1324 {
1325         ExtensionInfo *ext = findOwningExtension(dobj->catId);
1326
1327         if (ext == NULL)
1328                 return false;
1329
1330         dobj->ext_member = true;
1331
1332         /* Record dependency so that getDependencies needn't deal with that */
1333         addObjectDependency(dobj, ext->dobj.dumpId);
1334
1335         /*
1336          * In 9.6 and above, mark the member object to have any non-initial ACL,
1337          * policies, and security labels dumped.
1338          *
1339          * Note that any initial ACLs (see pg_init_privs) will be removed when we
1340          * extract the information about the object.  We don't provide support for
1341          * initial policies and security labels and it seems unlikely for those to
1342          * ever exist, but we may have to revisit this later.
1343          *
1344          * Prior to 9.6, we do not include any extension member components.
1345          *
1346          * In binary upgrades, we still dump all components of the members
1347          * individually, since the idea is to exactly reproduce the database
1348          * contents rather than replace the extension contents with something
1349          * different.
1350          */
1351         if (fout->dopt->binary_upgrade)
1352                 dobj->dump = ext->dobj.dump;
1353         else
1354         {
1355                 if (fout->remoteVersion < 90600)
1356                         dobj->dump = DUMP_COMPONENT_NONE;
1357                 else
1358                         dobj->dump = ext->dobj.dump_contains & (DUMP_COMPONENT_ACL |
1359                                                                                                         DUMP_COMPONENT_SECLABEL |
1360                                                                                                         DUMP_COMPONENT_POLICY);
1361         }
1362
1363         return true;
1364 }
1365
1366 /*
1367  * selectDumpableNamespace: policy-setting subroutine
1368  *              Mark a namespace as to be dumped or not
1369  */
1370 static void
1371 selectDumpableNamespace(NamespaceInfo *nsinfo, Archive *fout)
1372 {
1373         /*
1374          * If specific tables are being dumped, do not dump any complete
1375          * namespaces. If specific namespaces are being dumped, dump just those
1376          * namespaces. Otherwise, dump all non-system namespaces.
1377          */
1378         if (table_include_oids.head != NULL)
1379                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1380         else if (schema_include_oids.head != NULL)
1381                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump =
1382                         simple_oid_list_member(&schema_include_oids,
1383                                                                    nsinfo->dobj.catId.oid) ?
1384                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1385         else if (fout->remoteVersion >= 90600 &&
1386                          strcmp(nsinfo->dobj.name, "pg_catalog") == 0)
1387         {
1388                 /*
1389                  * In 9.6 and above, we dump out any ACLs defined in pg_catalog, if
1390                  * they are interesting (and not the original ACLs which were set at
1391                  * initdb time, see pg_init_privs).
1392                  */
1393                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1394         }
1395         else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1396                          strcmp(nsinfo->dobj.name, "information_schema") == 0)
1397         {
1398                 /* Other system schemas don't get dumped */
1399                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1400         }
1401         else
1402                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ALL;
1403
1404         /*
1405          * In any case, a namespace can be excluded by an exclusion switch
1406          */
1407         if (nsinfo->dobj.dump_contains &&
1408                 simple_oid_list_member(&schema_exclude_oids,
1409                                                            nsinfo->dobj.catId.oid))
1410                 nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1411
1412         /*
1413          * If the schema belongs to an extension, allow extension membership to
1414          * override the dump decision for the schema itself.  However, this does
1415          * not change dump_contains, so this won't change what we do with objects
1416          * within the schema.  (If they belong to the extension, they'll get
1417          * suppressed by it, otherwise not.)
1418          */
1419         (void) checkExtensionMembership(&nsinfo->dobj, fout);
1420 }
1421
1422 /*
1423  * selectDumpableTable: policy-setting subroutine
1424  *              Mark a table as to be dumped or not
1425  */
1426 static void
1427 selectDumpableTable(TableInfo *tbinfo, Archive *fout)
1428 {
1429         if (checkExtensionMembership(&tbinfo->dobj, fout))
1430                 return;                                 /* extension membership overrides all else */
1431
1432         /*
1433          * If specific tables are being dumped, dump just those tables; else, dump
1434          * according to the parent namespace's dump flag.
1435          */
1436         if (table_include_oids.head != NULL)
1437                 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1438                                                                                                    tbinfo->dobj.catId.oid) ?
1439                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1440         else
1441                 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump_contains;
1442
1443         /*
1444          * In any case, a table can be excluded by an exclusion switch
1445          */
1446         if (tbinfo->dobj.dump &&
1447                 simple_oid_list_member(&table_exclude_oids,
1448                                                            tbinfo->dobj.catId.oid))
1449                 tbinfo->dobj.dump = DUMP_COMPONENT_NONE;
1450 }
1451
1452 /*
1453  * selectDumpableType: policy-setting subroutine
1454  *              Mark a type as to be dumped or not
1455  *
1456  * If it's a table's rowtype or an autogenerated array type, we also apply a
1457  * special type code to facilitate sorting into the desired order.  (We don't
1458  * want to consider those to be ordinary types because that would bring tables
1459  * up into the datatype part of the dump order.)  We still set the object's
1460  * dump flag; that's not going to cause the dummy type to be dumped, but we
1461  * need it so that casts involving such types will be dumped correctly -- see
1462  * dumpCast.  This means the flag should be set the same as for the underlying
1463  * object (the table or base type).
1464  */
1465 static void
1466 selectDumpableType(TypeInfo *tyinfo, Archive *fout)
1467 {
1468         /* skip complex types, except for standalone composite types */
1469         if (OidIsValid(tyinfo->typrelid) &&
1470                 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1471         {
1472                 TableInfo  *tytable = findTableByOid(tyinfo->typrelid);
1473
1474                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1475                 if (tytable != NULL)
1476                         tyinfo->dobj.dump = tytable->dobj.dump;
1477                 else
1478                         tyinfo->dobj.dump = DUMP_COMPONENT_NONE;
1479                 return;
1480         }
1481
1482         /* skip auto-generated array types */
1483         if (tyinfo->isArray)
1484         {
1485                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1486
1487                 /*
1488                  * Fall through to set the dump flag; we assume that the subsequent
1489                  * rules will do the same thing as they would for the array's base
1490                  * type.  (We cannot reliably look up the base type here, since
1491                  * getTypes may not have processed it yet.)
1492                  */
1493         }
1494
1495         if (checkExtensionMembership(&tyinfo->dobj, fout))
1496                 return;                                 /* extension membership overrides all else */
1497
1498         /* Dump based on if the contents of the namespace are being dumped */
1499         tyinfo->dobj.dump = tyinfo->dobj.namespace->dobj.dump_contains;
1500 }
1501
1502 /*
1503  * selectDumpableDefaultACL: policy-setting subroutine
1504  *              Mark a default ACL as to be dumped or not
1505  *
1506  * For per-schema default ACLs, dump if the schema is to be dumped.
1507  * Otherwise dump if we are dumping "everything".  Note that dataOnly
1508  * and aclsSkip are checked separately.
1509  */
1510 static void
1511 selectDumpableDefaultACL(DefaultACLInfo *dinfo, DumpOptions *dopt)
1512 {
1513         /* Default ACLs can't be extension members */
1514
1515         if (dinfo->dobj.namespace)
1516                 /* default ACLs are considered part of the namespace */
1517                 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump_contains;
1518         else
1519                 dinfo->dobj.dump = dopt->include_everything ?
1520                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1521 }
1522
1523 /*
1524  * selectDumpableCast: policy-setting subroutine
1525  *              Mark a cast as to be dumped or not
1526  *
1527  * Casts do not belong to any particular namespace (since they haven't got
1528  * names), nor do they have identifiable owners.  To distinguish user-defined
1529  * casts from built-in ones, we must resort to checking whether the cast's
1530  * OID is in the range reserved for initdb.
1531  */
1532 static void
1533 selectDumpableCast(CastInfo *cast, Archive *fout)
1534 {
1535         if (checkExtensionMembership(&cast->dobj, fout))
1536                 return;                                 /* extension membership overrides all else */
1537
1538         /*
1539          * This would be DUMP_COMPONENT_ACL for from-initdb casts, but they do not
1540          * support ACLs currently.
1541          */
1542         if (cast->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1543                 cast->dobj.dump = DUMP_COMPONENT_NONE;
1544         else
1545                 cast->dobj.dump = fout->dopt->include_everything ?
1546                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1547 }
1548
1549 /*
1550  * selectDumpableProcLang: policy-setting subroutine
1551  *              Mark a procedural language as to be dumped or not
1552  *
1553  * Procedural languages do not belong to any particular namespace.  To
1554  * identify built-in languages, we must resort to checking whether the
1555  * language's OID is in the range reserved for initdb.
1556  */
1557 static void
1558 selectDumpableProcLang(ProcLangInfo *plang, Archive *fout)
1559 {
1560         if (checkExtensionMembership(&plang->dobj, fout))
1561                 return;                                 /* extension membership overrides all else */
1562
1563         /*
1564          * Only include procedural languages when we are dumping everything.
1565          *
1566          * For from-initdb procedural languages, only include ACLs, as we do for
1567          * the pg_catalog namespace.  We need this because procedural languages do
1568          * not live in any namespace.
1569          */
1570         if (!fout->dopt->include_everything)
1571                 plang->dobj.dump = DUMP_COMPONENT_NONE;
1572         else
1573         {
1574                 if (plang->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1575                         plang->dobj.dump = fout->remoteVersion < 90600 ?
1576                                 DUMP_COMPONENT_NONE : DUMP_COMPONENT_ACL;
1577                 else
1578                         plang->dobj.dump = DUMP_COMPONENT_ALL;
1579         }
1580 }
1581
1582 /*
1583  * selectDumpableAccessMethod: policy-setting subroutine
1584  *              Mark an access method as to be dumped or not
1585  *
1586  * Access methods do not belong to any particular namespace.  To identify
1587  * built-in access methods, we must resort to checking whether the
1588  * method's OID is in the range reserved for initdb.
1589  */
1590 static void
1591 selectDumpableAccessMethod(AccessMethodInfo *method, Archive *fout)
1592 {
1593         if (checkExtensionMembership(&method->dobj, fout))
1594                 return;                                 /* extension membership overrides all else */
1595
1596         /*
1597          * This would be DUMP_COMPONENT_ACL for from-initdb access methods, but
1598          * they do not support ACLs currently.
1599          */
1600         if (method->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1601                 method->dobj.dump = DUMP_COMPONENT_NONE;
1602         else
1603                 method->dobj.dump = fout->dopt->include_everything ?
1604                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1605 }
1606
1607 /*
1608  * selectDumpableExtension: policy-setting subroutine
1609  *              Mark an extension as to be dumped or not
1610  *
1611  * Normally, we dump all extensions, or none of them if include_everything
1612  * is false (i.e., a --schema or --table switch was given).  However, in
1613  * binary-upgrade mode it's necessary to skip built-in extensions, since we
1614  * assume those will already be installed in the target database.  We identify
1615  * such extensions by their having OIDs in the range reserved for initdb.
1616  */
1617 static void
1618 selectDumpableExtension(ExtensionInfo *extinfo, DumpOptions *dopt)
1619 {
1620         /*
1621          * Use DUMP_COMPONENT_ACL for from-initdb extensions, to allow users to
1622          * change permissions on those objects, if they wish to, and have those
1623          * changes preserved.
1624          */
1625         if (dopt->binary_upgrade && extinfo->dobj.catId.oid <= (Oid) g_last_builtin_oid)
1626                 extinfo->dobj.dump = extinfo->dobj.dump_contains = DUMP_COMPONENT_ACL;
1627         else
1628                 extinfo->dobj.dump = extinfo->dobj.dump_contains =
1629                         dopt->include_everything ? DUMP_COMPONENT_ALL :
1630                         DUMP_COMPONENT_NONE;
1631 }
1632
1633 /*
1634  * selectDumpablePublicationTable: policy-setting subroutine
1635  *              Mark a publication table as to be dumped or not
1636  *
1637  * Publication tables have schemas, but those are ignored in decision making,
1638  * because publications are only dumped when we are dumping everything.
1639  */
1640 static void
1641 selectDumpablePublicationTable(DumpableObject *dobj, Archive *fout)
1642 {
1643         if (checkExtensionMembership(dobj, fout))
1644                 return;                                 /* extension membership overrides all else */
1645
1646         dobj->dump = fout->dopt->include_everything ?
1647                 DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1648 }
1649
1650 /*
1651  * selectDumpableObject: policy-setting subroutine
1652  *              Mark a generic dumpable object as to be dumped or not
1653  *
1654  * Use this only for object types without a special-case routine above.
1655  */
1656 static void
1657 selectDumpableObject(DumpableObject *dobj, Archive *fout)
1658 {
1659         if (checkExtensionMembership(dobj, fout))
1660                 return;                                 /* extension membership overrides all else */
1661
1662         /*
1663          * Default policy is to dump if parent namespace is dumpable, or for
1664          * non-namespace-associated items, dump if we're dumping "everything".
1665          */
1666         if (dobj->namespace)
1667                 dobj->dump = dobj->namespace->dobj.dump_contains;
1668         else
1669                 dobj->dump = fout->dopt->include_everything ?
1670                         DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1671 }
1672
1673 /*
1674  *      Dump a table's contents for loading using the COPY command
1675  *      - this routine is called by the Archiver when it wants the table
1676  *        to be dumped.
1677  */
1678
1679 static int
1680 dumpTableData_copy(Archive *fout, void *dcontext)
1681 {
1682         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1683         TableInfo  *tbinfo = tdinfo->tdtable;
1684         const char *classname = tbinfo->dobj.name;
1685         const bool      hasoids = tbinfo->hasoids;
1686         const bool      oids = tdinfo->oids;
1687         PQExpBuffer q = createPQExpBuffer();
1688
1689         /*
1690          * Note: can't use getThreadLocalPQExpBuffer() here, we're calling fmtId
1691          * which uses it already.
1692          */
1693         PQExpBuffer clistBuf = createPQExpBuffer();
1694         PGconn     *conn = GetConnection(fout);
1695         PGresult   *res;
1696         int                     ret;
1697         char       *copybuf;
1698         const char *column_list;
1699
1700         if (g_verbose)
1701                 write_msg(NULL, "dumping contents of table \"%s.%s\"\n",
1702                                   tbinfo->dobj.namespace->dobj.name, classname);
1703
1704         /*
1705          * Make sure we are in proper schema.  We will qualify the table name
1706          * below anyway (in case its name conflicts with a pg_catalog table); but
1707          * this ensures reproducible results in case the table contains regproc,
1708          * regclass, etc columns.
1709          */
1710         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1711
1712         /*
1713          * Specify the column list explicitly so that we have no possibility of
1714          * retrieving data in the wrong column order.  (The default column
1715          * ordering of COPY will not be what we want in certain corner cases
1716          * involving ADD COLUMN and inheritance.)
1717          */
1718         column_list = fmtCopyColumnList(tbinfo, clistBuf);
1719
1720         if (oids && hasoids)
1721         {
1722                 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1723                                                   fmtQualifiedId(fout->remoteVersion,
1724                                                                                  tbinfo->dobj.namespace->dobj.name,
1725                                                                                  classname),
1726                                                   column_list);
1727         }
1728         else if (tdinfo->filtercond)
1729         {
1730                 /* Note: this syntax is only supported in 8.2 and up */
1731                 appendPQExpBufferStr(q, "COPY (SELECT ");
1732                 /* klugery to get rid of parens in column list */
1733                 if (strlen(column_list) > 2)
1734                 {
1735                         appendPQExpBufferStr(q, column_list + 1);
1736                         q->data[q->len - 1] = ' ';
1737                 }
1738                 else
1739                         appendPQExpBufferStr(q, "* ");
1740                 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1741                                                   fmtQualifiedId(fout->remoteVersion,
1742                                                                                  tbinfo->dobj.namespace->dobj.name,
1743                                                                                  classname),
1744                                                   tdinfo->filtercond);
1745         }
1746         else
1747         {
1748                 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1749                                                   fmtQualifiedId(fout->remoteVersion,
1750                                                                                  tbinfo->dobj.namespace->dobj.name,
1751                                                                                  classname),
1752                                                   column_list);
1753         }
1754         res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1755         PQclear(res);
1756         destroyPQExpBuffer(clistBuf);
1757
1758         for (;;)
1759         {
1760                 ret = PQgetCopyData(conn, &copybuf, 0);
1761
1762                 if (ret < 0)
1763                         break;                          /* done or error */
1764
1765                 if (copybuf)
1766                 {
1767                         WriteData(fout, copybuf, ret);
1768                         PQfreemem(copybuf);
1769                 }
1770
1771                 /* ----------
1772                  * THROTTLE:
1773                  *
1774                  * There was considerable discussion in late July, 2000 regarding
1775                  * slowing down pg_dump when backing up large tables. Users with both
1776                  * slow & fast (multi-processor) machines experienced performance
1777                  * degradation when doing a backup.
1778                  *
1779                  * Initial attempts based on sleeping for a number of ms for each ms
1780                  * of work were deemed too complex, then a simple 'sleep in each loop'
1781                  * implementation was suggested. The latter failed because the loop
1782                  * was too tight. Finally, the following was implemented:
1783                  *
1784                  * If throttle is non-zero, then
1785                  *              See how long since the last sleep.
1786                  *              Work out how long to sleep (based on ratio).
1787                  *              If sleep is more than 100ms, then
1788                  *                      sleep
1789                  *                      reset timer
1790                  *              EndIf
1791                  * EndIf
1792                  *
1793                  * where the throttle value was the number of ms to sleep per ms of
1794                  * work. The calculation was done in each loop.
1795                  *
1796                  * Most of the hard work is done in the backend, and this solution
1797                  * still did not work particularly well: on slow machines, the ratio
1798                  * was 50:1, and on medium paced machines, 1:1, and on fast
1799                  * multi-processor machines, it had little or no effect, for reasons
1800                  * that were unclear.
1801                  *
1802                  * Further discussion ensued, and the proposal was dropped.
1803                  *
1804                  * For those people who want this feature, it can be implemented using
1805                  * gettimeofday in each loop, calculating the time since last sleep,
1806                  * multiplying that by the sleep ratio, then if the result is more
1807                  * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1808                  * function to sleep for a subsecond period ie.
1809                  *
1810                  * select(0, NULL, NULL, NULL, &tvi);
1811                  *
1812                  * This will return after the interval specified in the structure tvi.
1813                  * Finally, call gettimeofday again to save the 'last sleep time'.
1814                  * ----------
1815                  */
1816         }
1817         archprintf(fout, "\\.\n\n\n");
1818
1819         if (ret == -2)
1820         {
1821                 /* copy data transfer failed */
1822                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1823                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1824                 write_msg(NULL, "The command was: %s\n", q->data);
1825                 exit_nicely(1);
1826         }
1827
1828         /* Check command status and return to normal libpq state */
1829         res = PQgetResult(conn);
1830         if (PQresultStatus(res) != PGRES_COMMAND_OK)
1831         {
1832                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1833                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1834                 write_msg(NULL, "The command was: %s\n", q->data);
1835                 exit_nicely(1);
1836         }
1837         PQclear(res);
1838
1839         /* Do this to ensure we've pumped libpq back to idle state */
1840         if (PQgetResult(conn) != NULL)
1841                 write_msg(NULL, "WARNING: unexpected extra results during COPY of table \"%s\"\n",
1842                                   classname);
1843
1844         destroyPQExpBuffer(q);
1845         return 1;
1846 }
1847
1848 /*
1849  * Dump table data using INSERT commands.
1850  *
1851  * Caution: when we restore from an archive file direct to database, the
1852  * INSERT commands emitted by this function have to be parsed by
1853  * pg_backup_db.c's ExecuteSimpleCommands(), which will not handle comments,
1854  * E'' strings, or dollar-quoted strings.  So don't emit anything like that.
1855  */
1856 static int
1857 dumpTableData_insert(Archive *fout, void *dcontext)
1858 {
1859         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1860         TableInfo  *tbinfo = tdinfo->tdtable;
1861         const char *classname = tbinfo->dobj.name;
1862         DumpOptions *dopt = fout->dopt;
1863         PQExpBuffer q = createPQExpBuffer();
1864         PQExpBuffer insertStmt = NULL;
1865         PGresult   *res;
1866         int                     tuple;
1867         int                     nfields;
1868         int                     field;
1869
1870         /*
1871          * Make sure we are in proper schema.  We will qualify the table name
1872          * below anyway (in case its name conflicts with a pg_catalog table); but
1873          * this ensures reproducible results in case the table contains regproc,
1874          * regclass, etc columns.
1875          */
1876         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1877
1878         appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1879                                           "SELECT * FROM ONLY %s",
1880                                           fmtQualifiedId(fout->remoteVersion,
1881                                                                          tbinfo->dobj.namespace->dobj.name,
1882                                                                          classname));
1883         if (tdinfo->filtercond)
1884                 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1885
1886         ExecuteSqlStatement(fout, q->data);
1887
1888         while (1)
1889         {
1890                 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1891                                                           PGRES_TUPLES_OK);
1892                 nfields = PQnfields(res);
1893                 for (tuple = 0; tuple < PQntuples(res); tuple++)
1894                 {
1895                         /*
1896                          * First time through, we build as much of the INSERT statement as
1897                          * possible in "insertStmt", which we can then just print for each
1898                          * line. If the table happens to have zero columns then this will
1899                          * be a complete statement, otherwise it will end in "VALUES(" and
1900                          * be ready to have the row's column values appended.
1901                          */
1902                         if (insertStmt == NULL)
1903                         {
1904                                 insertStmt = createPQExpBuffer();
1905                                 appendPQExpBuffer(insertStmt, "INSERT INTO %s ",
1906                                                                   fmtId(classname));
1907
1908                                 /* corner case for zero-column table */
1909                                 if (nfields == 0)
1910                                 {
1911                                         appendPQExpBufferStr(insertStmt, "DEFAULT VALUES;\n");
1912                                 }
1913                                 else
1914                                 {
1915                                         /* append the list of column names if required */
1916                                         if (dopt->column_inserts)
1917                                         {
1918                                                 appendPQExpBufferChar(insertStmt, '(');
1919                                                 for (field = 0; field < nfields; field++)
1920                                                 {
1921                                                         if (field > 0)
1922                                                                 appendPQExpBufferStr(insertStmt, ", ");
1923                                                         appendPQExpBufferStr(insertStmt,
1924                                                                                                  fmtId(PQfname(res, field)));
1925                                                 }
1926                                                 appendPQExpBufferStr(insertStmt, ") ");
1927                                         }
1928
1929                                         if (tbinfo->needs_override)
1930                                                 appendPQExpBufferStr(insertStmt, "OVERRIDING SYSTEM VALUE ");
1931
1932                                         appendPQExpBufferStr(insertStmt, "VALUES (");
1933                                 }
1934                         }
1935
1936                         archputs(insertStmt->data, fout);
1937
1938                         /* if it is zero-column table then we're done */
1939                         if (nfields == 0)
1940                                 continue;
1941
1942                         for (field = 0; field < nfields; field++)
1943                         {
1944                                 if (field > 0)
1945                                         archputs(", ", fout);
1946                                 if (PQgetisnull(res, tuple, field))
1947                                 {
1948                                         archputs("NULL", fout);
1949                                         continue;
1950                                 }
1951
1952                                 /* XXX This code is partially duplicated in ruleutils.c */
1953                                 switch (PQftype(res, field))
1954                                 {
1955                                         case INT2OID:
1956                                         case INT4OID:
1957                                         case INT8OID:
1958                                         case OIDOID:
1959                                         case FLOAT4OID:
1960                                         case FLOAT8OID:
1961                                         case NUMERICOID:
1962                                                 {
1963                                                         /*
1964                                                          * These types are printed without quotes unless
1965                                                          * they contain values that aren't accepted by the
1966                                                          * scanner unquoted (e.g., 'NaN').  Note that
1967                                                          * strtod() and friends might accept NaN, so we
1968                                                          * can't use that to test.
1969                                                          *
1970                                                          * In reality we only need to defend against
1971                                                          * infinity and NaN, so we need not get too crazy
1972                                                          * about pattern matching here.
1973                                                          */
1974                                                         const char *s = PQgetvalue(res, tuple, field);
1975
1976                                                         if (strspn(s, "0123456789 +-eE.") == strlen(s))
1977                                                                 archputs(s, fout);
1978                                                         else
1979                                                                 archprintf(fout, "'%s'", s);
1980                                                 }
1981                                                 break;
1982
1983                                         case BITOID:
1984                                         case VARBITOID:
1985                                                 archprintf(fout, "B'%s'",
1986                                                                    PQgetvalue(res, tuple, field));
1987                                                 break;
1988
1989                                         case BOOLOID:
1990                                                 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1991                                                         archputs("true", fout);
1992                                                 else
1993                                                         archputs("false", fout);
1994                                                 break;
1995
1996                                         default:
1997                                                 /* All other types are printed as string literals. */
1998                                                 resetPQExpBuffer(q);
1999                                                 appendStringLiteralAH(q,
2000                                                                                           PQgetvalue(res, tuple, field),
2001                                                                                           fout);
2002                                                 archputs(q->data, fout);
2003                                                 break;
2004                                 }
2005                         }
2006                         archputs(");\n", fout);
2007                 }
2008
2009                 if (PQntuples(res) <= 0)
2010                 {
2011                         PQclear(res);
2012                         break;
2013                 }
2014                 PQclear(res);
2015         }
2016
2017         archputs("\n\n", fout);
2018
2019         ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
2020
2021         destroyPQExpBuffer(q);
2022         if (insertStmt != NULL)
2023                 destroyPQExpBuffer(insertStmt);
2024
2025         return 1;
2026 }
2027
2028
2029 /*
2030  * dumpTableData -
2031  *        dump the contents of a single table
2032  *
2033  * Actually, this just makes an ArchiveEntry for the table contents.
2034  */
2035 static void
2036 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
2037 {
2038         DumpOptions *dopt = fout->dopt;
2039         TableInfo  *tbinfo = tdinfo->tdtable;
2040         PQExpBuffer copyBuf = createPQExpBuffer();
2041         PQExpBuffer clistBuf = createPQExpBuffer();
2042         DataDumperPtr dumpFn;
2043         char       *copyStmt;
2044
2045         if (!dopt->dump_inserts)
2046         {
2047                 /* Dump/restore using COPY */
2048                 dumpFn = dumpTableData_copy;
2049                 /* must use 2 steps here 'cause fmtId is nonreentrant */
2050                 appendPQExpBuffer(copyBuf, "COPY %s ",
2051                                                   fmtId(tbinfo->dobj.name));
2052                 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
2053                                                   fmtCopyColumnList(tbinfo, clistBuf),
2054                                                   (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
2055                 copyStmt = copyBuf->data;
2056         }
2057         else
2058         {
2059                 /* Restore using INSERT */
2060                 dumpFn = dumpTableData_insert;
2061                 copyStmt = NULL;
2062         }
2063
2064         /*
2065          * Note: although the TableDataInfo is a full DumpableObject, we treat its
2066          * dependency on its table as "special" and pass it to ArchiveEntry now.
2067          * See comments for BuildArchiveDependencies.
2068          */
2069         if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2070                 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
2071                                          tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
2072                                          NULL, tbinfo->rolname,
2073                                          false, "TABLE DATA", SECTION_DATA,
2074                                          "", "", copyStmt,
2075                                          &(tbinfo->dobj.dumpId), 1,
2076                                          dumpFn, tdinfo);
2077
2078         destroyPQExpBuffer(copyBuf);
2079         destroyPQExpBuffer(clistBuf);
2080 }
2081
2082 /*
2083  * refreshMatViewData -
2084  *        load or refresh the contents of a single materialized view
2085  *
2086  * Actually, this just makes an ArchiveEntry for the REFRESH MATERIALIZED VIEW
2087  * statement.
2088  */
2089 static void
2090 refreshMatViewData(Archive *fout, TableDataInfo *tdinfo)
2091 {
2092         TableInfo  *tbinfo = tdinfo->tdtable;
2093         PQExpBuffer q;
2094
2095         /* If the materialized view is not flagged as populated, skip this. */
2096         if (!tbinfo->relispopulated)
2097                 return;
2098
2099         q = createPQExpBuffer();
2100
2101         appendPQExpBuffer(q, "REFRESH MATERIALIZED VIEW %s;\n",
2102                                           fmtId(tbinfo->dobj.name));
2103
2104         if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2105                 ArchiveEntry(fout,
2106                                          tdinfo->dobj.catId,    /* catalog ID */
2107                                          tdinfo->dobj.dumpId,   /* dump ID */
2108                                          tbinfo->dobj.name, /* Name */
2109                                          tbinfo->dobj.namespace->dobj.name, /* Namespace */
2110                                          NULL,          /* Tablespace */
2111                                          tbinfo->rolname,       /* Owner */
2112                                          false,         /* with oids */
2113                                          "MATERIALIZED VIEW DATA",      /* Desc */
2114                                          SECTION_POST_DATA, /* Section */
2115                                          q->data,       /* Create */
2116                                          "",            /* Del */
2117                                          NULL,          /* Copy */
2118                                          tdinfo->dobj.dependencies, /* Deps */
2119                                          tdinfo->dobj.nDeps,    /* # Deps */
2120                                          NULL,          /* Dumper */
2121                                          NULL);         /* Dumper Arg */
2122
2123         destroyPQExpBuffer(q);
2124 }
2125
2126 /*
2127  * getTableData -
2128  *        set up dumpable objects representing the contents of tables
2129  */
2130 static void
2131 getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, bool oids, char relkind)
2132 {
2133         int                     i;
2134
2135         for (i = 0; i < numTables; i++)
2136         {
2137                 if (tblinfo[i].dobj.dump & DUMP_COMPONENT_DATA &&
2138                         (!relkind || tblinfo[i].relkind == relkind))
2139                         makeTableDataInfo(dopt, &(tblinfo[i]), oids);
2140         }
2141 }
2142
2143 /*
2144  * Make a dumpable object for the data of this specific table
2145  *
2146  * Note: we make a TableDataInfo if and only if we are going to dump the
2147  * table data; the "dump" flag in such objects isn't used.
2148  */
2149 static void
2150 makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo, bool oids)
2151 {
2152         TableDataInfo *tdinfo;
2153
2154         /*
2155          * Nothing to do if we already decided to dump the table.  This will
2156          * happen for "config" tables.
2157          */
2158         if (tbinfo->dataObj != NULL)
2159                 return;
2160
2161         /* Skip VIEWs (no data to dump) */
2162         if (tbinfo->relkind == RELKIND_VIEW)
2163                 return;
2164         /* Skip FOREIGN TABLEs (no data to dump) */
2165         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
2166                 return;
2167         /* Skip partitioned tables (data in partitions) */
2168         if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
2169                 return;
2170
2171         /* Don't dump data in unlogged tables, if so requested */
2172         if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
2173                 dopt->no_unlogged_table_data)
2174                 return;
2175
2176         /* Check that the data is not explicitly excluded */
2177         if (simple_oid_list_member(&tabledata_exclude_oids,
2178                                                            tbinfo->dobj.catId.oid))
2179                 return;
2180
2181         /* OK, let's dump it */
2182         tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
2183
2184         if (tbinfo->relkind == RELKIND_MATVIEW)
2185                 tdinfo->dobj.objType = DO_REFRESH_MATVIEW;
2186         else if (tbinfo->relkind == RELKIND_SEQUENCE)
2187                 tdinfo->dobj.objType = DO_SEQUENCE_SET;
2188         else
2189                 tdinfo->dobj.objType = DO_TABLE_DATA;
2190
2191         /*
2192          * Note: use tableoid 0 so that this object won't be mistaken for
2193          * something that pg_depend entries apply to.
2194          */
2195         tdinfo->dobj.catId.tableoid = 0;
2196         tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
2197         AssignDumpId(&tdinfo->dobj);
2198         tdinfo->dobj.name = tbinfo->dobj.name;
2199         tdinfo->dobj.namespace = tbinfo->dobj.namespace;
2200         tdinfo->tdtable = tbinfo;
2201         tdinfo->oids = oids;
2202         tdinfo->filtercond = NULL;      /* might get set later */
2203         addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
2204
2205         tbinfo->dataObj = tdinfo;
2206 }
2207
2208 /*
2209  * The refresh for a materialized view must be dependent on the refresh for
2210  * any materialized view that this one is dependent on.
2211  *
2212  * This must be called after all the objects are created, but before they are
2213  * sorted.
2214  */
2215 static void
2216 buildMatViewRefreshDependencies(Archive *fout)
2217 {
2218         PQExpBuffer query;
2219         PGresult   *res;
2220         int                     ntups,
2221                                 i;
2222         int                     i_classid,
2223                                 i_objid,
2224                                 i_refobjid;
2225
2226         /* No Mat Views before 9.3. */
2227         if (fout->remoteVersion < 90300)
2228                 return;
2229
2230         /* Make sure we are in proper schema */
2231         selectSourceSchema(fout, "pg_catalog");
2232
2233         query = createPQExpBuffer();
2234
2235         appendPQExpBufferStr(query, "WITH RECURSIVE w AS "
2236                                                  "( "
2237                                                  "SELECT d1.objid, d2.refobjid, c2.relkind AS refrelkind "
2238                                                  "FROM pg_depend d1 "
2239                                                  "JOIN pg_class c1 ON c1.oid = d1.objid "
2240                                                  "AND c1.relkind = " CppAsString2(RELKIND_MATVIEW)
2241                                                  " JOIN pg_rewrite r1 ON r1.ev_class = d1.objid "
2242                                                  "JOIN pg_depend d2 ON d2.classid = 'pg_rewrite'::regclass "
2243                                                  "AND d2.objid = r1.oid "
2244                                                  "AND d2.refobjid <> d1.objid "
2245                                                  "JOIN pg_class c2 ON c2.oid = d2.refobjid "
2246                                                  "AND c2.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2247                                                  CppAsString2(RELKIND_VIEW) ") "
2248                                                  "WHERE d1.classid = 'pg_class'::regclass "
2249                                                  "UNION "
2250                                                  "SELECT w.objid, d3.refobjid, c3.relkind "
2251                                                  "FROM w "
2252                                                  "JOIN pg_rewrite r3 ON r3.ev_class = w.refobjid "
2253                                                  "JOIN pg_depend d3 ON d3.classid = 'pg_rewrite'::regclass "
2254                                                  "AND d3.objid = r3.oid "
2255                                                  "AND d3.refobjid <> w.refobjid "
2256                                                  "JOIN pg_class c3 ON c3.oid = d3.refobjid "
2257                                                  "AND c3.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2258                                                  CppAsString2(RELKIND_VIEW) ") "
2259                                                  ") "
2260                                                  "SELECT 'pg_class'::regclass::oid AS classid, objid, refobjid "
2261                                                  "FROM w "
2262                                                  "WHERE refrelkind = " CppAsString2(RELKIND_MATVIEW));
2263
2264         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2265
2266         ntups = PQntuples(res);
2267
2268         i_classid = PQfnumber(res, "classid");
2269         i_objid = PQfnumber(res, "objid");
2270         i_refobjid = PQfnumber(res, "refobjid");
2271
2272         for (i = 0; i < ntups; i++)
2273         {
2274                 CatalogId       objId;
2275                 CatalogId       refobjId;
2276                 DumpableObject *dobj;
2277                 DumpableObject *refdobj;
2278                 TableInfo  *tbinfo;
2279                 TableInfo  *reftbinfo;
2280
2281                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
2282                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
2283                 refobjId.tableoid = objId.tableoid;
2284                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
2285
2286                 dobj = findObjectByCatalogId(objId);
2287                 if (dobj == NULL)
2288                         continue;
2289
2290                 Assert(dobj->objType == DO_TABLE);
2291                 tbinfo = (TableInfo *) dobj;
2292                 Assert(tbinfo->relkind == RELKIND_MATVIEW);
2293                 dobj = (DumpableObject *) tbinfo->dataObj;
2294                 if (dobj == NULL)
2295                         continue;
2296                 Assert(dobj->objType == DO_REFRESH_MATVIEW);
2297
2298                 refdobj = findObjectByCatalogId(refobjId);
2299                 if (refdobj == NULL)
2300                         continue;
2301
2302                 Assert(refdobj->objType == DO_TABLE);
2303                 reftbinfo = (TableInfo *) refdobj;
2304                 Assert(reftbinfo->relkind == RELKIND_MATVIEW);
2305                 refdobj = (DumpableObject *) reftbinfo->dataObj;
2306                 if (refdobj == NULL)
2307                         continue;
2308                 Assert(refdobj->objType == DO_REFRESH_MATVIEW);
2309
2310                 addObjectDependency(dobj, refdobj->dumpId);
2311
2312                 if (!reftbinfo->relispopulated)
2313                         tbinfo->relispopulated = false;
2314         }
2315
2316         PQclear(res);
2317
2318         destroyPQExpBuffer(query);
2319 }
2320
2321 /*
2322  * getTableDataFKConstraints -
2323  *        add dump-order dependencies reflecting foreign key constraints
2324  *
2325  * This code is executed only in a data-only dump --- in schema+data dumps
2326  * we handle foreign key issues by not creating the FK constraints until
2327  * after the data is loaded.  In a data-only dump, however, we want to
2328  * order the table data objects in such a way that a table's referenced
2329  * tables are restored first.  (In the presence of circular references or
2330  * self-references this may be impossible; we'll detect and complain about
2331  * that during the dependency sorting step.)
2332  */
2333 static void
2334 getTableDataFKConstraints(void)
2335 {
2336         DumpableObject **dobjs;
2337         int                     numObjs;
2338         int                     i;
2339
2340         /* Search through all the dumpable objects for FK constraints */
2341         getDumpableObjects(&dobjs, &numObjs);
2342         for (i = 0; i < numObjs; i++)
2343         {
2344                 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
2345                 {
2346                         ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
2347                         TableInfo  *ftable;
2348
2349                         /* Not interesting unless both tables are to be dumped */
2350                         if (cinfo->contable == NULL ||
2351                                 cinfo->contable->dataObj == NULL)
2352                                 continue;
2353                         ftable = findTableByOid(cinfo->confrelid);
2354                         if (ftable == NULL ||
2355                                 ftable->dataObj == NULL)
2356                                 continue;
2357
2358                         /*
2359                          * Okay, make referencing table's TABLE_DATA object depend on the
2360                          * referenced table's TABLE_DATA object.
2361                          */
2362                         addObjectDependency(&cinfo->contable->dataObj->dobj,
2363                                                                 ftable->dataObj->dobj.dumpId);
2364                 }
2365         }
2366         free(dobjs);
2367 }
2368
2369
2370 /*
2371  * guessConstraintInheritance:
2372  *      In pre-8.4 databases, we can't tell for certain which constraints
2373  *      are inherited.  We assume a CHECK constraint is inherited if its name
2374  *      matches the name of any constraint in the parent.  Originally this code
2375  *      tried to compare the expression texts, but that can fail for various
2376  *      reasons --- for example, if the parent and child tables are in different
2377  *      schemas, reverse-listing of function calls may produce different text
2378  *      (schema-qualified or not) depending on search path.
2379  *
2380  *      In 8.4 and up we can rely on the conislocal field to decide which
2381  *      constraints must be dumped; much safer.
2382  *
2383  *      This function assumes all conislocal flags were initialized to TRUE.
2384  *      It clears the flag on anything that seems to be inherited.
2385  */
2386 static void
2387 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
2388 {
2389         int                     i,
2390                                 j,
2391                                 k;
2392
2393         for (i = 0; i < numTables; i++)
2394         {
2395                 TableInfo  *tbinfo = &(tblinfo[i]);
2396                 int                     numParents;
2397                 TableInfo **parents;
2398                 TableInfo  *parent;
2399
2400                 /* Sequences and views never have parents */
2401                 if (tbinfo->relkind == RELKIND_SEQUENCE ||
2402                         tbinfo->relkind == RELKIND_VIEW)
2403                         continue;
2404
2405                 /* Don't bother computing anything for non-target tables, either */
2406                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
2407                         continue;
2408
2409                 numParents = tbinfo->numParents;
2410                 parents = tbinfo->parents;
2411
2412                 if (numParents == 0)
2413                         continue;                       /* nothing to see here, move along */
2414
2415                 /* scan for inherited CHECK constraints */
2416                 for (j = 0; j < tbinfo->ncheck; j++)
2417                 {
2418                         ConstraintInfo *constr;
2419
2420                         constr = &(tbinfo->checkexprs[j]);
2421
2422                         for (k = 0; k < numParents; k++)
2423                         {
2424                                 int                     l;
2425
2426                                 parent = parents[k];
2427                                 for (l = 0; l < parent->ncheck; l++)
2428                                 {
2429                                         ConstraintInfo *pconstr = &(parent->checkexprs[l]);
2430
2431                                         if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
2432                                         {
2433                                                 constr->conislocal = false;
2434                                                 break;
2435                                         }
2436                                 }
2437                                 if (!constr->conislocal)
2438                                         break;
2439                         }
2440                 }
2441         }
2442 }
2443
2444
2445 /*
2446  * dumpDatabase:
2447  *      dump the database definition
2448  */
2449 static void
2450 dumpDatabase(Archive *fout)
2451 {
2452         DumpOptions *dopt = fout->dopt;
2453         PQExpBuffer dbQry = createPQExpBuffer();
2454         PQExpBuffer delQry = createPQExpBuffer();
2455         PQExpBuffer creaQry = createPQExpBuffer();
2456         PGconn     *conn = GetConnection(fout);
2457         PGresult   *res;
2458         int                     i_tableoid,
2459                                 i_oid,
2460                                 i_dba,
2461                                 i_encoding,
2462                                 i_collate,
2463                                 i_ctype,
2464                                 i_frozenxid,
2465                                 i_minmxid,
2466                                 i_tablespace;
2467         CatalogId       dbCatId;
2468         DumpId          dbDumpId;
2469         const char *datname,
2470                            *dba,
2471                            *encoding,
2472                            *collate,
2473                            *ctype,
2474                            *tablespace;
2475         uint32          frozenxid,
2476                                 minmxid;
2477
2478         datname = PQdb(conn);
2479
2480         if (g_verbose)
2481                 write_msg(NULL, "saving database definition\n");
2482
2483         /* Make sure we are in proper schema */
2484         selectSourceSchema(fout, "pg_catalog");
2485
2486         /* Get the database owner and parameters from pg_database */
2487         if (fout->remoteVersion >= 90300)
2488         {
2489                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2490                                                   "(%s datdba) AS dba, "
2491                                                   "pg_encoding_to_char(encoding) AS encoding, "
2492                                                   "datcollate, datctype, datfrozenxid, datminmxid, "
2493                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2494                                                   "shobj_description(oid, 'pg_database') AS description "
2495
2496                                                   "FROM pg_database "
2497                                                   "WHERE datname = ",
2498                                                   username_subquery);
2499                 appendStringLiteralAH(dbQry, datname, fout);
2500         }
2501         else if (fout->remoteVersion >= 80400)
2502         {
2503                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2504                                                   "(%s datdba) AS dba, "
2505                                                   "pg_encoding_to_char(encoding) AS encoding, "
2506                                                   "datcollate, datctype, datfrozenxid, 0 AS datminmxid, "
2507                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2508                                                   "shobj_description(oid, 'pg_database') AS description "
2509
2510                                                   "FROM pg_database "
2511                                                   "WHERE datname = ",
2512                                                   username_subquery);
2513                 appendStringLiteralAH(dbQry, datname, fout);
2514         }
2515         else if (fout->remoteVersion >= 80200)
2516         {
2517                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2518                                                   "(%s datdba) AS dba, "
2519                                                   "pg_encoding_to_char(encoding) AS encoding, "
2520                                                   "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2521                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2522                                                   "shobj_description(oid, 'pg_database') AS description "
2523
2524                                                   "FROM pg_database "
2525                                                   "WHERE datname = ",
2526                                                   username_subquery);
2527                 appendStringLiteralAH(dbQry, datname, fout);
2528         }
2529         else
2530         {
2531                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2532                                                   "(%s datdba) AS dba, "
2533                                                   "pg_encoding_to_char(encoding) AS encoding, "
2534                                                   "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2535                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
2536                                                   "FROM pg_database "
2537                                                   "WHERE datname = ",
2538                                                   username_subquery);
2539                 appendStringLiteralAH(dbQry, datname, fout);
2540         }
2541
2542         res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
2543
2544         i_tableoid = PQfnumber(res, "tableoid");
2545         i_oid = PQfnumber(res, "oid");
2546         i_dba = PQfnumber(res, "dba");
2547         i_encoding = PQfnumber(res, "encoding");
2548         i_collate = PQfnumber(res, "datcollate");
2549         i_ctype = PQfnumber(res, "datctype");
2550         i_frozenxid = PQfnumber(res, "datfrozenxid");
2551         i_minmxid = PQfnumber(res, "datminmxid");
2552         i_tablespace = PQfnumber(res, "tablespace");
2553
2554         dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
2555         dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
2556         dba = PQgetvalue(res, 0, i_dba);
2557         encoding = PQgetvalue(res, 0, i_encoding);
2558         collate = PQgetvalue(res, 0, i_collate);
2559         ctype = PQgetvalue(res, 0, i_ctype);
2560         frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
2561         minmxid = atooid(PQgetvalue(res, 0, i_minmxid));
2562         tablespace = PQgetvalue(res, 0, i_tablespace);
2563
2564         appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
2565                                           fmtId(datname));
2566         if (strlen(encoding) > 0)
2567         {
2568                 appendPQExpBufferStr(creaQry, " ENCODING = ");
2569                 appendStringLiteralAH(creaQry, encoding, fout);
2570         }
2571         if (strlen(collate) > 0)
2572         {
2573                 appendPQExpBufferStr(creaQry, " LC_COLLATE = ");
2574                 appendStringLiteralAH(creaQry, collate, fout);
2575         }
2576         if (strlen(ctype) > 0)
2577         {
2578                 appendPQExpBufferStr(creaQry, " LC_CTYPE = ");
2579                 appendStringLiteralAH(creaQry, ctype, fout);
2580         }
2581         if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0 &&
2582                 !dopt->outputNoTablespaces)
2583                 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
2584                                                   fmtId(tablespace));
2585         appendPQExpBufferStr(creaQry, ";\n");
2586
2587         if (dopt->binary_upgrade)
2588         {
2589                 appendPQExpBufferStr(creaQry, "\n-- For binary upgrade, set datfrozenxid and datminmxid.\n");
2590                 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
2591                                                   "SET datfrozenxid = '%u', datminmxid = '%u'\n"
2592                                                   "WHERE datname = ",
2593                                                   frozenxid, minmxid);
2594                 appendStringLiteralAH(creaQry, datname, fout);
2595                 appendPQExpBufferStr(creaQry, ";\n");
2596
2597         }
2598
2599         appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
2600                                           fmtId(datname));
2601
2602         dbDumpId = createDumpId();
2603
2604         ArchiveEntry(fout,
2605                                  dbCatId,               /* catalog ID */
2606                                  dbDumpId,              /* dump ID */
2607                                  datname,               /* Name */
2608                                  NULL,                  /* Namespace */
2609                                  NULL,                  /* Tablespace */
2610                                  dba,                   /* Owner */
2611                                  false,                 /* with oids */
2612                                  "DATABASE",    /* Desc */
2613                                  SECTION_PRE_DATA,      /* Section */
2614                                  creaQry->data, /* Create */
2615                                  delQry->data,  /* Del */
2616                                  NULL,                  /* Copy */
2617                                  NULL,                  /* Deps */
2618                                  0,                             /* # Deps */
2619                                  NULL,                  /* Dumper */
2620                                  NULL);                 /* Dumper Arg */
2621
2622         /*
2623          * pg_largeobject and pg_largeobject_metadata come from the old system
2624          * intact, so set their relfrozenxids and relminmxids.
2625          */
2626         if (dopt->binary_upgrade)
2627         {
2628                 PGresult   *lo_res;
2629                 PQExpBuffer loFrozenQry = createPQExpBuffer();
2630                 PQExpBuffer loOutQry = createPQExpBuffer();
2631                 int                     i_relfrozenxid,
2632                                         i_relminmxid;
2633
2634                 /*
2635                  * pg_largeobject
2636                  */
2637                 if (fout->remoteVersion >= 90300)
2638                         appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
2639                                                           "FROM pg_catalog.pg_class\n"
2640                                                           "WHERE oid = %u;\n",
2641                                                           LargeObjectRelationId);
2642                 else
2643                         appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
2644                                                           "FROM pg_catalog.pg_class\n"
2645                                                           "WHERE oid = %u;\n",
2646                                                           LargeObjectRelationId);
2647
2648                 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2649
2650                 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2651                 i_relminmxid = PQfnumber(lo_res, "relminmxid");
2652
2653                 appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject relfrozenxid and relminmxid\n");
2654                 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2655                                                   "SET relfrozenxid = '%u', relminmxid = '%u'\n"
2656                                                   "WHERE oid = %u;\n",
2657                                                   atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2658                                                   atoi(PQgetvalue(lo_res, 0, i_relminmxid)),
2659                                                   LargeObjectRelationId);
2660                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2661                                          "pg_largeobject", NULL, NULL, "",
2662                                          false, "pg_largeobject", SECTION_PRE_DATA,
2663                                          loOutQry->data, "", NULL,
2664                                          NULL, 0,
2665                                          NULL, NULL);
2666
2667                 PQclear(lo_res);
2668
2669                 /*
2670                  * pg_largeobject_metadata
2671                  */
2672                 if (fout->remoteVersion >= 90000)
2673                 {
2674                         resetPQExpBuffer(loFrozenQry);
2675                         resetPQExpBuffer(loOutQry);
2676
2677                         if (fout->remoteVersion >= 90300)
2678                                 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid\n"
2679                                                                   "FROM pg_catalog.pg_class\n"
2680                                                                   "WHERE oid = %u;\n",
2681                                                                   LargeObjectMetadataRelationId);
2682                         else
2683                                 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid\n"
2684                                                                   "FROM pg_catalog.pg_class\n"
2685                                                                   "WHERE oid = %u;\n",
2686                                                                   LargeObjectMetadataRelationId);
2687
2688                         lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2689
2690                         i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2691                         i_relminmxid = PQfnumber(lo_res, "relminmxid");
2692
2693                         appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata relfrozenxid and relminmxid\n");
2694                         appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2695                                                           "SET relfrozenxid = '%u', relminmxid = '%u'\n"
2696                                                           "WHERE oid = %u;\n",
2697                                                           atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2698                                                           atoi(PQgetvalue(lo_res, 0, i_relminmxid)),
2699                                                           LargeObjectMetadataRelationId);
2700                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2701                                                  "pg_largeobject_metadata", NULL, NULL, "",
2702                                                  false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2703                                                  loOutQry->data, "", NULL,
2704                                                  NULL, 0,
2705                                                  NULL, NULL);
2706
2707                         PQclear(lo_res);
2708                 }
2709
2710                 destroyPQExpBuffer(loFrozenQry);
2711                 destroyPQExpBuffer(loOutQry);
2712         }
2713
2714         /* Dump DB comment if any */
2715         if (fout->remoteVersion >= 80200)
2716         {
2717                 /*
2718                  * 8.2 keeps comments on shared objects in a shared table, so we
2719                  * cannot use the dumpComment used for other database objects.
2720                  */
2721                 char       *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2722
2723                 if (comment && strlen(comment))
2724                 {
2725                         resetPQExpBuffer(dbQry);
2726
2727                         /*
2728                          * Generates warning when loaded into a differently-named
2729                          * database.
2730                          */
2731                         appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2732                         appendStringLiteralAH(dbQry, comment, fout);
2733                         appendPQExpBufferStr(dbQry, ";\n");
2734
2735                         ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2736                                                  dba, false, "COMMENT", SECTION_NONE,
2737                                                  dbQry->data, "", NULL,
2738                                                  &dbDumpId, 1, NULL, NULL);
2739                 }
2740         }
2741         else
2742         {
2743                 resetPQExpBuffer(dbQry);
2744                 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2745                 dumpComment(fout, dbQry->data, NULL, "",
2746                                         dbCatId, 0, dbDumpId);
2747         }
2748
2749         /* Dump shared security label. */
2750         if (!dopt->no_security_labels && fout->remoteVersion >= 90200)
2751         {
2752                 PGresult   *shres;
2753                 PQExpBuffer seclabelQry;
2754
2755                 seclabelQry = createPQExpBuffer();
2756
2757                 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2758                 shres = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2759                 resetPQExpBuffer(seclabelQry);
2760                 emitShSecLabels(conn, shres, seclabelQry, "DATABASE", datname);
2761                 if (strlen(seclabelQry->data))
2762                         ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2763                                                  dba, false, "SECURITY LABEL", SECTION_NONE,
2764                                                  seclabelQry->data, "", NULL,
2765                                                  &dbDumpId, 1, NULL, NULL);
2766                 destroyPQExpBuffer(seclabelQry);
2767                 PQclear(shres);
2768         }
2769
2770         PQclear(res);
2771
2772         destroyPQExpBuffer(dbQry);
2773         destroyPQExpBuffer(delQry);
2774         destroyPQExpBuffer(creaQry);
2775 }
2776
2777 /*
2778  * dumpEncoding: put the correct encoding into the archive
2779  */
2780 static void
2781 dumpEncoding(Archive *AH)
2782 {
2783         const char *encname = pg_encoding_to_char(AH->encoding);
2784         PQExpBuffer qry = createPQExpBuffer();
2785
2786         if (g_verbose)
2787                 write_msg(NULL, "saving encoding = %s\n", encname);
2788
2789         appendPQExpBufferStr(qry, "SET client_encoding = ");
2790         appendStringLiteralAH(qry, encname, AH);
2791         appendPQExpBufferStr(qry, ";\n");
2792
2793         ArchiveEntry(AH, nilCatalogId, createDumpId(),
2794                                  "ENCODING", NULL, NULL, "",
2795                                  false, "ENCODING", SECTION_PRE_DATA,
2796                                  qry->data, "", NULL,
2797                                  NULL, 0,
2798                                  NULL, NULL);
2799
2800         destroyPQExpBuffer(qry);
2801 }
2802
2803
2804 /*
2805  * dumpStdStrings: put the correct escape string behavior into the archive
2806  */
2807 static void
2808 dumpStdStrings(Archive *AH)
2809 {
2810         const char *stdstrings = AH->std_strings ? "on" : "off";
2811         PQExpBuffer qry = createPQExpBuffer();
2812
2813         if (g_verbose)
2814                 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2815                                   stdstrings);
2816
2817         appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2818                                           stdstrings);
2819
2820         ArchiveEntry(AH, nilCatalogId, createDumpId(),
2821                                  "STDSTRINGS", NULL, NULL, "",
2822                                  false, "STDSTRINGS", SECTION_PRE_DATA,
2823                                  qry->data, "", NULL,
2824                                  NULL, 0,
2825                                  NULL, NULL);
2826
2827         destroyPQExpBuffer(qry);
2828 }
2829
2830
2831 /*
2832  * getBlobs:
2833  *      Collect schema-level data about large objects
2834  */
2835 static void
2836 getBlobs(Archive *fout)
2837 {
2838         DumpOptions *dopt = fout->dopt;
2839         PQExpBuffer blobQry = createPQExpBuffer();
2840         BlobInfo   *binfo;
2841         DumpableObject *bdata;
2842         PGresult   *res;
2843         int                     ntups;
2844         int                     i;
2845         int                     i_oid;
2846         int                     i_lomowner;
2847         int                     i_lomacl;
2848         int                     i_rlomacl;
2849         int                     i_initlomacl;
2850         int                     i_initrlomacl;
2851
2852         /* Verbose message */
2853         if (g_verbose)
2854                 write_msg(NULL, "reading large objects\n");
2855
2856         /* Make sure we are in proper schema */
2857         selectSourceSchema(fout, "pg_catalog");
2858
2859         /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2860         if (fout->remoteVersion >= 90600)
2861         {
2862                 PQExpBuffer acl_subquery = createPQExpBuffer();
2863                 PQExpBuffer racl_subquery = createPQExpBuffer();
2864                 PQExpBuffer init_acl_subquery = createPQExpBuffer();
2865                 PQExpBuffer init_racl_subquery = createPQExpBuffer();
2866
2867                 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
2868                                                 init_racl_subquery, "l.lomacl", "l.lomowner", "'L'",
2869                                                 dopt->binary_upgrade);
2870
2871                 appendPQExpBuffer(blobQry,
2872                                                   "SELECT l.oid, (%s l.lomowner) AS rolname, "
2873                                                   "%s AS lomacl, "
2874                                                   "%s AS rlomacl, "
2875                                                   "%s AS initlomacl, "
2876                                                   "%s AS initrlomacl "
2877                                                   "FROM pg_largeobject_metadata l "
2878                                                   "LEFT JOIN pg_init_privs pip ON "
2879                                                   "(l.oid = pip.objoid "
2880                                                   "AND pip.classoid = 'pg_largeobject'::regclass "
2881                                                   "AND pip.objsubid = 0) ",
2882                                                   username_subquery,
2883                                                   acl_subquery->data,
2884                                                   racl_subquery->data,
2885                                                   init_acl_subquery->data,
2886                                                   init_racl_subquery->data);
2887
2888                 destroyPQExpBuffer(acl_subquery);
2889                 destroyPQExpBuffer(racl_subquery);
2890                 destroyPQExpBuffer(init_acl_subquery);
2891                 destroyPQExpBuffer(init_racl_subquery);
2892         }
2893         else if (fout->remoteVersion >= 90000)
2894                 appendPQExpBuffer(blobQry,
2895                                                   "SELECT oid, (%s lomowner) AS rolname, lomacl, "
2896                                                   "NULL AS rlomacl, NULL AS initlomacl, "
2897                                                   "NULL AS initrlomacl "
2898                                                   " FROM pg_largeobject_metadata",
2899                                                   username_subquery);
2900         else
2901                 appendPQExpBufferStr(blobQry,
2902                                                          "SELECT DISTINCT loid AS oid, "
2903                                                          "NULL::name AS rolname, NULL::oid AS lomacl, "
2904                                                          "NULL::oid AS rlomacl, NULL::oid AS initlomacl, "
2905                                                          "NULL::oid AS initrlomacl "
2906                                                          " FROM pg_largeobject");
2907
2908         res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
2909
2910         i_oid = PQfnumber(res, "oid");
2911         i_lomowner = PQfnumber(res, "rolname");
2912         i_lomacl = PQfnumber(res, "lomacl");
2913         i_rlomacl = PQfnumber(res, "rlomacl");
2914         i_initlomacl = PQfnumber(res, "initlomacl");
2915         i_initrlomacl = PQfnumber(res, "initrlomacl");
2916
2917         ntups = PQntuples(res);
2918
2919         /*
2920          * Each large object has its own BLOB archive entry.
2921          */
2922         binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2923
2924         for (i = 0; i < ntups; i++)
2925         {
2926                 binfo[i].dobj.objType = DO_BLOB;
2927                 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2928                 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2929                 AssignDumpId(&binfo[i].dobj);
2930
2931                 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oid));
2932                 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_lomowner));
2933                 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, i_lomacl));
2934                 binfo[i].rblobacl = pg_strdup(PQgetvalue(res, i, i_rlomacl));
2935                 binfo[i].initblobacl = pg_strdup(PQgetvalue(res, i, i_initlomacl));
2936                 binfo[i].initrblobacl = pg_strdup(PQgetvalue(res, i, i_initrlomacl));
2937
2938                 if (PQgetisnull(res, i, i_lomacl) &&
2939                         PQgetisnull(res, i, i_rlomacl) &&
2940                         PQgetisnull(res, i, i_initlomacl) &&
2941                         PQgetisnull(res, i, i_initrlomacl))
2942                         binfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
2943
2944                 /*
2945                  * In binary-upgrade mode for blobs, we do *not* dump out the data or
2946                  * the ACLs, should any exist.  The data and ACL (if any) will be
2947                  * copied by pg_upgrade, which simply copies the pg_largeobject and
2948                  * pg_largeobject_metadata tables.
2949                  *
2950                  * We *do* dump out the definition of the blob because we need that to
2951                  * make the restoration of the comments, and anything else, work since
2952                  * pg_upgrade copies the files behind pg_largeobject and
2953                  * pg_largeobject_metadata after the dump is restored.
2954                  */
2955                 if (dopt->binary_upgrade)
2956                         binfo[i].dobj.dump &= ~(DUMP_COMPONENT_DATA | DUMP_COMPONENT_ACL);
2957         }
2958
2959         /*
2960          * If we have any large objects, a "BLOBS" archive entry is needed. This
2961          * is just a placeholder for sorting; it carries no data now.
2962          */
2963         if (ntups > 0)
2964         {
2965                 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2966                 bdata->objType = DO_BLOB_DATA;
2967                 bdata->catId = nilCatalogId;
2968                 AssignDumpId(bdata);
2969                 bdata->name = pg_strdup("BLOBS");
2970         }
2971
2972         PQclear(res);
2973         destroyPQExpBuffer(blobQry);
2974 }
2975
2976 /*
2977  * dumpBlob
2978  *
2979  * dump the definition (metadata) of the given large object
2980  */
2981 static void
2982 dumpBlob(Archive *fout, BlobInfo *binfo)
2983 {
2984         PQExpBuffer cquery = createPQExpBuffer();
2985         PQExpBuffer dquery = createPQExpBuffer();
2986
2987         appendPQExpBuffer(cquery,
2988                                           "SELECT pg_catalog.lo_create('%s');\n",
2989                                           binfo->dobj.name);
2990
2991         appendPQExpBuffer(dquery,
2992                                           "SELECT pg_catalog.lo_unlink('%s');\n",
2993                                           binfo->dobj.name);
2994
2995         if (binfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
2996                 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
2997                                          binfo->dobj.name,
2998                                          NULL, NULL,
2999                                          binfo->rolname, false,
3000                                          "BLOB", SECTION_PRE_DATA,
3001                                          cquery->data, dquery->data, NULL,
3002                                          NULL, 0,
3003                                          NULL, NULL);
3004
3005         /* set up tag for comment and/or ACL */
3006         resetPQExpBuffer(cquery);
3007         appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
3008
3009         /* Dump comment if any */
3010         if (binfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3011                 dumpComment(fout, cquery->data,
3012                                         NULL, binfo->rolname,
3013                                         binfo->dobj.catId, 0, binfo->dobj.dumpId);
3014
3015         /* Dump security label if any */
3016         if (binfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3017                 dumpSecLabel(fout, cquery->data,
3018                                          NULL, binfo->rolname,
3019                                          binfo->dobj.catId, 0, binfo->dobj.dumpId);
3020
3021         /* Dump ACL if any */
3022         if (binfo->blobacl && (binfo->dobj.dump & DUMP_COMPONENT_ACL))
3023                 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
3024                                 binfo->dobj.name, NULL, cquery->data,
3025                                 NULL, binfo->rolname, binfo->blobacl, binfo->rblobacl,
3026                                 binfo->initblobacl, binfo->initrblobacl);
3027
3028         destroyPQExpBuffer(cquery);
3029         destroyPQExpBuffer(dquery);
3030 }
3031
3032 /*
3033  * dumpBlobs:
3034  *      dump the data contents of all large objects
3035  */
3036 static int
3037 dumpBlobs(Archive *fout, void *arg)
3038 {
3039         const char *blobQry;
3040         const char *blobFetchQry;
3041         PGconn     *conn = GetConnection(fout);
3042         PGresult   *res;
3043         char            buf[LOBBUFSIZE];
3044         int                     ntups;
3045         int                     i;
3046         int                     cnt;
3047
3048         if (g_verbose)
3049                 write_msg(NULL, "saving large objects\n");
3050
3051         /* Make sure we are in proper schema */
3052         selectSourceSchema(fout, "pg_catalog");
3053
3054         /*
3055          * Currently, we re-fetch all BLOB OIDs using a cursor.  Consider scanning
3056          * the already-in-memory dumpable objects instead...
3057          */
3058         if (fout->remoteVersion >= 90000)
3059                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
3060         else
3061                 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
3062
3063         ExecuteSqlStatement(fout, blobQry);
3064
3065         /* Command to fetch from cursor */
3066         blobFetchQry = "FETCH 1000 IN bloboid";
3067
3068         do
3069         {
3070                 /* Do a fetch */
3071                 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
3072
3073                 /* Process the tuples, if any */
3074                 ntups = PQntuples(res);
3075                 for (i = 0; i < ntups; i++)
3076                 {
3077                         Oid                     blobOid;
3078                         int                     loFd;
3079
3080                         blobOid = atooid(PQgetvalue(res, i, 0));
3081                         /* Open the BLOB */
3082                         loFd = lo_open(conn, blobOid, INV_READ);
3083                         if (loFd == -1)
3084                                 exit_horribly(NULL, "could not open large object %u: %s",
3085                                                           blobOid, PQerrorMessage(conn));
3086
3087                         StartBlob(fout, blobOid);
3088
3089                         /* Now read it in chunks, sending data to archive */
3090                         do
3091                         {
3092                                 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
3093                                 if (cnt < 0)
3094                                         exit_horribly(NULL, "error reading large object %u: %s",
3095                                                                   blobOid, PQerrorMessage(conn));
3096
3097                                 WriteData(fout, buf, cnt);
3098                         } while (cnt > 0);
3099
3100                         lo_close(conn, loFd);
3101
3102                         EndBlob(fout, blobOid);
3103                 }
3104
3105                 PQclear(res);
3106         } while (ntups > 0);
3107
3108         return 1;
3109 }
3110
3111 /*
3112  * getPolicies
3113  *        get information about policies on a dumpable table.
3114  */
3115 void
3116 getPolicies(Archive *fout, TableInfo tblinfo[], int numTables)
3117 {
3118         PQExpBuffer query;
3119         PGresult   *res;
3120         PolicyInfo *polinfo;
3121         int                     i_oid;
3122         int                     i_tableoid;
3123         int                     i_polname;
3124         int                     i_polcmd;
3125         int                     i_polpermissive;
3126         int                     i_polroles;
3127         int                     i_polqual;
3128         int                     i_polwithcheck;
3129         int                     i,
3130                                 j,
3131                                 ntups;
3132
3133         if (fout->remoteVersion < 90500)
3134                 return;
3135
3136         query = createPQExpBuffer();
3137
3138         for (i = 0; i < numTables; i++)
3139         {
3140                 TableInfo  *tbinfo = &tblinfo[i];
3141
3142                 /* Ignore row security on tables not to be dumped */
3143                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_POLICY))
3144                         continue;
3145
3146                 if (g_verbose)
3147                         write_msg(NULL, "reading row security enabled for table \"%s.%s\"\n",
3148                                           tbinfo->dobj.namespace->dobj.name,
3149                                           tbinfo->dobj.name);
3150
3151                 /*
3152                  * Get row security enabled information for the table. We represent
3153                  * RLS enabled on a table by creating PolicyInfo object with an empty
3154                  * policy.
3155                  */
3156                 if (tbinfo->rowsec)
3157                 {
3158                         /*
3159                          * Note: use tableoid 0 so that this object won't be mistaken for
3160                          * something that pg_depend entries apply to.
3161                          */
3162                         polinfo = pg_malloc(sizeof(PolicyInfo));
3163                         polinfo->dobj.objType = DO_POLICY;
3164                         polinfo->dobj.catId.tableoid = 0;
3165                         polinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
3166                         AssignDumpId(&polinfo->dobj);
3167                         polinfo->dobj.namespace = tbinfo->dobj.namespace;
3168                         polinfo->dobj.name = pg_strdup(tbinfo->dobj.name);
3169                         polinfo->poltable = tbinfo;
3170                         polinfo->polname = NULL;
3171                         polinfo->polcmd = '\0';
3172                         polinfo->polpermissive = 0;
3173                         polinfo->polroles = NULL;
3174                         polinfo->polqual = NULL;
3175                         polinfo->polwithcheck = NULL;
3176                 }
3177
3178                 if (g_verbose)
3179                         write_msg(NULL, "reading policies for table \"%s.%s\"\n",
3180                                           tbinfo->dobj.namespace->dobj.name,
3181                                           tbinfo->dobj.name);
3182
3183                 /*
3184                  * select table schema to ensure regproc name is qualified if needed
3185                  */
3186                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
3187
3188                 resetPQExpBuffer(query);
3189
3190                 /* Get the policies for the table. */
3191                 if (fout->remoteVersion >= 100000)
3192                         appendPQExpBuffer(query,
3193                                                           "SELECT oid, tableoid, pol.polname, pol.polcmd, pol.polpermissive, "
3194                                                           "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3195                                                           "   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, "
3196                                                           "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3197                                                           "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3198                                                           "FROM pg_catalog.pg_policy pol "
3199                                                           "WHERE polrelid = '%u'",
3200                                                           tbinfo->dobj.catId.oid);
3201                 else
3202                         appendPQExpBuffer(query,
3203                                                           "SELECT oid, tableoid, pol.polname, pol.polcmd, 't' as polpermissive, "
3204                                                           "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3205                                                           "   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, "
3206                                                           "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3207                                                           "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3208                                                           "FROM pg_catalog.pg_policy pol "
3209                                                           "WHERE polrelid = '%u'",
3210                                                           tbinfo->dobj.catId.oid);
3211                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3212
3213                 ntups = PQntuples(res);
3214
3215                 if (ntups == 0)
3216                 {
3217                         /*
3218                          * No explicit policies to handle (only the default-deny policy,
3219                          * which is handled as part of the table definition).  Clean up
3220                          * and return.
3221                          */
3222                         PQclear(res);
3223                         continue;
3224                 }
3225
3226                 i_oid = PQfnumber(res, "oid");
3227                 i_tableoid = PQfnumber(res, "tableoid");
3228                 i_polname = PQfnumber(res, "polname");
3229                 i_polcmd = PQfnumber(res, "polcmd");
3230                 i_polpermissive = PQfnumber(res, "polpermissive");
3231                 i_polroles = PQfnumber(res, "polroles");
3232                 i_polqual = PQfnumber(res, "polqual");
3233                 i_polwithcheck = PQfnumber(res, "polwithcheck");
3234
3235                 polinfo = pg_malloc(ntups * sizeof(PolicyInfo));
3236
3237                 for (j = 0; j < ntups; j++)
3238                 {
3239                         polinfo[j].dobj.objType = DO_POLICY;
3240                         polinfo[j].dobj.catId.tableoid =
3241                                 atooid(PQgetvalue(res, j, i_tableoid));
3242                         polinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3243                         AssignDumpId(&polinfo[j].dobj);
3244                         polinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3245                         polinfo[j].poltable = tbinfo;
3246                         polinfo[j].polname = pg_strdup(PQgetvalue(res, j, i_polname));
3247                         polinfo[j].dobj.name = pg_strdup(polinfo[j].polname);
3248
3249                         polinfo[j].polcmd = *(PQgetvalue(res, j, i_polcmd));
3250                         polinfo[j].polpermissive = *(PQgetvalue(res, j, i_polpermissive)) == 't';
3251
3252                         if (PQgetisnull(res, j, i_polroles))
3253                                 polinfo[j].polroles = NULL;
3254                         else
3255                                 polinfo[j].polroles = pg_strdup(PQgetvalue(res, j, i_polroles));
3256
3257                         if (PQgetisnull(res, j, i_polqual))
3258                                 polinfo[j].polqual = NULL;
3259                         else
3260                                 polinfo[j].polqual = pg_strdup(PQgetvalue(res, j, i_polqual));
3261
3262                         if (PQgetisnull(res, j, i_polwithcheck))
3263                                 polinfo[j].polwithcheck = NULL;
3264                         else
3265                                 polinfo[j].polwithcheck
3266                                         = pg_strdup(PQgetvalue(res, j, i_polwithcheck));
3267                 }
3268                 PQclear(res);
3269         }
3270         destroyPQExpBuffer(query);
3271 }
3272
3273 /*
3274  * dumpPolicy
3275  *        dump the definition of the given policy
3276  */
3277 static void
3278 dumpPolicy(Archive *fout, PolicyInfo *polinfo)
3279 {
3280         DumpOptions *dopt = fout->dopt;
3281         TableInfo  *tbinfo = polinfo->poltable;
3282         PQExpBuffer query;
3283         PQExpBuffer delqry;
3284         const char *cmd;
3285         char       *tag;
3286
3287         if (dopt->dataOnly)
3288                 return;
3289
3290         /*
3291          * If polname is NULL, then this record is just indicating that ROW LEVEL
3292          * SECURITY is enabled for the table. Dump as ALTER TABLE <table> ENABLE
3293          * ROW LEVEL SECURITY.
3294          */
3295         if (polinfo->polname == NULL)
3296         {
3297                 query = createPQExpBuffer();
3298
3299                 appendPQExpBuffer(query, "ALTER TABLE %s ENABLE ROW LEVEL SECURITY;",
3300                                                   fmtId(polinfo->dobj.name));
3301
3302                 if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3303                         ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3304                                                  polinfo->dobj.name,
3305                                                  polinfo->dobj.namespace->dobj.name,
3306                                                  NULL,
3307                                                  tbinfo->rolname, false,
3308                                                  "ROW SECURITY", SECTION_POST_DATA,
3309                                                  query->data, "", NULL,
3310                                                  NULL, 0,
3311                                                  NULL, NULL);
3312
3313                 destroyPQExpBuffer(query);
3314                 return;
3315         }
3316
3317         if (polinfo->polcmd == '*')
3318                 cmd = "";
3319         else if (polinfo->polcmd == 'r')
3320                 cmd = " FOR SELECT";
3321         else if (polinfo->polcmd == 'a')
3322                 cmd = " FOR INSERT";
3323         else if (polinfo->polcmd == 'w')
3324                 cmd = " FOR UPDATE";
3325         else if (polinfo->polcmd == 'd')
3326                 cmd = " FOR DELETE";
3327         else
3328         {
3329                 write_msg(NULL, "unexpected policy command type: %c\n",
3330                                   polinfo->polcmd);
3331                 exit_nicely(1);
3332         }
3333
3334         query = createPQExpBuffer();
3335         delqry = createPQExpBuffer();
3336
3337         appendPQExpBuffer(query, "CREATE POLICY %s", fmtId(polinfo->polname));
3338
3339         appendPQExpBuffer(query, " ON %s%s%s", fmtId(tbinfo->dobj.name),
3340                                           !polinfo->polpermissive ? " AS RESTRICTIVE" : "", cmd);
3341
3342         if (polinfo->polroles != NULL)
3343                 appendPQExpBuffer(query, " TO %s", polinfo->polroles);
3344
3345         if (polinfo->polqual != NULL)
3346                 appendPQExpBuffer(query, " USING (%s)", polinfo->polqual);
3347
3348         if (polinfo->polwithcheck != NULL)
3349                 appendPQExpBuffer(query, " WITH CHECK (%s)", polinfo->polwithcheck);
3350
3351         appendPQExpBuffer(query, ";\n");
3352
3353         appendPQExpBuffer(delqry, "DROP POLICY %s", fmtId(polinfo->polname));
3354         appendPQExpBuffer(delqry, " ON %s;\n", fmtId(tbinfo->dobj.name));
3355
3356         tag = psprintf("%s %s", tbinfo->dobj.name, polinfo->dobj.name);
3357
3358         if (polinfo->dobj.dump & DUMP_COMPONENT_POLICY)
3359                 ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
3360                                          tag,
3361                                          polinfo->dobj.namespace->dobj.name,
3362                                          NULL,
3363                                          tbinfo->rolname, false,
3364                                          "POLICY", SECTION_POST_DATA,
3365                                          query->data, delqry->data, NULL,
3366                                          NULL, 0,
3367                                          NULL, NULL);
3368
3369         free(tag);
3370         destroyPQExpBuffer(query);
3371         destroyPQExpBuffer(delqry);
3372 }
3373
3374 /*
3375  * getPublications
3376  *        get information about publications
3377  */
3378 void
3379 getPublications(Archive *fout)
3380 {
3381         DumpOptions *dopt = fout->dopt;
3382         PQExpBuffer query;
3383         PGresult   *res;
3384         PublicationInfo *pubinfo;
3385         int                     i_tableoid;
3386         int                     i_oid;
3387         int                     i_pubname;
3388         int                     i_rolname;
3389         int                     i_puballtables;
3390         int                     i_pubinsert;
3391         int                     i_pubupdate;
3392         int                     i_pubdelete;
3393         int                     i,
3394                                 ntups;
3395
3396         if (dopt->no_publications || fout->remoteVersion < 100000)
3397                 return;
3398
3399         query = createPQExpBuffer();
3400
3401         resetPQExpBuffer(query);
3402
3403         /* Get the publications. */
3404         appendPQExpBuffer(query,
3405                                           "SELECT p.tableoid, p.oid, p.pubname, "
3406                                           "(%s p.pubowner) AS rolname, "
3407                                           "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete "
3408                                           "FROM pg_catalog.pg_publication p",
3409                                           username_subquery);
3410
3411         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3412
3413         ntups = PQntuples(res);
3414
3415         i_tableoid = PQfnumber(res, "tableoid");
3416         i_oid = PQfnumber(res, "oid");
3417         i_pubname = PQfnumber(res, "pubname");
3418         i_rolname = PQfnumber(res, "rolname");
3419         i_puballtables = PQfnumber(res, "puballtables");
3420         i_pubinsert = PQfnumber(res, "pubinsert");
3421         i_pubupdate = PQfnumber(res, "pubupdate");
3422         i_pubdelete = PQfnumber(res, "pubdelete");
3423
3424         pubinfo = pg_malloc(ntups * sizeof(PublicationInfo));
3425
3426         for (i = 0; i < ntups; i++)
3427         {
3428                 pubinfo[i].dobj.objType = DO_PUBLICATION;
3429                 pubinfo[i].dobj.catId.tableoid =
3430                         atooid(PQgetvalue(res, i, i_tableoid));
3431                 pubinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3432                 AssignDumpId(&pubinfo[i].dobj);
3433                 pubinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_pubname));
3434                 pubinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3435                 pubinfo[i].puballtables =
3436                         (strcmp(PQgetvalue(res, i, i_puballtables), "t") == 0);
3437                 pubinfo[i].pubinsert =
3438                         (strcmp(PQgetvalue(res, i, i_pubinsert), "t") == 0);
3439                 pubinfo[i].pubupdate =
3440                         (strcmp(PQgetvalue(res, i, i_pubupdate), "t") == 0);
3441                 pubinfo[i].pubdelete =
3442                         (strcmp(PQgetvalue(res, i, i_pubdelete), "t") == 0);
3443
3444                 if (strlen(pubinfo[i].rolname) == 0)
3445                         write_msg(NULL, "WARNING: owner of publication \"%s\" appears to be invalid\n",
3446                                           pubinfo[i].dobj.name);
3447
3448                 /* Decide whether we want to dump it */
3449                 selectDumpableObject(&(pubinfo[i].dobj), fout);
3450         }
3451         PQclear(res);
3452
3453         destroyPQExpBuffer(query);
3454 }
3455
3456 /*
3457  * dumpPublication
3458  *        dump the definition of the given publication
3459  */
3460 static void
3461 dumpPublication(Archive *fout, PublicationInfo *pubinfo)
3462 {
3463         PQExpBuffer delq;
3464         PQExpBuffer query;
3465         PQExpBuffer labelq;
3466         bool            first = true;
3467
3468         if (!(pubinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3469                 return;
3470
3471         delq = createPQExpBuffer();
3472         query = createPQExpBuffer();
3473         labelq = createPQExpBuffer();
3474
3475         appendPQExpBuffer(delq, "DROP PUBLICATION %s;\n",
3476                                           fmtId(pubinfo->dobj.name));
3477
3478         appendPQExpBuffer(query, "CREATE PUBLICATION %s",
3479                                           fmtId(pubinfo->dobj.name));
3480
3481         appendPQExpBuffer(labelq, "PUBLICATION %s", fmtId(pubinfo->dobj.name));
3482
3483         if (pubinfo->puballtables)
3484                 appendPQExpBufferStr(query, " FOR ALL TABLES");
3485
3486         appendPQExpBufferStr(query, " WITH (publish = '");
3487         if (pubinfo->pubinsert)
3488         {
3489                 appendPQExpBufferStr(query, "insert");
3490                 first = false;
3491         }
3492
3493         if (pubinfo->pubupdate)
3494         {
3495                 if (!first)
3496                         appendPQExpBufferStr(query, ", ");
3497
3498                 appendPQExpBufferStr(query, "update");
3499                 first = false;
3500         }
3501
3502         if (pubinfo->pubdelete)
3503         {
3504                 if (!first)
3505                         appendPQExpBufferStr(query, ", ");
3506
3507                 appendPQExpBufferStr(query, "delete");
3508                 first = false;
3509         }
3510
3511         appendPQExpBufferStr(query, "');\n");
3512
3513         ArchiveEntry(fout, pubinfo->dobj.catId, pubinfo->dobj.dumpId,
3514                                  pubinfo->dobj.name,
3515                                  NULL,
3516                                  NULL,
3517                                  pubinfo->rolname, false,
3518                                  "PUBLICATION", SECTION_POST_DATA,
3519                                  query->data, delq->data, NULL,
3520                                  NULL, 0,
3521                                  NULL, NULL);
3522
3523         if (pubinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3524                 dumpComment(fout, labelq->data,
3525                                         NULL, pubinfo->rolname,
3526                                         pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3527
3528         if (pubinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3529                 dumpSecLabel(fout, labelq->data,
3530                                          NULL, pubinfo->rolname,
3531                                          pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
3532
3533         destroyPQExpBuffer(delq);
3534         destroyPQExpBuffer(query);
3535 }
3536
3537 /*
3538  * getPublicationTables
3539  *        get information about publication membership for dumpable tables.
3540  */
3541 void
3542 getPublicationTables(Archive *fout, TableInfo tblinfo[], int numTables)
3543 {
3544         PQExpBuffer query;
3545         PGresult   *res;
3546         PublicationRelInfo *pubrinfo;
3547         int                     i_tableoid;
3548         int                     i_oid;
3549         int                     i_pubname;
3550         int                     i,
3551                                 j,
3552                                 ntups;
3553
3554         if (fout->remoteVersion < 100000)
3555                 return;
3556
3557         query = createPQExpBuffer();
3558
3559         for (i = 0; i < numTables; i++)
3560         {
3561                 TableInfo  *tbinfo = &tblinfo[i];
3562
3563                 /* Only plain tables can be aded to publications. */
3564                 if (tbinfo->relkind != RELKIND_RELATION)
3565                         continue;
3566
3567                 /*
3568                  * Ignore publication membership of tables whose definitions are not
3569                  * to be dumped.
3570                  */
3571                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3572                         continue;
3573
3574                 if (g_verbose)
3575                         write_msg(NULL, "reading publication membership for table \"%s.%s\"\n",
3576                                           tbinfo->dobj.namespace->dobj.name,
3577                                           tbinfo->dobj.name);
3578
3579                 resetPQExpBuffer(query);
3580
3581                 /* Get the publication membership for the table. */
3582                 appendPQExpBuffer(query,
3583                                                   "SELECT pr.tableoid, pr.oid, p.pubname "
3584                                                   "FROM pg_catalog.pg_publication_rel pr,"
3585                                                   "     pg_catalog.pg_publication p "
3586                                                   "WHERE pr.prrelid = '%u'"
3587                                                   "  AND p.oid = pr.prpubid",
3588                                                   tbinfo->dobj.catId.oid);
3589                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3590
3591                 ntups = PQntuples(res);
3592
3593                 if (ntups == 0)
3594                 {
3595                         /*
3596                          * Table is not member of any publications. Clean up and return.
3597                          */
3598                         PQclear(res);
3599                         continue;
3600                 }
3601
3602                 i_tableoid = PQfnumber(res, "tableoid");
3603                 i_oid = PQfnumber(res, "oid");
3604                 i_pubname = PQfnumber(res, "pubname");
3605
3606                 pubrinfo = pg_malloc(ntups * sizeof(PublicationRelInfo));
3607
3608                 for (j = 0; j < ntups; j++)
3609                 {
3610                         pubrinfo[j].dobj.objType = DO_PUBLICATION_REL;
3611                         pubrinfo[j].dobj.catId.tableoid =
3612                                 atooid(PQgetvalue(res, j, i_tableoid));
3613                         pubrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
3614                         AssignDumpId(&pubrinfo[j].dobj);
3615                         pubrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
3616                         pubrinfo[j].dobj.name = tbinfo->dobj.name;
3617                         pubrinfo[j].pubname = pg_strdup(PQgetvalue(res, j, i_pubname));
3618                         pubrinfo[j].pubtable = tbinfo;
3619
3620                         /* Decide whether we want to dump it */
3621                         selectDumpablePublicationTable(&(pubrinfo[j].dobj), fout);
3622                 }
3623                 PQclear(res);
3624         }
3625         destroyPQExpBuffer(query);
3626 }
3627
3628 /*
3629  * dumpPublicationTable
3630  *        dump the definition of the given publication table mapping
3631  */
3632 static void
3633 dumpPublicationTable(Archive *fout, PublicationRelInfo *pubrinfo)
3634 {
3635         TableInfo  *tbinfo = pubrinfo->pubtable;
3636         PQExpBuffer query;
3637         char       *tag;
3638
3639         if (!(pubrinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3640                 return;
3641
3642         tag = psprintf("%s %s", pubrinfo->pubname, tbinfo->dobj.name);
3643
3644         query = createPQExpBuffer();
3645
3646         appendPQExpBuffer(query, "ALTER PUBLICATION %s ADD TABLE ONLY",
3647                                           fmtId(pubrinfo->pubname));
3648         appendPQExpBuffer(query, " %s;",
3649                                           fmtId(tbinfo->dobj.name));
3650
3651         /*
3652          * There is no point in creating drop query as drop query as the drop is
3653          * done by table drop.
3654          */
3655         ArchiveEntry(fout, pubrinfo->dobj.catId, pubrinfo->dobj.dumpId,
3656                                  tag,
3657                                  tbinfo->dobj.namespace->dobj.name,
3658                                  NULL,
3659                                  "", false,
3660                                  "PUBLICATION TABLE", SECTION_POST_DATA,
3661                                  query->data, "", NULL,
3662                                  NULL, 0,
3663                                  NULL, NULL);
3664
3665         free(tag);
3666         destroyPQExpBuffer(query);
3667 }
3668
3669 /*
3670  * Is the currently connected user a superuser?
3671  */
3672 static bool
3673 is_superuser(Archive *fout)
3674 {
3675         ArchiveHandle *AH = (ArchiveHandle *) fout;
3676         const char *val;
3677
3678         val = PQparameterStatus(AH->connection, "is_superuser");
3679
3680         if (val && strcmp(val, "on") == 0)
3681                 return true;
3682
3683         return false;
3684 }
3685
3686 /*
3687  * getSubscriptions
3688  *        get information about subscriptions
3689  */
3690 void
3691 getSubscriptions(Archive *fout)
3692 {
3693         DumpOptions *dopt = fout->dopt;
3694         PQExpBuffer query;
3695         PGresult   *res;
3696         SubscriptionInfo *subinfo;
3697         int                     i_tableoid;
3698         int                     i_oid;
3699         int                     i_subname;
3700         int                     i_rolname;
3701         int                     i_subconninfo;
3702         int                     i_subslotname;
3703         int                     i_subsynccommit;
3704         int                     i_subpublications;
3705         int                     i,
3706                                 ntups;
3707
3708         if (dopt->no_subscriptions || fout->remoteVersion < 100000)
3709                 return;
3710
3711         if (!is_superuser(fout))
3712         {
3713                 int                     n;
3714
3715                 res = ExecuteSqlQuery(fout,
3716                                                           "SELECT count(*) FROM pg_subscription "
3717                                                           "WHERE subdbid = (SELECT oid FROM pg_catalog.pg_database"
3718                                                           "                 WHERE datname = current_database())",
3719                                                           PGRES_TUPLES_OK);
3720                 n = atoi(PQgetvalue(res, 0, 0));
3721                 if (n > 0)
3722                         write_msg(NULL, "WARNING: subscriptions not dumped because current user is not a superuser\n");
3723                 PQclear(res);
3724                 return;
3725         }
3726
3727         query = createPQExpBuffer();
3728
3729         resetPQExpBuffer(query);
3730
3731         /* Get the subscriptions in current database. */
3732         appendPQExpBuffer(query,
3733                                           "SELECT s.tableoid, s.oid, s.subname,"
3734                                           "(%s s.subowner) AS rolname, "
3735                                           " s.subconninfo, s.subslotname, s.subsynccommit, "
3736                                           " s.subpublications "
3737                                           "FROM pg_catalog.pg_subscription s "
3738                                           "WHERE s.subdbid = (SELECT oid FROM pg_catalog.pg_database"
3739                                           "                   WHERE datname = current_database())",
3740                                           username_subquery);
3741         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3742
3743         ntups = PQntuples(res);
3744
3745         i_tableoid = PQfnumber(res, "tableoid");
3746         i_oid = PQfnumber(res, "oid");
3747         i_subname = PQfnumber(res, "subname");
3748         i_rolname = PQfnumber(res, "rolname");
3749         i_subconninfo = PQfnumber(res, "subconninfo");
3750         i_subslotname = PQfnumber(res, "subslotname");
3751         i_subsynccommit = PQfnumber(res, "subsynccommit");
3752         i_subpublications = PQfnumber(res, "subpublications");
3753
3754         subinfo = pg_malloc(ntups * sizeof(SubscriptionInfo));
3755
3756         for (i = 0; i < ntups; i++)
3757         {
3758                 subinfo[i].dobj.objType = DO_SUBSCRIPTION;
3759                 subinfo[i].dobj.catId.tableoid =
3760                         atooid(PQgetvalue(res, i, i_tableoid));
3761                 subinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3762                 AssignDumpId(&subinfo[i].dobj);
3763                 subinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_subname));
3764                 subinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3765                 subinfo[i].subconninfo = pg_strdup(PQgetvalue(res, i, i_subconninfo));
3766                 if (PQgetisnull(res, i, i_subslotname))
3767                         subinfo[i].subslotname = NULL;
3768                 else
3769                         subinfo[i].subslotname = pg_strdup(PQgetvalue(res, i, i_subslotname));
3770                 subinfo[i].subsynccommit =
3771                         pg_strdup(PQgetvalue(res, i, i_subsynccommit));
3772                 subinfo[i].subpublications =
3773                         pg_strdup(PQgetvalue(res, i, i_subpublications));
3774
3775                 if (strlen(subinfo[i].rolname) == 0)
3776                         write_msg(NULL, "WARNING: owner of subscription \"%s\" appears to be invalid\n",
3777                                           subinfo[i].dobj.name);
3778
3779                 /* Decide whether we want to dump it */
3780                 selectDumpableObject(&(subinfo[i].dobj), fout);
3781         }
3782         PQclear(res);
3783
3784         destroyPQExpBuffer(query);
3785 }
3786
3787 /*
3788  * dumpSubscription
3789  *        dump the definition of the given subscription
3790  */
3791 static void
3792 dumpSubscription(Archive *fout, SubscriptionInfo *subinfo)
3793 {
3794         PQExpBuffer delq;
3795         PQExpBuffer query;
3796         PQExpBuffer labelq;
3797         PQExpBuffer publications;
3798         char      **pubnames = NULL;
3799         int                     npubnames = 0;
3800         int                     i;
3801
3802         if (!(subinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
3803                 return;
3804
3805         delq = createPQExpBuffer();
3806         query = createPQExpBuffer();
3807         labelq = createPQExpBuffer();
3808
3809         appendPQExpBuffer(delq, "DROP SUBSCRIPTION %s;\n",
3810                                           fmtId(subinfo->dobj.name));
3811
3812         appendPQExpBuffer(query, "CREATE SUBSCRIPTION %s CONNECTION ",
3813                                           fmtId(subinfo->dobj.name));
3814         appendStringLiteralAH(query, subinfo->subconninfo, fout);
3815
3816         /* Build list of quoted publications and append them to query. */
3817         if (!parsePGArray(subinfo->subpublications, &pubnames, &npubnames))
3818         {
3819                 write_msg(NULL,
3820                                   "WARNING: could not parse subpublications array\n");
3821                 if (pubnames)
3822                         free(pubnames);
3823                 pubnames = NULL;
3824                 npubnames = 0;
3825         }
3826
3827         publications = createPQExpBuffer();
3828         for (i = 0; i < npubnames; i++)
3829         {
3830                 if (i > 0)
3831                         appendPQExpBufferStr(publications, ", ");
3832
3833                 appendPQExpBufferStr(publications, fmtId(pubnames[i]));
3834         }
3835
3836         appendPQExpBuffer(query, " PUBLICATION %s WITH (connect = false, slot_name = ", publications->data);
3837         if (subinfo->subslotname)
3838                 appendStringLiteralAH(query, subinfo->subslotname, fout);
3839         else
3840                 appendPQExpBufferStr(query, "NONE");
3841
3842         if (strcmp(subinfo->subsynccommit, "off") != 0)
3843                 appendPQExpBuffer(query, ", synchronous_commit = %s", fmtId(subinfo->subsynccommit));
3844
3845         appendPQExpBufferStr(query, ");\n");
3846
3847         appendPQExpBuffer(labelq, "SUBSCRIPTION %s", fmtId(subinfo->dobj.name));
3848
3849         ArchiveEntry(fout, subinfo->dobj.catId, subinfo->dobj.dumpId,
3850                                  subinfo->dobj.name,
3851                                  NULL,
3852                                  NULL,
3853                                  subinfo->rolname, false,
3854                                  "SUBSCRIPTION", SECTION_POST_DATA,
3855                                  query->data, delq->data, NULL,
3856                                  NULL, 0,
3857                                  NULL, NULL);
3858
3859         if (subinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3860                 dumpComment(fout, labelq->data,
3861                                         NULL, subinfo->rolname,
3862                                         subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
3863
3864         if (subinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3865                 dumpSecLabel(fout, labelq->data,
3866                                          NULL, subinfo->rolname,
3867                                          subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
3868
3869         destroyPQExpBuffer(publications);
3870         if (pubnames)
3871                 free(pubnames);
3872
3873         destroyPQExpBuffer(delq);
3874         destroyPQExpBuffer(query);
3875 }
3876
3877 static void
3878 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
3879                                                                                  PQExpBuffer upgrade_buffer,
3880                                                                                  Oid pg_type_oid)
3881 {
3882         PQExpBuffer upgrade_query = createPQExpBuffer();
3883         PGresult   *upgrade_res;
3884         Oid                     pg_type_array_oid;
3885
3886         appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
3887         appendPQExpBuffer(upgrade_buffer,
3888                                           "SELECT pg_catalog.binary_upgrade_set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
3889                                           pg_type_oid);
3890
3891         /* we only support old >= 8.3 for binary upgrades */
3892         appendPQExpBuffer(upgrade_query,
3893                                           "SELECT typarray "
3894                                           "FROM pg_catalog.pg_type "
3895                                           "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
3896                                           pg_type_oid);
3897
3898         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
3899
3900         pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
3901
3902         if (OidIsValid(pg_type_array_oid))
3903         {
3904                 appendPQExpBufferStr(upgrade_buffer,
3905                                                          "\n-- For binary upgrade, must preserve pg_type array oid\n");
3906                 appendPQExpBuffer(upgrade_buffer,
3907                                                   "SELECT pg_catalog.binary_upgrade_set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
3908                                                   pg_type_array_oid);
3909         }
3910
3911         PQclear(upgrade_res);
3912         destroyPQExpBuffer(upgrade_query);
3913 }
3914
3915 static bool
3916 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
3917                                                                                 PQExpBuffer upgrade_buffer,
3918                                                                                 Oid pg_rel_oid)
3919 {
3920         PQExpBuffer upgrade_query = createPQExpBuffer();
3921         PGresult   *upgrade_res;
3922         Oid                     pg_type_oid;
3923         bool            toast_set = false;
3924
3925         /* we only support old >= 8.3 for binary upgrades */
3926         appendPQExpBuffer(upgrade_query,
3927                                           "SELECT c.reltype AS crel, t.reltype AS trel "
3928                                           "FROM pg_catalog.pg_class c "
3929                                           "LEFT JOIN pg_catalog.pg_class t ON "
3930                                           "  (c.reltoastrelid = t.oid) "
3931                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
3932                                           pg_rel_oid);
3933
3934         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
3935
3936         pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
3937
3938         binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
3939                                                                                          pg_type_oid);
3940
3941         if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
3942         {
3943                 /* Toast tables do not have pg_type array rows */
3944                 Oid                     pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
3945                                                                                                                   PQfnumber(upgrade_res, "trel")));
3946
3947                 appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
3948                 appendPQExpBuffer(upgrade_buffer,
3949                                                   "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
3950                                                   pg_type_toast_oid);
3951
3952                 toast_set = true;
3953         }
3954
3955         PQclear(upgrade_res);
3956         destroyPQExpBuffer(upgrade_query);
3957
3958         return toast_set;
3959 }
3960
3961 static void
3962 binary_upgrade_set_pg_class_oids(Archive *fout,
3963                                                                  PQExpBuffer upgrade_buffer, Oid pg_class_oid,
3964                                                                  bool is_index)
3965 {
3966         PQExpBuffer upgrade_query = createPQExpBuffer();
3967         PGresult   *upgrade_res;
3968         Oid                     pg_class_reltoastrelid;
3969         Oid                     pg_index_indexrelid;
3970
3971         appendPQExpBuffer(upgrade_query,
3972                                           "SELECT c.reltoastrelid, i.indexrelid "
3973                                           "FROM pg_catalog.pg_class c LEFT JOIN "
3974                                           "pg_catalog.pg_index i ON (c.reltoastrelid = i.indrelid AND i.indisvalid) "
3975                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
3976                                           pg_class_oid);
3977
3978         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
3979
3980         pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
3981         pg_index_indexrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "indexrelid")));
3982
3983         appendPQExpBufferStr(upgrade_buffer,
3984                                                  "\n-- For binary upgrade, must preserve pg_class oids\n");
3985
3986         if (!is_index)
3987         {
3988                 appendPQExpBuffer(upgrade_buffer,
3989                                                   "SELECT pg_catalog.binary_upgrade_set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
3990                                                   pg_class_oid);
3991                 /* only tables have toast tables, not indexes */
3992                 if (OidIsValid(pg_class_reltoastrelid))
3993                 {
3994                         /*
3995                          * One complexity is that the table definition might not require
3996                          * the creation of a TOAST table, and the TOAST table might have
3997                          * been created long after table creation, when the table was
3998                          * loaded with wide data.  By setting the TOAST oid we force
3999                          * creation of the TOAST heap and TOAST index by the backend so we
4000                          * can cleanly copy the files during binary upgrade.
4001                          */
4002
4003                         appendPQExpBuffer(upgrade_buffer,
4004                                                           "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
4005                                                           pg_class_reltoastrelid);
4006
4007                         /* every toast table has an index */
4008                         appendPQExpBuffer(upgrade_buffer,
4009                                                           "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4010                                                           pg_index_indexrelid);
4011                 }
4012         }
4013         else
4014                 appendPQExpBuffer(upgrade_buffer,
4015                                                   "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4016                                                   pg_class_oid);
4017
4018         appendPQExpBufferChar(upgrade_buffer, '\n');
4019
4020         PQclear(upgrade_res);
4021         destroyPQExpBuffer(upgrade_query);
4022 }
4023
4024 /*
4025  * If the DumpableObject is a member of an extension, add a suitable
4026  * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
4027  */
4028 static void
4029 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
4030                                                                 DumpableObject *dobj,
4031                                                                 const char *objlabel)
4032 {
4033         DumpableObject *extobj = NULL;
4034         int                     i;
4035
4036         if (!dobj->ext_member)
4037                 return;
4038
4039         /*
4040          * Find the parent extension.  We could avoid this search if we wanted to
4041          * add a link field to DumpableObject, but the space costs of that would
4042          * be considerable.  We assume that member objects could only have a
4043          * direct dependency on their own extension, not any others.
4044          */
4045         for (i = 0; i < dobj->nDeps; i++)
4046         {
4047                 extobj = findObjectByDumpId(dobj->dependencies[i]);
4048                 if (extobj && extobj->objType == DO_EXTENSION)
4049                         break;
4050                 extobj = NULL;
4051         }
4052         if (extobj == NULL)
4053                 exit_horribly(NULL, "could not find parent extension for %s\n", objlabel);
4054
4055         appendPQExpBufferStr(upgrade_buffer,
4056                                                  "\n-- For binary upgrade, handle extension membership the hard way\n");
4057         appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
4058                                           fmtId(extobj->name),
4059                                           objlabel);
4060 }
4061
4062 /*
4063  * getNamespaces:
4064  *        read all namespaces in the system catalogs and return them in the
4065  * NamespaceInfo* structure
4066  *
4067  *      numNamespaces is set to the number of namespaces read in
4068  */
4069 NamespaceInfo *
4070 getNamespaces(Archive *fout, int *numNamespaces)
4071 {
4072         DumpOptions *dopt = fout->dopt;
4073         PGresult   *res;
4074         int                     ntups;
4075         int                     i;
4076         PQExpBuffer query;
4077         NamespaceInfo *nsinfo;
4078         int                     i_tableoid;
4079         int                     i_oid;
4080         int                     i_nspname;
4081         int                     i_rolname;
4082         int                     i_nspacl;
4083         int                     i_rnspacl;
4084         int                     i_initnspacl;
4085         int                     i_initrnspacl;
4086
4087         query = createPQExpBuffer();
4088
4089         /* Make sure we are in proper schema */
4090         selectSourceSchema(fout, "pg_catalog");
4091
4092         /*
4093          * we fetch all namespaces including system ones, so that every object we
4094          * read in can be linked to a containing namespace.
4095          */
4096         if (fout->remoteVersion >= 90600)
4097         {
4098                 PQExpBuffer acl_subquery = createPQExpBuffer();
4099                 PQExpBuffer racl_subquery = createPQExpBuffer();
4100                 PQExpBuffer init_acl_subquery = createPQExpBuffer();
4101                 PQExpBuffer init_racl_subquery = createPQExpBuffer();
4102
4103                 buildACLQueries(acl_subquery, racl_subquery, init_acl_subquery,
4104                                                 init_racl_subquery, "n.nspacl", "n.nspowner", "'n'",
4105                                                 dopt->binary_upgrade);
4106
4107                 appendPQExpBuffer(query, "SELECT n.tableoid, n.oid, n.nspname, "
4108                                                   "(%s nspowner) AS rolname, "
4109                                                   "%s as nspacl, "
4110                                                   "%s as rnspacl, "
4111                                                   "%s as initnspacl, "
4112                                                   "%s as initrnspacl "
4113                                                   "FROM pg_namespace n "
4114                                                   "LEFT JOIN pg_init_privs pip "
4115                                                   "ON (n.oid = pip.objoid "
4116                                                   "AND pip.classoid = 'pg_namespace'::regclass "
4117                                                   "AND pip.objsubid = 0",
4118                                                   username_subquery,
4119                                                   acl_subquery->data,
4120                                                   racl_subquery->data,
4121                                                   init_acl_subquery->data,
4122                                                   init_racl_subquery->data);
4123
4124                 /*
4125                  * When we are doing a 'clean' run, we will be dropping and recreating
4126                  * the 'public' schema (the only object which has that kind of
4127                  * treatment in the backend and which has an entry in pg_init_privs)
4128                  * and therefore we should not consider any initial privileges in
4129                  * pg_init_privs in that case.
4130                  *
4131                  * See pg_backup_archiver.c:_printTocEntry() for the details on why
4132                  * the public schema is special in this regard.
4133                  *
4134                  * Note that if the public schema is dropped and re-created, this is
4135                  * essentially a no-op because the new public schema won't have an
4136                  * entry in pg_init_privs anyway, as the entry will be removed when
4137                  * the public schema is dropped.
4138                  *
4139                  * Further, we have to handle the case where the public schema does
4140                  * not exist at all.
4141                  */
4142                 if (dopt->outputClean)
4143                         appendPQExpBuffer(query, " AND pip.objoid <> "
4144                                                                          "coalesce((select oid from pg_namespace "
4145                                                                          "where nspname = 'public'),0)");
4146
4147                 appendPQExpBuffer(query, ") ");
4148
4149                 destroyPQExpBuffer(acl_subquery);
4150                 destroyPQExpBuffer(racl_subquery);
4151                 destroyPQExpBuffer(init_acl_subquery);
4152                 destroyPQExpBuffer(init_racl_subquery);
4153         }
4154         else
4155                 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
4156                                                   "(%s nspowner) AS rolname, "
4157                                                   "nspacl, NULL as rnspacl, "
4158                                                   "NULL AS initnspacl, NULL as initrnspacl "
4159                                                   "FROM pg_namespace",
4160                                                   username_subquery);
4161
4162         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4163
4164         ntups = PQntuples(res);
4165
4166         nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
4167
4168         i_tableoid = PQfnumber(res, "tableoid");
4169         i_oid = PQfnumber(res, "oid");
4170         i_nspname = PQfnumber(res, "nspname");
4171         i_rolname = PQfnumber(res, "rolname");
4172         i_nspacl = PQfnumber(res, "nspacl");
4173         i_rnspacl = PQfnumber(res, "rnspacl");
4174         i_initnspacl = PQfnumber(res, "initnspacl");
4175         i_initrnspacl = PQfnumber(res, "initrnspacl");
4176
4177         for (i = 0; i < ntups; i++)
4178         {
4179                 nsinfo[i].dobj.objType = DO_NAMESPACE;
4180                 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4181                 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4182                 AssignDumpId(&nsinfo[i].dobj);
4183                 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
4184                 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4185                 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
4186                 nsinfo[i].rnspacl = pg_strdup(PQgetvalue(res, i, i_rnspacl));
4187                 nsinfo[i].initnspacl = pg_strdup(PQgetvalue(res, i, i_initnspacl));
4188                 nsinfo[i].initrnspacl = pg_strdup(PQgetvalue(res, i, i_initrnspacl));
4189
4190                 /* Decide whether to dump this namespace */
4191                 selectDumpableNamespace(&nsinfo[i], fout);
4192
4193                 /*
4194                  * Do not try to dump ACL if the ACL is empty or the default.
4195                  *
4196                  * This is useful because, for some schemas/objects, the only
4197                  * component we are going to try and dump is the ACL and if we can
4198                  * remove that then 'dump' goes to zero/false and we don't consider
4199                  * this object for dumping at all later on.
4200                  */
4201                 if (PQgetisnull(res, i, i_nspacl) && PQgetisnull(res, i, i_rnspacl) &&
4202                         PQgetisnull(res, i, i_initnspacl) &&
4203                         PQgetisnull(res, i, i_initrnspacl))
4204                         nsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4205
4206                 if (strlen(nsinfo[i].rolname) == 0)
4207                         write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
4208                                           nsinfo[i].dobj.name);
4209         }
4210
4211         PQclear(res);
4212         destroyPQExpBuffer(query);
4213
4214         *numNamespaces = ntups;
4215
4216         return nsinfo;
4217 }
4218
4219 /*
4220  * findNamespace:
4221  *              given a namespace OID, look up the info read by getNamespaces
4222  */
4223 static NamespaceInfo *
4224 findNamespace(Archive *fout, Oid nsoid)
4225 {
4226         NamespaceInfo *nsinfo;
4227
4228         nsinfo = findNamespaceByOid(nsoid);
4229         if (nsinfo == NULL)
4230                 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
4231         return nsinfo;
4232 }
4233
4234 /*
4235  * getExtensions:
4236  *        read all extensions in the system catalogs and return them in the
4237  * ExtensionInfo* structure
4238  *
4239  *      numExtensions is set to the number of extensions read in
4240  */
4241 ExtensionInfo *
4242 getExtensions(Archive *fout, int *numExtensions)
4243 {
4244         DumpOptions *dopt = fout->dopt;
4245         PGresult   *res;
4246         int                     ntups;
4247         int                     i;
4248         PQExpBuffer query;
4249         ExtensionInfo *extinfo;
4250         int                     i_tableoid;
4251         int                     i_oid;
4252         int                     i_extname;
4253         int                     i_nspname;
4254         int                     i_extrelocatable;
4255         int                     i_extversion;
4256         int                     i_extconfig;
4257         int                     i_extcondition;
4258
4259         /*
4260          * Before 9.1, there are no extensions.
4261          */
4262         if (fout->remoteVersion < 90100)
4263         {
4264                 *numExtensions = 0;
4265                 return NULL;
4266         }
4267
4268         query = createPQExpBuffer();
4269
4270         /* Make sure we are in proper schema */
4271         selectSourceSchema(fout, "pg_catalog");
4272
4273         appendPQExpBufferStr(query, "SELECT x.tableoid, x.oid, "
4274                                                  "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
4275                                                  "FROM pg_extension x "
4276                                                  "JOIN pg_namespace n ON n.oid = x.extnamespace");
4277
4278         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4279
4280         ntups = PQntuples(res);
4281
4282         extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
4283
4284         i_tableoid = PQfnumber(res, "tableoid");
4285         i_oid = PQfnumber(res, "oid");
4286         i_extname = PQfnumber(res, "extname");
4287         i_nspname = PQfnumber(res, "nspname");
4288         i_extrelocatable = PQfnumber(res, "extrelocatable");
4289         i_extversion = PQfnumber(res, "extversion");
4290         i_extconfig = PQfnumber(res, "extconfig");
4291         i_extcondition = PQfnumber(res, "extcondition");
4292
4293         for (i = 0; i < ntups; i++)
4294         {
4295                 extinfo[i].dobj.objType = DO_EXTENSION;
4296                 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4297                 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4298                 AssignDumpId(&extinfo[i].dobj);
4299                 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
4300                 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
4301                 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
4302                 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
4303                 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
4304                 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
4305
4306                 /* Decide whether we want to dump it */
4307                 selectDumpableExtension(&(extinfo[i]), dopt);
4308         }
4309
4310         PQclear(res);
4311         destroyPQExpBuffer(query);
4312
4313         *numExtensions = ntups;
4314
4315         return extinfo;
4316 }
4317
4318 /*
4319  * getTypes:
4320  *        read all types in the system catalogs and return them in the
4321  * TypeInfo* structure
4322  *
4323  *      numTypes is set to the number of types read in
4324  *
4325  * NB: this must run after getFuncs() because we assume we can do
4326  * findFuncByOid().
4327  */
4328 TypeInfo *
4329 getTypes(Archive *fout, int *numTypes)
4330 {
4331         DumpOptions *dopt = fout->dopt;
4332         PGresult   *res;
4333         int                     ntups;
4334         int                     i;
4335         PQExpBuffer query = createPQExpBuffer();
4336         TypeInfo   *tyinfo;
4337         ShellTypeInfo *stinfo;
4338         int                     i_tableoid;
4339         int                     i_oid;
4340         int                     i_typname;
4341         int                     i_typnamespace;
4342         int                     i_typacl;
4343         int                     i_rtypacl;
4344         int                     i_inittypacl;
4345         int                     i_initrtypacl;
4346         int                     i_rolname;
4347         int                     i_typelem;
4348         int                     i_typrelid;
4349         int                     i_typrelkind;
4350         int                     i_typtype;
4351         int                     i_typisdefined;
4352         int                     i_isarray;
4353
4354         /*
4355          * we include even the built-in types because those may be used as array
4356          * elements by user-defined types
4357          *
4358          * we filter out the built-in types when we dump out the types
4359          *
4360          * same approach for undefined (shell) types and array types
4361          *
4362          * Note: as of 8.3 we can reliably detect whether a type is an
4363          * auto-generated array type by checking the element type's typarray.
4364          * (Before that the test is capable of generating false positives.) We
4365          * still check for name beginning with '_', though, so as to avoid the
4366          * cost of the subselect probe for all standard types.  This would have to
4367          * be revisited if the backend ever allows renaming of array types.
4368          */
4369
4370         /* Make sure we are in proper schema */
4371         selectSourceSchema(fout, "pg_catalog");
4372
4373         if (fout->remoteVersion >= 90600)
4374         {
4375                 PQExpBuffer acl_subquery = createPQExpBuffer();
4376                 PQExpBuffer racl_subquery = createPQExpBuffer();
4377                 PQExpBuffer initacl_subquery = createPQExpBuffer();
4378                 PQExpBuffer initracl_subquery = createPQExpBuffer();
4379
4380                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
4381                                                 initracl_subquery, "t.typacl", "t.typowner", "'T'",
4382                                                 dopt->binary_upgrade);
4383
4384                 appendPQExpBuffer(query, "SELECT t.tableoid, t.oid, t.typname, "
4385                                                   "t.typnamespace, "
4386                                                   "%s AS typacl, "
4387                                                   "%s AS rtypacl, "
4388                                                   "%s AS inittypacl, "
4389                                                   "%s AS initrtypacl, "
4390                                                   "(%s t.typowner) AS rolname, "
4391                                                   "t.typelem, t.typrelid, "
4392                                                   "CASE WHEN t.typrelid = 0 THEN ' '::\"char\" "
4393                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = t.typrelid) END AS typrelkind, "
4394                                                   "t.typtype, t.typisdefined, "
4395                                                   "t.typname[0] = '_' AND t.typelem != 0 AND "
4396                                                   "(SELECT typarray FROM pg_type te WHERE oid = t.typelem) = t.oid AS isarray "
4397                                                   "FROM pg_type t "
4398                                                   "LEFT JOIN pg_init_privs pip ON "
4399                                                   "(t.oid = pip.objoid "
4400                                                   "AND pip.classoid = 'pg_type'::regclass "
4401                                                   "AND pip.objsubid = 0) ",
4402                                                   acl_subquery->data,
4403                                                   racl_subquery->data,
4404                                                   initacl_subquery->data,
4405                                                   initracl_subquery->data,
4406                                                   username_subquery);
4407
4408                 destroyPQExpBuffer(acl_subquery);
4409                 destroyPQExpBuffer(racl_subquery);
4410                 destroyPQExpBuffer(initacl_subquery);
4411                 destroyPQExpBuffer(initracl_subquery);
4412         }
4413         else if (fout->remoteVersion >= 90200)
4414         {
4415                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4416                                                   "typnamespace, typacl, NULL as rtypacl, "
4417                                                   "NULL AS inittypacl, NULL AS initrtypacl, "
4418                                                   "(%s typowner) AS rolname, "
4419                                                   "typelem, typrelid, "
4420                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4421                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4422                                                   "typtype, typisdefined, "
4423                                                   "typname[0] = '_' AND typelem != 0 AND "
4424                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4425                                                   "FROM pg_type",
4426                                                   username_subquery);
4427         }
4428         else if (fout->remoteVersion >= 80300)
4429         {
4430                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4431                                                   "typnamespace, NULL AS typacl, NULL as rtypacl, "
4432                                                   "NULL AS inittypacl, NULL AS initrtypacl, "
4433                                                   "(%s typowner) AS rolname, "
4434                                                   "typelem, typrelid, "
4435                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4436                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4437                                                   "typtype, typisdefined, "
4438                                                   "typname[0] = '_' AND typelem != 0 AND "
4439                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
4440                                                   "FROM pg_type",
4441                                                   username_subquery);
4442         }
4443         else
4444         {
4445                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
4446                                                   "typnamespace, NULL AS typacl, NULL as rtypacl, "
4447                                                   "NULL AS inittypacl, NULL AS initrtypacl, "
4448                                                   "(%s typowner) AS rolname, "
4449                                                   "typelem, typrelid, "
4450                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
4451                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
4452                                                   "typtype, typisdefined, "
4453                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
4454                                                   "FROM pg_type",
4455                                                   username_subquery);
4456         }
4457
4458         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4459
4460         ntups = PQntuples(res);
4461
4462         tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
4463
4464         i_tableoid = PQfnumber(res, "tableoid");
4465         i_oid = PQfnumber(res, "oid");
4466         i_typname = PQfnumber(res, "typname");
4467         i_typnamespace = PQfnumber(res, "typnamespace");
4468         i_typacl = PQfnumber(res, "typacl");
4469         i_rtypacl = PQfnumber(res, "rtypacl");
4470         i_inittypacl = PQfnumber(res, "inittypacl");
4471         i_initrtypacl = PQfnumber(res, "initrtypacl");
4472         i_rolname = PQfnumber(res, "rolname");
4473         i_typelem = PQfnumber(res, "typelem");
4474         i_typrelid = PQfnumber(res, "typrelid");
4475         i_typrelkind = PQfnumber(res, "typrelkind");
4476         i_typtype = PQfnumber(res, "typtype");
4477         i_typisdefined = PQfnumber(res, "typisdefined");
4478         i_isarray = PQfnumber(res, "isarray");
4479
4480         for (i = 0; i < ntups; i++)
4481         {
4482                 tyinfo[i].dobj.objType = DO_TYPE;
4483                 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4484                 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4485                 AssignDumpId(&tyinfo[i].dobj);
4486                 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
4487                 tyinfo[i].dobj.namespace =
4488                         findNamespace(fout,
4489                                                   atooid(PQgetvalue(res, i, i_typnamespace)));
4490                 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4491                 tyinfo[i].typacl = pg_strdup(PQgetvalue(res, i, i_typacl));
4492                 tyinfo[i].rtypacl = pg_strdup(PQgetvalue(res, i, i_rtypacl));
4493                 tyinfo[i].inittypacl = pg_strdup(PQgetvalue(res, i, i_inittypacl));
4494                 tyinfo[i].initrtypacl = pg_strdup(PQgetvalue(res, i, i_initrtypacl));
4495                 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
4496                 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
4497                 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
4498                 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
4499                 tyinfo[i].shellType = NULL;
4500
4501                 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
4502                         tyinfo[i].isDefined = true;
4503                 else
4504                         tyinfo[i].isDefined = false;
4505
4506                 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
4507                         tyinfo[i].isArray = true;
4508                 else
4509                         tyinfo[i].isArray = false;
4510
4511                 /* Decide whether we want to dump it */
4512                 selectDumpableType(&tyinfo[i], fout);
4513
4514                 /* Do not try to dump ACL if no ACL exists. */
4515                 if (PQgetisnull(res, i, i_typacl) && PQgetisnull(res, i, i_rtypacl) &&
4516                         PQgetisnull(res, i, i_inittypacl) &&
4517                         PQgetisnull(res, i, i_initrtypacl))
4518                         tyinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4519
4520                 /*
4521                  * If it's a domain, fetch info about its constraints, if any
4522                  */
4523                 tyinfo[i].nDomChecks = 0;
4524                 tyinfo[i].domChecks = NULL;
4525                 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4526                         tyinfo[i].typtype == TYPTYPE_DOMAIN)
4527                         getDomainConstraints(fout, &(tyinfo[i]));
4528
4529                 /*
4530                  * If it's a base type, make a DumpableObject representing a shell
4531                  * definition of the type.  We will need to dump that ahead of the I/O
4532                  * functions for the type.  Similarly, range types need a shell
4533                  * definition in case they have a canonicalize function.
4534                  *
4535                  * Note: the shell type doesn't have a catId.  You might think it
4536                  * should copy the base type's catId, but then it might capture the
4537                  * pg_depend entries for the type, which we don't want.
4538                  */
4539                 if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
4540                         (tyinfo[i].typtype == TYPTYPE_BASE ||
4541                          tyinfo[i].typtype == TYPTYPE_RANGE))
4542                 {
4543                         stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
4544                         stinfo->dobj.objType = DO_SHELL_TYPE;
4545                         stinfo->dobj.catId = nilCatalogId;
4546                         AssignDumpId(&stinfo->dobj);
4547                         stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
4548                         stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
4549                         stinfo->baseType = &(tyinfo[i]);
4550                         tyinfo[i].shellType = stinfo;
4551
4552                         /*
4553                          * Initially mark the shell type as not to be dumped.  We'll only
4554                          * dump it if the I/O or canonicalize functions need to be dumped;
4555                          * this is taken care of while sorting dependencies.
4556                          */
4557                         stinfo->dobj.dump = DUMP_COMPONENT_NONE;
4558                 }
4559
4560                 if (strlen(tyinfo[i].rolname) == 0)
4561                         write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
4562                                           tyinfo[i].dobj.name);
4563         }
4564
4565         *numTypes = ntups;
4566
4567         PQclear(res);
4568
4569         destroyPQExpBuffer(query);
4570
4571         return tyinfo;
4572 }
4573
4574 /*
4575  * getOperators:
4576  *        read all operators in the system catalogs and return them in the
4577  * OprInfo* structure
4578  *
4579  *      numOprs is set to the number of operators read in
4580  */
4581 OprInfo *
4582 getOperators(Archive *fout, int *numOprs)
4583 {
4584         PGresult   *res;
4585         int                     ntups;
4586         int                     i;
4587         PQExpBuffer query = createPQExpBuffer();
4588         OprInfo    *oprinfo;
4589         int                     i_tableoid;
4590         int                     i_oid;
4591         int                     i_oprname;
4592         int                     i_oprnamespace;
4593         int                     i_rolname;
4594         int                     i_oprkind;
4595         int                     i_oprcode;
4596
4597         /*
4598          * find all operators, including builtin operators; we filter out
4599          * system-defined operators at dump-out time.
4600          */
4601
4602         /* Make sure we are in proper schema */
4603         selectSourceSchema(fout, "pg_catalog");
4604
4605         appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
4606                                           "oprnamespace, "
4607                                           "(%s oprowner) AS rolname, "
4608                                           "oprkind, "
4609                                           "oprcode::oid AS oprcode "
4610                                           "FROM pg_operator",
4611                                           username_subquery);
4612
4613         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4614
4615         ntups = PQntuples(res);
4616         *numOprs = ntups;
4617
4618         oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
4619
4620         i_tableoid = PQfnumber(res, "tableoid");
4621         i_oid = PQfnumber(res, "oid");
4622         i_oprname = PQfnumber(res, "oprname");
4623         i_oprnamespace = PQfnumber(res, "oprnamespace");
4624         i_rolname = PQfnumber(res, "rolname");
4625         i_oprkind = PQfnumber(res, "oprkind");
4626         i_oprcode = PQfnumber(res, "oprcode");
4627
4628         for (i = 0; i < ntups; i++)
4629         {
4630                 oprinfo[i].dobj.objType = DO_OPERATOR;
4631                 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4632                 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4633                 AssignDumpId(&oprinfo[i].dobj);
4634                 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
4635                 oprinfo[i].dobj.namespace =
4636                         findNamespace(fout,
4637                                                   atooid(PQgetvalue(res, i, i_oprnamespace)));
4638                 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4639                 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
4640                 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
4641
4642                 /* Decide whether we want to dump it */
4643                 selectDumpableObject(&(oprinfo[i].dobj), fout);
4644
4645                 /* Operators do not currently have ACLs. */
4646                 oprinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4647
4648                 if (strlen(oprinfo[i].rolname) == 0)
4649                         write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
4650                                           oprinfo[i].dobj.name);
4651         }
4652
4653         PQclear(res);
4654
4655         destroyPQExpBuffer(query);
4656
4657         return oprinfo;
4658 }
4659
4660 /*
4661  * getCollations:
4662  *        read all collations in the system catalogs and return them in the
4663  * CollInfo* structure
4664  *
4665  *      numCollations is set to the number of collations read in
4666  */
4667 CollInfo *
4668 getCollations(Archive *fout, int *numCollations)
4669 {
4670         PGresult   *res;
4671         int                     ntups;
4672         int                     i;
4673         PQExpBuffer query;
4674         CollInfo   *collinfo;
4675         int                     i_tableoid;
4676         int                     i_oid;
4677         int                     i_collname;
4678         int                     i_collnamespace;
4679         int                     i_rolname;
4680
4681         /* Collations didn't exist pre-9.1 */
4682         if (fout->remoteVersion < 90100)
4683         {
4684                 *numCollations = 0;
4685                 return NULL;
4686         }
4687
4688         query = createPQExpBuffer();
4689
4690         /*
4691          * find all collations, including builtin collations; we filter out
4692          * system-defined collations at dump-out time.
4693          */
4694
4695         /* Make sure we are in proper schema */
4696         selectSourceSchema(fout, "pg_catalog");
4697
4698         appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
4699                                           "collnamespace, "
4700                                           "(%s collowner) AS rolname "
4701                                           "FROM pg_collation",
4702                                           username_subquery);
4703
4704         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4705
4706         ntups = PQntuples(res);
4707         *numCollations = ntups;
4708
4709         collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
4710
4711         i_tableoid = PQfnumber(res, "tableoid");
4712         i_oid = PQfnumber(res, "oid");
4713         i_collname = PQfnumber(res, "collname");
4714         i_collnamespace = PQfnumber(res, "collnamespace");
4715         i_rolname = PQfnumber(res, "rolname");
4716
4717         for (i = 0; i < ntups; i++)
4718         {
4719                 collinfo[i].dobj.objType = DO_COLLATION;
4720                 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4721                 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4722                 AssignDumpId(&collinfo[i].dobj);
4723                 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
4724                 collinfo[i].dobj.namespace =
4725                         findNamespace(fout,
4726                                                   atooid(PQgetvalue(res, i, i_collnamespace)));
4727                 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4728
4729                 /* Decide whether we want to dump it */
4730                 selectDumpableObject(&(collinfo[i].dobj), fout);
4731
4732                 /* Collations do not currently have ACLs. */
4733                 collinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4734         }
4735
4736         PQclear(res);
4737
4738         destroyPQExpBuffer(query);
4739
4740         return collinfo;
4741 }
4742
4743 /*
4744  * getConversions:
4745  *        read all conversions in the system catalogs and return them in the
4746  * ConvInfo* structure
4747  *
4748  *      numConversions is set to the number of conversions read in
4749  */
4750 ConvInfo *
4751 getConversions(Archive *fout, int *numConversions)
4752 {
4753         PGresult   *res;
4754         int                     ntups;
4755         int                     i;
4756         PQExpBuffer query;
4757         ConvInfo   *convinfo;
4758         int                     i_tableoid;
4759         int                     i_oid;
4760         int                     i_conname;
4761         int                     i_connamespace;
4762         int                     i_rolname;
4763
4764         query = createPQExpBuffer();
4765
4766         /*
4767          * find all conversions, including builtin conversions; we filter out
4768          * system-defined conversions at dump-out time.
4769          */
4770
4771         /* Make sure we are in proper schema */
4772         selectSourceSchema(fout, "pg_catalog");
4773
4774         appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4775                                           "connamespace, "
4776                                           "(%s conowner) AS rolname "
4777                                           "FROM pg_conversion",
4778                                           username_subquery);
4779
4780         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4781
4782         ntups = PQntuples(res);
4783         *numConversions = ntups;
4784
4785         convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
4786
4787         i_tableoid = PQfnumber(res, "tableoid");
4788         i_oid = PQfnumber(res, "oid");
4789         i_conname = PQfnumber(res, "conname");
4790         i_connamespace = PQfnumber(res, "connamespace");
4791         i_rolname = PQfnumber(res, "rolname");
4792
4793         for (i = 0; i < ntups; i++)
4794         {
4795                 convinfo[i].dobj.objType = DO_CONVERSION;
4796                 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4797                 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4798                 AssignDumpId(&convinfo[i].dobj);
4799                 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
4800                 convinfo[i].dobj.namespace =
4801                         findNamespace(fout,
4802                                                   atooid(PQgetvalue(res, i, i_connamespace)));
4803                 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4804
4805                 /* Decide whether we want to dump it */
4806                 selectDumpableObject(&(convinfo[i].dobj), fout);
4807
4808                 /* Conversions do not currently have ACLs. */
4809                 convinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4810         }
4811
4812         PQclear(res);
4813
4814         destroyPQExpBuffer(query);
4815
4816         return convinfo;
4817 }
4818
4819 /*
4820  * getAccessMethods:
4821  *        read all user-defined access methods in the system catalogs and return
4822  *        them in the AccessMethodInfo* structure
4823  *
4824  *      numAccessMethods is set to the number of access methods read in
4825  */
4826 AccessMethodInfo *
4827 getAccessMethods(Archive *fout, int *numAccessMethods)
4828 {
4829         PGresult   *res;
4830         int                     ntups;
4831         int                     i;
4832         PQExpBuffer query;
4833         AccessMethodInfo *aminfo;
4834         int                     i_tableoid;
4835         int                     i_oid;
4836         int                     i_amname;
4837         int                     i_amhandler;
4838         int                     i_amtype;
4839
4840         /* Before 9.6, there are no user-defined access methods */
4841         if (fout->remoteVersion < 90600)
4842         {
4843                 *numAccessMethods = 0;
4844                 return NULL;
4845         }
4846
4847         query = createPQExpBuffer();
4848
4849         /* Make sure we are in proper schema */
4850         selectSourceSchema(fout, "pg_catalog");
4851
4852         /* Select all access methods from pg_am table */
4853         appendPQExpBuffer(query, "SELECT tableoid, oid, amname, amtype, "
4854                                           "amhandler::pg_catalog.regproc AS amhandler "
4855                                           "FROM pg_am");
4856
4857         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4858
4859         ntups = PQntuples(res);
4860         *numAccessMethods = ntups;
4861
4862         aminfo = (AccessMethodInfo *) pg_malloc(ntups * sizeof(AccessMethodInfo));
4863
4864         i_tableoid = PQfnumber(res, "tableoid");
4865         i_oid = PQfnumber(res, "oid");
4866         i_amname = PQfnumber(res, "amname");
4867         i_amhandler = PQfnumber(res, "amhandler");
4868         i_amtype = PQfnumber(res, "amtype");
4869
4870         for (i = 0; i < ntups; i++)
4871         {
4872                 aminfo[i].dobj.objType = DO_ACCESS_METHOD;
4873                 aminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4874                 aminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4875                 AssignDumpId(&aminfo[i].dobj);
4876                 aminfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_amname));
4877                 aminfo[i].dobj.namespace = NULL;
4878                 aminfo[i].amhandler = pg_strdup(PQgetvalue(res, i, i_amhandler));
4879                 aminfo[i].amtype = *(PQgetvalue(res, i, i_amtype));
4880
4881                 /* Decide whether we want to dump it */
4882                 selectDumpableAccessMethod(&(aminfo[i]), fout);
4883
4884                 /* Access methods do not currently have ACLs. */
4885                 aminfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4886         }
4887
4888         PQclear(res);
4889
4890         destroyPQExpBuffer(query);
4891
4892         return aminfo;
4893 }
4894
4895
4896 /*
4897  * getOpclasses:
4898  *        read all opclasses in the system catalogs and return them in the
4899  * OpclassInfo* structure
4900  *
4901  *      numOpclasses is set to the number of opclasses read in
4902  */
4903 OpclassInfo *
4904 getOpclasses(Archive *fout, int *numOpclasses)
4905 {
4906         PGresult   *res;
4907         int                     ntups;
4908         int                     i;
4909         PQExpBuffer query = createPQExpBuffer();
4910         OpclassInfo *opcinfo;
4911         int                     i_tableoid;
4912         int                     i_oid;
4913         int                     i_opcname;
4914         int                     i_opcnamespace;
4915         int                     i_rolname;
4916
4917         /*
4918          * find all opclasses, including builtin opclasses; we filter out
4919          * system-defined opclasses at dump-out time.
4920          */
4921
4922         /* Make sure we are in proper schema */
4923         selectSourceSchema(fout, "pg_catalog");
4924
4925         appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
4926                                           "opcnamespace, "
4927                                           "(%s opcowner) AS rolname "
4928                                           "FROM pg_opclass",
4929                                           username_subquery);
4930
4931         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4932
4933         ntups = PQntuples(res);
4934         *numOpclasses = ntups;
4935
4936         opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
4937
4938         i_tableoid = PQfnumber(res, "tableoid");
4939         i_oid = PQfnumber(res, "oid");
4940         i_opcname = PQfnumber(res, "opcname");
4941         i_opcnamespace = PQfnumber(res, "opcnamespace");
4942         i_rolname = PQfnumber(res, "rolname");
4943
4944         for (i = 0; i < ntups; i++)
4945         {
4946                 opcinfo[i].dobj.objType = DO_OPCLASS;
4947                 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4948                 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4949                 AssignDumpId(&opcinfo[i].dobj);
4950                 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
4951                 opcinfo[i].dobj.namespace =
4952                         findNamespace(fout,
4953                                                   atooid(PQgetvalue(res, i, i_opcnamespace)));
4954                 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4955
4956                 /* Decide whether we want to dump it */
4957                 selectDumpableObject(&(opcinfo[i].dobj), fout);
4958
4959                 /* Op Classes do not currently have ACLs. */
4960                 opcinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
4961
4962                 if (strlen(opcinfo[i].rolname) == 0)
4963                         write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
4964                                           opcinfo[i].dobj.name);
4965         }
4966
4967         PQclear(res);
4968
4969         destroyPQExpBuffer(query);
4970
4971         return opcinfo;
4972 }
4973
4974 /*
4975  * getOpfamilies:
4976  *        read all opfamilies in the system catalogs and return them in the
4977  * OpfamilyInfo* structure
4978  *
4979  *      numOpfamilies is set to the number of opfamilies read in
4980  */
4981 OpfamilyInfo *
4982 getOpfamilies(Archive *fout, int *numOpfamilies)
4983 {
4984         PGresult   *res;
4985         int                     ntups;
4986         int                     i;
4987         PQExpBuffer query;
4988         OpfamilyInfo *opfinfo;
4989         int                     i_tableoid;
4990         int                     i_oid;
4991         int                     i_opfname;
4992         int                     i_opfnamespace;
4993         int                     i_rolname;
4994
4995         /* Before 8.3, there is no separate concept of opfamilies */
4996         if (fout->remoteVersion < 80300)
4997         {
4998                 *numOpfamilies = 0;
4999                 return NULL;
5000         }
5001
5002         query = createPQExpBuffer();
5003
5004         /*
5005          * find all opfamilies, including builtin opfamilies; we filter out
5006          * system-defined opfamilies at dump-out time.
5007          */
5008
5009         /* Make sure we are in proper schema */
5010         selectSourceSchema(fout, "pg_catalog");
5011
5012         appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
5013                                           "opfnamespace, "
5014                                           "(%s opfowner) AS rolname "
5015                                           "FROM pg_opfamily",
5016                                           username_subquery);
5017
5018         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5019
5020         ntups = PQntuples(res);
5021         *numOpfamilies = ntups;
5022
5023         opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
5024
5025         i_tableoid = PQfnumber(res, "tableoid");
5026         i_oid = PQfnumber(res, "oid");
5027         i_opfname = PQfnumber(res, "opfname");
5028         i_opfnamespace = PQfnumber(res, "opfnamespace");
5029         i_rolname = PQfnumber(res, "rolname");
5030
5031         for (i = 0; i < ntups; i++)
5032         {
5033                 opfinfo[i].dobj.objType = DO_OPFAMILY;
5034                 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5035                 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5036                 AssignDumpId(&opfinfo[i].dobj);
5037                 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
5038                 opfinfo[i].dobj.namespace =
5039                         findNamespace(fout,
5040                                                   atooid(PQgetvalue(res, i, i_opfnamespace)));
5041                 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5042
5043                 /* Decide whether we want to dump it */
5044                 selectDumpableObject(&(opfinfo[i].dobj), fout);
5045
5046                 /* Extensions do not currently have ACLs. */
5047                 opfinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5048
5049                 if (strlen(opfinfo[i].rolname) == 0)
5050                         write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
5051                                           opfinfo[i].dobj.name);
5052         }
5053
5054         PQclear(res);
5055
5056         destroyPQExpBuffer(query);
5057
5058         return opfinfo;
5059 }
5060
5061 /*
5062  * getAggregates:
5063  *        read all the user-defined aggregates in the system catalogs and
5064  * return them in the AggInfo* structure
5065  *
5066  * numAggs is set to the number of aggregates read in
5067  */
5068 AggInfo *
5069 getAggregates(Archive *fout, int *numAggs)
5070 {
5071         DumpOptions *dopt = fout->dopt;
5072         PGresult   *res;
5073         int                     ntups;
5074         int                     i;
5075         PQExpBuffer query = createPQExpBuffer();
5076         AggInfo    *agginfo;
5077         int                     i_tableoid;
5078         int                     i_oid;
5079         int                     i_aggname;
5080         int                     i_aggnamespace;
5081         int                     i_pronargs;
5082         int                     i_proargtypes;
5083         int                     i_rolname;
5084         int                     i_aggacl;
5085         int                     i_raggacl;
5086         int                     i_initaggacl;
5087         int                     i_initraggacl;
5088
5089         /* Make sure we are in proper schema */
5090         selectSourceSchema(fout, "pg_catalog");
5091
5092         /*
5093          * Find all interesting aggregates.  See comment in getFuncs() for the
5094          * rationale behind the filtering logic.
5095          */
5096         if (fout->remoteVersion >= 90600)
5097         {
5098                 PQExpBuffer acl_subquery = createPQExpBuffer();
5099                 PQExpBuffer racl_subquery = createPQExpBuffer();
5100                 PQExpBuffer initacl_subquery = createPQExpBuffer();
5101                 PQExpBuffer initracl_subquery = createPQExpBuffer();
5102
5103                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5104                                                 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5105                                                 dopt->binary_upgrade);
5106
5107                 appendPQExpBuffer(query, "SELECT p.tableoid, p.oid, "
5108                                                   "p.proname AS aggname, "
5109                                                   "p.pronamespace AS aggnamespace, "
5110                                                   "p.pronargs, p.proargtypes, "
5111                                                   "(%s p.proowner) AS rolname, "
5112                                                   "%s AS aggacl, "
5113                                                   "%s AS raggacl, "
5114                                                   "%s AS initaggacl, "
5115                                                   "%s AS initraggacl "
5116                                                   "FROM pg_proc p "
5117                                                   "LEFT JOIN pg_init_privs pip ON "
5118                                                   "(p.oid = pip.objoid "
5119                                                   "AND pip.classoid = 'pg_proc'::regclass "
5120                                                   "AND pip.objsubid = 0) "
5121                                                   "WHERE p.proisagg AND ("
5122                                                   "p.pronamespace != "
5123                                                   "(SELECT oid FROM pg_namespace "
5124                                                   "WHERE nspname = 'pg_catalog') OR "
5125                                                   "p.proacl IS DISTINCT FROM pip.initprivs",
5126                                                   username_subquery,
5127                                                   acl_subquery->data,
5128                                                   racl_subquery->data,
5129                                                   initacl_subquery->data,
5130                                                   initracl_subquery->data);
5131                 if (dopt->binary_upgrade)
5132                         appendPQExpBufferStr(query,
5133                                                                  " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5134                                                                  "classid = 'pg_proc'::regclass AND "
5135                                                                  "objid = p.oid AND "
5136                                                                  "refclassid = 'pg_extension'::regclass AND "
5137                                                                  "deptype = 'e')");
5138                 appendPQExpBufferChar(query, ')');
5139
5140                 destroyPQExpBuffer(acl_subquery);
5141                 destroyPQExpBuffer(racl_subquery);
5142                 destroyPQExpBuffer(initacl_subquery);
5143                 destroyPQExpBuffer(initracl_subquery);
5144         }
5145         else if (fout->remoteVersion >= 80200)
5146         {
5147                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5148                                                   "pronamespace AS aggnamespace, "
5149                                                   "pronargs, proargtypes, "
5150                                                   "(%s proowner) AS rolname, "
5151                                                   "proacl AS aggacl, "
5152                                                   "NULL AS raggacl, "
5153                                                   "NULL AS initaggacl, NULL AS initraggacl "
5154                                                   "FROM pg_proc p "
5155                                                   "WHERE proisagg AND ("
5156                                                   "pronamespace != "
5157                                                   "(SELECT oid FROM pg_namespace "
5158                                                   "WHERE nspname = 'pg_catalog')",
5159                                                   username_subquery);
5160                 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5161                         appendPQExpBufferStr(query,
5162                                                                  " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5163                                                                  "classid = 'pg_proc'::regclass AND "
5164                                                                  "objid = p.oid AND "
5165                                                                  "refclassid = 'pg_extension'::regclass AND "
5166                                                                  "deptype = 'e')");
5167                 appendPQExpBufferChar(query, ')');
5168         }
5169         else
5170         {
5171                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
5172                                                   "pronamespace AS aggnamespace, "
5173                                                   "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
5174                                                   "proargtypes, "
5175                                                   "(%s proowner) AS rolname, "
5176                                                   "proacl AS aggacl, "
5177                                                   "NULL AS raggacl, "
5178                                                   "NULL AS initaggacl, NULL AS initraggacl "
5179                                                   "FROM pg_proc "
5180                                                   "WHERE proisagg "
5181                                                   "AND pronamespace != "
5182                                                   "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
5183                                                   username_subquery);
5184         }
5185
5186         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5187
5188         ntups = PQntuples(res);
5189         *numAggs = ntups;
5190
5191         agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
5192
5193         i_tableoid = PQfnumber(res, "tableoid");
5194         i_oid = PQfnumber(res, "oid");
5195         i_aggname = PQfnumber(res, "aggname");
5196         i_aggnamespace = PQfnumber(res, "aggnamespace");
5197         i_pronargs = PQfnumber(res, "pronargs");
5198         i_proargtypes = PQfnumber(res, "proargtypes");
5199         i_rolname = PQfnumber(res, "rolname");
5200         i_aggacl = PQfnumber(res, "aggacl");
5201         i_raggacl = PQfnumber(res, "raggacl");
5202         i_initaggacl = PQfnumber(res, "initaggacl");
5203         i_initraggacl = PQfnumber(res, "initraggacl");
5204
5205         for (i = 0; i < ntups; i++)
5206         {
5207                 agginfo[i].aggfn.dobj.objType = DO_AGG;
5208                 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5209                 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5210                 AssignDumpId(&agginfo[i].aggfn.dobj);
5211                 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
5212                 agginfo[i].aggfn.dobj.namespace =
5213                         findNamespace(fout,
5214                                                   atooid(PQgetvalue(res, i, i_aggnamespace)));
5215                 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5216                 if (strlen(agginfo[i].aggfn.rolname) == 0)
5217                         write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
5218                                           agginfo[i].aggfn.dobj.name);
5219                 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
5220                 agginfo[i].aggfn.prorettype = InvalidOid;       /* not saved */
5221                 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
5222                 agginfo[i].aggfn.rproacl = pg_strdup(PQgetvalue(res, i, i_raggacl));
5223                 agginfo[i].aggfn.initproacl = pg_strdup(PQgetvalue(res, i, i_initaggacl));
5224                 agginfo[i].aggfn.initrproacl = pg_strdup(PQgetvalue(res, i, i_initraggacl));
5225                 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
5226                 if (agginfo[i].aggfn.nargs == 0)
5227                         agginfo[i].aggfn.argtypes = NULL;
5228                 else
5229                 {
5230                         agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
5231                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
5232                                                   agginfo[i].aggfn.argtypes,
5233                                                   agginfo[i].aggfn.nargs);
5234                 }
5235
5236                 /* Decide whether we want to dump it */
5237                 selectDumpableObject(&(agginfo[i].aggfn.dobj), fout);
5238
5239                 /* Do not try to dump ACL if no ACL exists. */
5240                 if (PQgetisnull(res, i, i_aggacl) && PQgetisnull(res, i, i_raggacl) &&
5241                         PQgetisnull(res, i, i_initaggacl) &&
5242                         PQgetisnull(res, i, i_initraggacl))
5243                         agginfo[i].aggfn.dobj.dump &= ~DUMP_COMPONENT_ACL;
5244         }
5245
5246         PQclear(res);
5247
5248         destroyPQExpBuffer(query);
5249
5250         return agginfo;
5251 }
5252
5253 /*
5254  * getFuncs:
5255  *        read all the user-defined functions in the system catalogs and
5256  * return them in the FuncInfo* structure
5257  *
5258  * numFuncs is set to the number of functions read in
5259  */
5260 FuncInfo *
5261 getFuncs(Archive *fout, int *numFuncs)
5262 {
5263         DumpOptions *dopt = fout->dopt;
5264         PGresult   *res;
5265         int                     ntups;
5266         int                     i;
5267         PQExpBuffer query = createPQExpBuffer();
5268         FuncInfo   *finfo;
5269         int                     i_tableoid;
5270         int                     i_oid;
5271         int                     i_proname;
5272         int                     i_pronamespace;
5273         int                     i_rolname;
5274         int                     i_prolang;
5275         int                     i_pronargs;
5276         int                     i_proargtypes;
5277         int                     i_prorettype;
5278         int                     i_proacl;
5279         int                     i_rproacl;
5280         int                     i_initproacl;
5281         int                     i_initrproacl;
5282
5283         /* Make sure we are in proper schema */
5284         selectSourceSchema(fout, "pg_catalog");
5285
5286         /*
5287          * Find all interesting functions.  This is a bit complicated:
5288          *
5289          * 1. Always exclude aggregates; those are handled elsewhere.
5290          *
5291          * 2. Always exclude functions that are internally dependent on something
5292          * else, since presumably those will be created as a result of creating
5293          * the something else.  This currently acts only to suppress constructor
5294          * functions for range types (so we only need it in 9.2 and up).  Note
5295          * this is OK only because the constructors don't have any dependencies
5296          * the range type doesn't have; otherwise we might not get creation
5297          * ordering correct.
5298          *
5299          * 3. Otherwise, we normally exclude functions in pg_catalog.  However, if
5300          * they're members of extensions and we are in binary-upgrade mode then
5301          * include them, since we want to dump extension members individually in
5302          * that mode.  Also, if they are used by casts or transforms then we need
5303          * to gather the information about them, though they won't be dumped if
5304          * they are built-in.  Also, in 9.6 and up, include functions in
5305          * pg_catalog if they have an ACL different from what's shown in
5306          * pg_init_privs.
5307          */
5308         if (fout->remoteVersion >= 90600)
5309         {
5310                 PQExpBuffer acl_subquery = createPQExpBuffer();
5311                 PQExpBuffer racl_subquery = createPQExpBuffer();
5312                 PQExpBuffer initacl_subquery = createPQExpBuffer();
5313                 PQExpBuffer initracl_subquery = createPQExpBuffer();
5314
5315                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5316                                                 initracl_subquery, "p.proacl", "p.proowner", "'f'",
5317                                                 dopt->binary_upgrade);
5318
5319                 appendPQExpBuffer(query,
5320                                                   "SELECT p.tableoid, p.oid, p.proname, p.prolang, "
5321                                                   "p.pronargs, p.proargtypes, p.prorettype, "
5322                                                   "%s AS proacl, "
5323                                                   "%s AS rproacl, "
5324                                                   "%s AS initproacl, "
5325                                                   "%s AS initrproacl, "
5326                                                   "p.pronamespace, "
5327                                                   "(%s p.proowner) AS rolname "
5328                                                   "FROM pg_proc p "
5329                                                   "LEFT JOIN pg_init_privs pip ON "
5330                                                   "(p.oid = pip.objoid "
5331                                                   "AND pip.classoid = 'pg_proc'::regclass "
5332                                                   "AND pip.objsubid = 0) "
5333                                                   "WHERE NOT proisagg"
5334                                                   "\n  AND NOT EXISTS (SELECT 1 FROM pg_depend "
5335                                                   "WHERE classid = 'pg_proc'::regclass AND "
5336                                                   "objid = p.oid AND deptype = 'i')"
5337                                                   "\n  AND ("
5338                                                   "\n  pronamespace != "
5339                                                   "(SELECT oid FROM pg_namespace "
5340                                                   "WHERE nspname = 'pg_catalog')"
5341                                                   "\n  OR EXISTS (SELECT 1 FROM pg_cast"
5342                                                   "\n  WHERE pg_cast.oid > %u "
5343                                                   "\n  AND p.oid = pg_cast.castfunc)"
5344                                                   "\n  OR EXISTS (SELECT 1 FROM pg_transform"
5345                                                   "\n  WHERE pg_transform.oid > %u AND "
5346                                                   "\n  (p.oid = pg_transform.trffromsql"
5347                                                   "\n  OR p.oid = pg_transform.trftosql))",
5348                                                   acl_subquery->data,
5349                                                   racl_subquery->data,
5350                                                   initacl_subquery->data,
5351                                                   initracl_subquery->data,
5352                                                   username_subquery,
5353                                                   g_last_builtin_oid,
5354                                                   g_last_builtin_oid);
5355                 if (dopt->binary_upgrade)
5356                         appendPQExpBufferStr(query,
5357                                                                  "\n  OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5358                                                                  "classid = 'pg_proc'::regclass AND "
5359                                                                  "objid = p.oid AND "
5360                                                                  "refclassid = 'pg_extension'::regclass AND "
5361                                                                  "deptype = 'e')");
5362                 appendPQExpBufferStr(query,
5363                                                          "\n  OR p.proacl IS DISTINCT FROM pip.initprivs");
5364                 appendPQExpBufferChar(query, ')');
5365
5366                 destroyPQExpBuffer(acl_subquery);
5367                 destroyPQExpBuffer(racl_subquery);
5368                 destroyPQExpBuffer(initacl_subquery);
5369                 destroyPQExpBuffer(initracl_subquery);
5370         }
5371         else
5372         {
5373                 appendPQExpBuffer(query,
5374                                                   "SELECT tableoid, oid, proname, prolang, "
5375                                                   "pronargs, proargtypes, prorettype, proacl, "
5376                                                   "NULL as rproacl, "
5377                                                   "NULL as initproacl, NULL AS initrproacl, "
5378                                                   "pronamespace, "
5379                                                   "(%s proowner) AS rolname "
5380                                                   "FROM pg_proc p "
5381                                                   "WHERE NOT proisagg",
5382                                                   username_subquery);
5383                 if (fout->remoteVersion >= 90200)
5384                         appendPQExpBufferStr(query,
5385                                                                  "\n  AND NOT EXISTS (SELECT 1 FROM pg_depend "
5386                                                                  "WHERE classid = 'pg_proc'::regclass AND "
5387                                                                  "objid = p.oid AND deptype = 'i')");
5388                 appendPQExpBuffer(query,
5389                                                   "\n  AND ("
5390                                                   "\n  pronamespace != "
5391                                                   "(SELECT oid FROM pg_namespace "
5392                                                   "WHERE nspname = 'pg_catalog')"
5393                                                   "\n  OR EXISTS (SELECT 1 FROM pg_cast"
5394                                                   "\n  WHERE pg_cast.oid > '%u'::oid"
5395                                                   "\n  AND p.oid = pg_cast.castfunc)",
5396                                                   g_last_builtin_oid);
5397
5398                 if (fout->remoteVersion >= 90500)
5399                         appendPQExpBuffer(query,
5400                                                           "\n  OR EXISTS (SELECT 1 FROM pg_transform"
5401                                                           "\n  WHERE pg_transform.oid > '%u'::oid"
5402                                                           "\n  AND (p.oid = pg_transform.trffromsql"
5403                                                           "\n  OR p.oid = pg_transform.trftosql))",
5404                                                           g_last_builtin_oid);
5405
5406                 if (dopt->binary_upgrade && fout->remoteVersion >= 90100)
5407                         appendPQExpBufferStr(query,
5408                                                                  "\n  OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5409                                                                  "classid = 'pg_proc'::regclass AND "
5410                                                                  "objid = p.oid AND "
5411                                                                  "refclassid = 'pg_extension'::regclass AND "
5412                                                                  "deptype = 'e')");
5413                 appendPQExpBufferChar(query, ')');
5414         }
5415
5416         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5417
5418         ntups = PQntuples(res);
5419
5420         *numFuncs = ntups;
5421
5422         finfo = (FuncInfo *) pg_malloc0(ntups * sizeof(FuncInfo));
5423
5424         i_tableoid = PQfnumber(res, "tableoid");
5425         i_oid = PQfnumber(res, "oid");
5426         i_proname = PQfnumber(res, "proname");
5427         i_pronamespace = PQfnumber(res, "pronamespace");
5428         i_rolname = PQfnumber(res, "rolname");
5429         i_prolang = PQfnumber(res, "prolang");
5430         i_pronargs = PQfnumber(res, "pronargs");
5431         i_proargtypes = PQfnumber(res, "proargtypes");
5432         i_prorettype = PQfnumber(res, "prorettype");
5433         i_proacl = PQfnumber(res, "proacl");
5434         i_rproacl = PQfnumber(res, "rproacl");
5435         i_initproacl = PQfnumber(res, "initproacl");
5436         i_initrproacl = PQfnumber(res, "initrproacl");
5437
5438         for (i = 0; i < ntups; i++)
5439         {
5440                 finfo[i].dobj.objType = DO_FUNC;
5441                 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5442                 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5443                 AssignDumpId(&finfo[i].dobj);
5444                 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
5445                 finfo[i].dobj.namespace =
5446                         findNamespace(fout,
5447                                                   atooid(PQgetvalue(res, i, i_pronamespace)));
5448                 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
5449                 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
5450                 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
5451                 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
5452                 finfo[i].rproacl = pg_strdup(PQgetvalue(res, i, i_rproacl));
5453                 finfo[i].initproacl = pg_strdup(PQgetvalue(res, i, i_initproacl));
5454                 finfo[i].initrproacl = pg_strdup(PQgetvalue(res, i, i_initrproacl));
5455                 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
5456                 if (finfo[i].nargs == 0)
5457                         finfo[i].argtypes = NULL;
5458                 else
5459                 {
5460                         finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
5461                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
5462                                                   finfo[i].argtypes, finfo[i].nargs);
5463                 }
5464
5465                 /* Decide whether we want to dump it */
5466                 selectDumpableObject(&(finfo[i].dobj), fout);
5467
5468                 /* Do not try to dump ACL if no ACL exists. */
5469                 if (PQgetisnull(res, i, i_proacl) && PQgetisnull(res, i, i_rproacl) &&
5470                         PQgetisnull(res, i, i_initproacl) &&
5471                         PQgetisnull(res, i, i_initrproacl))
5472                         finfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
5473
5474                 if (strlen(finfo[i].rolname) == 0)
5475                         write_msg(NULL,
5476                                           "WARNING: owner of function \"%s\" appears to be invalid\n",
5477                                           finfo[i].dobj.name);
5478         }
5479
5480         PQclear(res);
5481
5482         destroyPQExpBuffer(query);
5483
5484         return finfo;
5485 }
5486
5487 /*
5488  * getTables
5489  *        read all the tables (no indexes)
5490  * in the system catalogs return them in the TableInfo* structure
5491  *
5492  * numTables is set to the number of tables read in
5493  */
5494 TableInfo *
5495 getTables(Archive *fout, int *numTables)
5496 {
5497         DumpOptions *dopt = fout->dopt;
5498         PGresult   *res;
5499         int                     ntups;
5500         int                     i;
5501         PQExpBuffer query = createPQExpBuffer();
5502         TableInfo  *tblinfo;
5503         int                     i_reltableoid;
5504         int                     i_reloid;
5505         int                     i_relname;
5506         int                     i_relnamespace;
5507         int                     i_relkind;
5508         int                     i_relacl;
5509         int                     i_rrelacl;
5510         int                     i_initrelacl;
5511         int                     i_initrrelacl;
5512         int                     i_rolname;
5513         int                     i_relchecks;
5514         int                     i_relhastriggers;
5515         int                     i_relhasindex;
5516         int                     i_relhasrules;
5517         int                     i_relrowsec;
5518         int                     i_relforcerowsec;
5519         int                     i_relhasoids;
5520         int                     i_relfrozenxid;
5521         int                     i_relminmxid;
5522         int                     i_toastoid;
5523         int                     i_toastfrozenxid;
5524         int                     i_toastminmxid;
5525         int                     i_relpersistence;
5526         int                     i_relispopulated;
5527         int                     i_relreplident;
5528         int                     i_owning_tab;
5529         int                     i_owning_col;
5530         int                     i_reltablespace;
5531         int                     i_reloptions;
5532         int                     i_checkoption;
5533         int                     i_toastreloptions;
5534         int                     i_reloftype;
5535         int                     i_relpages;
5536         int                     i_is_identity_sequence;
5537         int                     i_changed_acl;
5538         int                     i_partkeydef;
5539         int                     i_ispartition;
5540         int                     i_partbound;
5541
5542         /* Make sure we are in proper schema */
5543         selectSourceSchema(fout, "pg_catalog");
5544
5545         /*
5546          * Find all the tables and table-like objects.
5547          *
5548          * We include system catalogs, so that we can work if a user table is
5549          * defined to inherit from a system catalog (pretty weird, but...)
5550          *
5551          * We ignore relations that are not ordinary tables, sequences, views,
5552          * materialized views, composite types, or foreign tables.
5553          *
5554          * Composite-type table entries won't be dumped as such, but we have to
5555          * make a DumpableObject for them so that we can track dependencies of the
5556          * composite type (pg_depend entries for columns of the composite type
5557          * link to the pg_class entry not the pg_type entry).
5558          *
5559          * Note: in this phase we should collect only a minimal amount of
5560          * information about each table, basically just enough to decide if it is
5561          * interesting. We must fetch all tables in this phase because otherwise
5562          * we cannot correctly identify inherited columns, owned sequences, etc.
5563          */
5564
5565         if (fout->remoteVersion >= 90600)
5566         {
5567                 char       *partkeydef = "NULL";
5568                 char       *ispartition = "false";
5569                 char       *partbound = "NULL";
5570
5571                 PQExpBuffer acl_subquery = createPQExpBuffer();
5572                 PQExpBuffer racl_subquery = createPQExpBuffer();
5573                 PQExpBuffer initacl_subquery = createPQExpBuffer();
5574                 PQExpBuffer initracl_subquery = createPQExpBuffer();
5575
5576                 PQExpBuffer attacl_subquery = createPQExpBuffer();
5577                 PQExpBuffer attracl_subquery = createPQExpBuffer();
5578                 PQExpBuffer attinitacl_subquery = createPQExpBuffer();
5579                 PQExpBuffer attinitracl_subquery = createPQExpBuffer();
5580
5581                 /*
5582                  * Collect the information about any partitioned tables, which were
5583                  * added in PG10.
5584                  */
5585
5586                 if (fout->remoteVersion >= 100000)
5587                 {
5588                         partkeydef = "pg_get_partkeydef(c.oid)";
5589                         ispartition = "c.relispartition";
5590                         partbound = "pg_get_expr(c.relpartbound, c.oid)";
5591                 }
5592
5593                 /*
5594                  * Left join to pick up dependency info linking sequences to their
5595                  * owning column, if any (note this dependency is AUTO as of 8.2)
5596                  *
5597                  * Left join to detect if any privileges are still as-set-at-init, in
5598                  * which case we won't dump out ACL commands for those.
5599                  */
5600
5601                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
5602                                                 initracl_subquery, "c.relacl", "c.relowner",
5603                                                 "CASE WHEN c.relkind = " CppAsString2(RELKIND_SEQUENCE)
5604                                                 " THEN 's' ELSE 'r' END::\"char\"",
5605                                                 dopt->binary_upgrade);
5606
5607                 buildACLQueries(attacl_subquery, attracl_subquery, attinitacl_subquery,
5608                                                 attinitracl_subquery, "at.attacl", "c.relowner", "'c'",
5609                                                 dopt->binary_upgrade);
5610
5611                 appendPQExpBuffer(query,
5612                                                   "SELECT c.tableoid, c.oid, c.relname, "
5613                                                   "%s AS relacl, %s as rrelacl, "
5614                                                   "%s AS initrelacl, %s as initrrelacl, "
5615                                                   "c.relkind, c.relnamespace, "
5616                                                   "(%s c.relowner) AS rolname, "
5617                                                   "c.relchecks, c.relhastriggers, "
5618                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
5619                                                   "c.relrowsecurity, c.relforcerowsecurity, "
5620                                                   "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
5621                                                   "tc.relfrozenxid AS tfrozenxid, "
5622                                                   "tc.relminmxid AS tminmxid, "
5623                                                   "c.relpersistence, c.relispopulated, "
5624                                                   "c.relreplident, c.relpages, "
5625                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
5626                                                   "d.refobjid AS owning_tab, "
5627                                                   "d.refobjsubid AS owning_col, "
5628                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5629                                                   "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
5630                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
5631                                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
5632                                                   "tc.reloptions AS toast_reloptions, "
5633                                                   "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, "
5634                                                   "EXISTS (SELECT 1 FROM pg_attribute at LEFT JOIN pg_init_privs pip ON "
5635                                                   "(c.oid = pip.objoid "
5636                                                   "AND pip.classoid = 'pg_class'::regclass "
5637                                                   "AND pip.objsubid = at.attnum)"
5638                                                   "WHERE at.attrelid = c.oid AND ("
5639                                                   "%s IS NOT NULL "
5640                                                   "OR %s IS NOT NULL "
5641                                                   "OR %s IS NOT NULL "
5642                                                   "OR %s IS NOT NULL"
5643                                                   "))"
5644                                                   "AS changed_acl, "
5645                                                   "%s AS partkeydef, "
5646                                                   "%s AS ispartition, "
5647                                                   "%s AS partbound "
5648                                                   "FROM pg_class c "
5649                                                   "LEFT JOIN pg_depend d ON "
5650                                                   "(c.relkind = '%c' AND "
5651                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
5652                                                   "d.objsubid = 0 AND "
5653                                                   "d.refclassid = c.tableoid AND d.deptype IN ('a', 'i')) "
5654                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5655                                                   "LEFT JOIN pg_init_privs pip ON "
5656                                                   "(c.oid = pip.objoid "
5657                                                   "AND pip.classoid = 'pg_class'::regclass "
5658                                                   "AND pip.objsubid = 0) "
5659                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c', '%c') "
5660                                                   "ORDER BY c.oid",
5661                                                   acl_subquery->data,
5662                                                   racl_subquery->data,
5663                                                   initacl_subquery->data,
5664                                                   initracl_subquery->data,
5665                                                   username_subquery,
5666                                                   RELKIND_SEQUENCE,
5667                                                   attacl_subquery->data,
5668                                                   attracl_subquery->data,
5669                                                   attinitacl_subquery->data,
5670                                                   attinitracl_subquery->data,
5671                                                   partkeydef,
5672                                                   ispartition,
5673                                                   partbound,
5674                                                   RELKIND_SEQUENCE,
5675                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
5676                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
5677                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
5678                                                   RELKIND_PARTITIONED_TABLE);
5679
5680                 destroyPQExpBuffer(acl_subquery);
5681                 destroyPQExpBuffer(racl_subquery);
5682                 destroyPQExpBuffer(initacl_subquery);
5683                 destroyPQExpBuffer(initracl_subquery);
5684
5685                 destroyPQExpBuffer(attacl_subquery);
5686                 destroyPQExpBuffer(attracl_subquery);
5687                 destroyPQExpBuffer(attinitacl_subquery);
5688                 destroyPQExpBuffer(attinitracl_subquery);
5689         }
5690         else if (fout->remoteVersion >= 90500)
5691         {
5692                 /*
5693                  * Left join to pick up dependency info linking sequences to their
5694                  * owning column, if any (note this dependency is AUTO as of 8.2)
5695                  */
5696                 appendPQExpBuffer(query,
5697                                                   "SELECT c.tableoid, c.oid, c.relname, "
5698                                                   "c.relacl, NULL as rrelacl, "
5699                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
5700                                                   "c.relkind, "
5701                                                   "c.relnamespace, "
5702                                                   "(%s c.relowner) AS rolname, "
5703                                                   "c.relchecks, c.relhastriggers, "
5704                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
5705                                                   "c.relrowsecurity, c.relforcerowsecurity, "
5706                                                   "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
5707                                                   "tc.relfrozenxid AS tfrozenxid, "
5708                                                   "tc.relminmxid AS tminmxid, "
5709                                                   "c.relpersistence, c.relispopulated, "
5710                                                   "c.relreplident, c.relpages, "
5711                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
5712                                                   "d.refobjid AS owning_tab, "
5713                                                   "d.refobjsubid AS owning_col, "
5714                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5715                                                   "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
5716                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
5717                                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
5718                                                   "tc.reloptions AS toast_reloptions, "
5719                                                   "NULL AS changed_acl, "
5720                                                   "NULL AS partkeydef, "
5721                                                   "false AS ispartition, "
5722                                                   "NULL AS partbound "
5723                                                   "FROM pg_class c "
5724                                                   "LEFT JOIN pg_depend d ON "
5725                                                   "(c.relkind = '%c' AND "
5726                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
5727                                                   "d.objsubid = 0 AND "
5728                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
5729                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5730                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
5731                                                   "ORDER BY c.oid",
5732                                                   username_subquery,
5733                                                   RELKIND_SEQUENCE,
5734                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
5735                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
5736                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
5737         }
5738         else if (fout->remoteVersion >= 90400)
5739         {
5740                 /*
5741                  * Left join to pick up dependency info linking sequences to their
5742                  * owning column, if any (note this dependency is AUTO as of 8.2)
5743                  */
5744                 appendPQExpBuffer(query,
5745                                                   "SELECT c.tableoid, c.oid, c.relname, "
5746                                                   "c.relacl, NULL as rrelacl, "
5747                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
5748                                                   "c.relkind, "
5749                                                   "c.relnamespace, "
5750                                                   "(%s c.relowner) AS rolname, "
5751                                                   "c.relchecks, c.relhastriggers, "
5752                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
5753                                                   "'f'::bool AS relrowsecurity, "
5754                                                   "'f'::bool AS relforcerowsecurity, "
5755                                                   "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
5756                                                   "tc.relfrozenxid AS tfrozenxid, "
5757                                                   "tc.relminmxid AS tminmxid, "
5758                                                   "c.relpersistence, c.relispopulated, "
5759                                                   "c.relreplident, c.relpages, "
5760                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
5761                                                   "d.refobjid AS owning_tab, "
5762                                                   "d.refobjsubid AS owning_col, "
5763                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5764                                                   "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
5765                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
5766                                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
5767                                                   "tc.reloptions AS toast_reloptions, "
5768                                                   "NULL AS changed_acl, "
5769                                                   "NULL AS partkeydef, "
5770                                                   "false AS ispartition, "
5771                                                   "NULL AS partbound "
5772                                                   "FROM pg_class c "
5773                                                   "LEFT JOIN pg_depend d ON "
5774                                                   "(c.relkind = '%c' AND "
5775                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
5776                                                   "d.objsubid = 0 AND "
5777                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
5778                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5779                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
5780                                                   "ORDER BY c.oid",
5781                                                   username_subquery,
5782                                                   RELKIND_SEQUENCE,
5783                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
5784                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
5785                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
5786         }
5787         else if (fout->remoteVersion >= 90300)
5788         {
5789                 /*
5790                  * Left join to pick up dependency info linking sequences to their
5791                  * owning column, if any (note this dependency is AUTO as of 8.2)
5792                  */
5793                 appendPQExpBuffer(query,
5794                                                   "SELECT c.tableoid, c.oid, c.relname, "
5795                                                   "c.relacl, NULL as rrelacl, "
5796                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
5797                                                   "c.relkind, "
5798                                                   "c.relnamespace, "
5799                                                   "(%s c.relowner) AS rolname, "
5800                                                   "c.relchecks, c.relhastriggers, "
5801                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
5802                                                   "'f'::bool AS relrowsecurity, "
5803                                                   "'f'::bool AS relforcerowsecurity, "
5804                                                   "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
5805                                                   "tc.relfrozenxid AS tfrozenxid, "
5806                                                   "tc.relminmxid AS tminmxid, "
5807                                                   "c.relpersistence, c.relispopulated, "
5808                                                   "'d' AS relreplident, c.relpages, "
5809                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
5810                                                   "d.refobjid AS owning_tab, "
5811                                                   "d.refobjsubid AS owning_col, "
5812                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5813                                                   "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
5814                                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
5815                                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
5816                                                   "tc.reloptions AS toast_reloptions, "
5817                                                   "NULL AS changed_acl, "
5818                                                   "NULL AS partkeydef, "
5819                                                   "false AS ispartition, "
5820                                                   "NULL AS partbound "
5821                                                   "FROM pg_class c "
5822                                                   "LEFT JOIN pg_depend d ON "
5823                                                   "(c.relkind = '%c' AND "
5824                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
5825                                                   "d.objsubid = 0 AND "
5826                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
5827                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5828                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
5829                                                   "ORDER BY c.oid",
5830                                                   username_subquery,
5831                                                   RELKIND_SEQUENCE,
5832                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
5833                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
5834                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
5835         }
5836         else if (fout->remoteVersion >= 90100)
5837         {
5838                 /*
5839                  * Left join to pick up dependency info linking sequences to their
5840                  * owning column, if any (note this dependency is AUTO as of 8.2)
5841                  */
5842                 appendPQExpBuffer(query,
5843                                                   "SELECT c.tableoid, c.oid, c.relname, "
5844                                                   "c.relacl, NULL as rrelacl, "
5845                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
5846                                                   "c.relkind, "
5847                                                   "c.relnamespace, "
5848                                                   "(%s c.relowner) AS rolname, "
5849                                                   "c.relchecks, c.relhastriggers, "
5850                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
5851                                                   "'f'::bool AS relrowsecurity, "
5852                                                   "'f'::bool AS relforcerowsecurity, "
5853                                                   "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
5854                                                   "tc.relfrozenxid AS tfrozenxid, "
5855                                                   "0 AS tminmxid, "
5856                                                   "c.relpersistence, 't' as relispopulated, "
5857                                                   "'d' AS relreplident, c.relpages, "
5858                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
5859                                                   "d.refobjid AS owning_tab, "
5860                                                   "d.refobjsubid AS owning_col, "
5861                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5862                                                   "c.reloptions AS reloptions, "
5863                                                   "tc.reloptions AS toast_reloptions, "
5864                                                   "NULL AS changed_acl, "
5865                                                   "NULL AS partkeydef, "
5866                                                   "false AS ispartition, "
5867                                                   "NULL AS partbound "
5868                                                   "FROM pg_class c "
5869                                                   "LEFT JOIN pg_depend d ON "
5870                                                   "(c.relkind = '%c' AND "
5871                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
5872                                                   "d.objsubid = 0 AND "
5873                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
5874                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5875                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
5876                                                   "ORDER BY c.oid",
5877                                                   username_subquery,
5878                                                   RELKIND_SEQUENCE,
5879                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
5880                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
5881                                                   RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
5882         }
5883         else if (fout->remoteVersion >= 90000)
5884         {
5885                 /*
5886                  * Left join to pick up dependency info linking sequences to their
5887                  * owning column, if any (note this dependency is AUTO as of 8.2)
5888                  */
5889                 appendPQExpBuffer(query,
5890                                                   "SELECT c.tableoid, c.oid, c.relname, "
5891                                                   "c.relacl, NULL as rrelacl, "
5892                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
5893                                                   "c.relkind, "
5894                                                   "c.relnamespace, "
5895                                                   "(%s c.relowner) AS rolname, "
5896                                                   "c.relchecks, c.relhastriggers, "
5897                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
5898                                                   "'f'::bool AS relrowsecurity, "
5899                                                   "'f'::bool AS relforcerowsecurity, "
5900                                                   "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
5901                                                   "tc.relfrozenxid AS tfrozenxid, "
5902                                                   "0 AS tminmxid, "
5903                                                   "'p' AS relpersistence, 't' as relispopulated, "
5904                                                   "'d' AS relreplident, c.relpages, "
5905                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
5906                                                   "d.refobjid AS owning_tab, "
5907                                                   "d.refobjsubid AS owning_col, "
5908                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5909                                                   "c.reloptions AS reloptions, "
5910                                                   "tc.reloptions AS toast_reloptions, "
5911                                                   "NULL AS changed_acl, "
5912                                                   "NULL AS partkeydef, "
5913                                                   "false AS ispartition, "
5914                                                   "NULL AS partbound "
5915                                                   "FROM pg_class c "
5916                                                   "LEFT JOIN pg_depend d ON "
5917                                                   "(c.relkind = '%c' AND "
5918                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
5919                                                   "d.objsubid = 0 AND "
5920                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
5921                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5922                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
5923                                                   "ORDER BY c.oid",
5924                                                   username_subquery,
5925                                                   RELKIND_SEQUENCE,
5926                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
5927                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
5928         }
5929         else if (fout->remoteVersion >= 80400)
5930         {
5931                 /*
5932                  * Left join to pick up dependency info linking sequences to their
5933                  * owning column, if any (note this dependency is AUTO as of 8.2)
5934                  */
5935                 appendPQExpBuffer(query,
5936                                                   "SELECT c.tableoid, c.oid, c.relname, "
5937                                                   "c.relacl, NULL as rrelacl, "
5938                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
5939                                                   "c.relkind, "
5940                                                   "c.relnamespace, "
5941                                                   "(%s c.relowner) AS rolname, "
5942                                                   "c.relchecks, c.relhastriggers, "
5943                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
5944                                                   "'f'::bool AS relrowsecurity, "
5945                                                   "'f'::bool AS relforcerowsecurity, "
5946                                                   "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
5947                                                   "tc.relfrozenxid AS tfrozenxid, "
5948                                                   "0 AS tminmxid, "
5949                                                   "'p' AS relpersistence, 't' as relispopulated, "
5950                                                   "'d' AS relreplident, c.relpages, "
5951                                                   "NULL AS reloftype, "
5952                                                   "d.refobjid AS owning_tab, "
5953                                                   "d.refobjsubid AS owning_col, "
5954                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
5955                                                   "c.reloptions AS reloptions, "
5956                                                   "tc.reloptions AS toast_reloptions, "
5957                                                   "NULL AS changed_acl, "
5958                                                   "NULL AS partkeydef, "
5959                                                   "false AS ispartition, "
5960                                                   "NULL AS partbound "
5961                                                   "FROM pg_class c "
5962                                                   "LEFT JOIN pg_depend d ON "
5963                                                   "(c.relkind = '%c' AND "
5964                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
5965                                                   "d.objsubid = 0 AND "
5966                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
5967                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
5968                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
5969                                                   "ORDER BY c.oid",
5970                                                   username_subquery,
5971                                                   RELKIND_SEQUENCE,
5972                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
5973                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
5974         }
5975         else if (fout->remoteVersion >= 80200)
5976         {
5977                 /*
5978                  * Left join to pick up dependency info linking sequences to their
5979                  * owning column, if any (note this dependency is AUTO as of 8.2)
5980                  */
5981                 appendPQExpBuffer(query,
5982                                                   "SELECT c.tableoid, c.oid, c.relname, "
5983                                                   "c.relacl, NULL as rrelacl, "
5984                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
5985                                                   "c.relkind, "
5986                                                   "c.relnamespace, "
5987                                                   "(%s c.relowner) AS rolname, "
5988                                                   "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
5989                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
5990                                                   "'f'::bool AS relrowsecurity, "
5991                                                   "'f'::bool AS relforcerowsecurity, "
5992                                                   "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
5993                                                   "tc.relfrozenxid AS tfrozenxid, "
5994                                                   "0 AS tminmxid, "
5995                                                   "'p' AS relpersistence, 't' as relispopulated, "
5996                                                   "'d' AS relreplident, c.relpages, "
5997                                                   "NULL AS reloftype, "
5998                                                   "d.refobjid AS owning_tab, "
5999                                                   "d.refobjsubid AS owning_col, "
6000                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6001                                                   "c.reloptions AS reloptions, "
6002                                                   "NULL AS toast_reloptions, "
6003                                                   "NULL AS changed_acl, "
6004                                                   "NULL AS partkeydef, "
6005                                                   "false AS ispartition, "
6006                                                   "NULL AS partbound "
6007                                                   "FROM pg_class c "
6008                                                   "LEFT JOIN pg_depend d ON "
6009                                                   "(c.relkind = '%c' AND "
6010                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6011                                                   "d.objsubid = 0 AND "
6012                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
6013                                                   "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6014                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6015                                                   "ORDER BY c.oid",
6016                                                   username_subquery,
6017                                                   RELKIND_SEQUENCE,
6018                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6019                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6020         }
6021         else
6022         {
6023                 /*
6024                  * Left join to pick up dependency info linking sequences to their
6025                  * owning column, if any
6026                  */
6027                 appendPQExpBuffer(query,
6028                                                   "SELECT c.tableoid, c.oid, relname, "
6029                                                   "relacl, NULL as rrelacl, "
6030                                                   "NULL AS initrelacl, NULL AS initrrelacl, "
6031                                                   "relkind, relnamespace, "
6032                                                   "(%s relowner) AS rolname, "
6033                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
6034                                                   "relhasindex, relhasrules, relhasoids, "
6035                                                   "'f'::bool AS relrowsecurity, "
6036                                                   "'f'::bool AS relforcerowsecurity, "
6037                                                   "0 AS relfrozenxid, 0 AS relminmxid,"
6038                                                   "0 AS toid, "
6039                                                   "0 AS tfrozenxid, 0 AS tminmxid,"
6040                                                   "'p' AS relpersistence, 't' as relispopulated, "
6041                                                   "'d' AS relreplident, relpages, "
6042                                                   "NULL AS reloftype, "
6043                                                   "d.refobjid AS owning_tab, "
6044                                                   "d.refobjsubid AS owning_col, "
6045                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6046                                                   "NULL AS reloptions, "
6047                                                   "NULL AS toast_reloptions, "
6048                                                   "NULL AS changed_acl, "
6049                                                   "NULL AS partkeydef, "
6050                                                   "false AS ispartition, "
6051                                                   "NULL AS partbound "
6052                                                   "FROM pg_class c "
6053                                                   "LEFT JOIN pg_depend d ON "
6054                                                   "(c.relkind = '%c' AND "
6055                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
6056                                                   "d.objsubid = 0 AND "
6057                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
6058                                                   "WHERE relkind in ('%c', '%c', '%c', '%c') "
6059                                                   "ORDER BY c.oid",
6060                                                   username_subquery,
6061                                                   RELKIND_SEQUENCE,
6062                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
6063                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
6064         }
6065
6066         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6067
6068         ntups = PQntuples(res);
6069
6070         *numTables = ntups;
6071
6072         /*
6073          * Extract data from result and lock dumpable tables.  We do the locking
6074          * before anything else, to minimize the window wherein a table could
6075          * disappear under us.
6076          *
6077          * Note that we have to save info about all tables here, even when dumping
6078          * only one, because we don't yet know which tables might be inheritance
6079          * ancestors of the target table.
6080          */
6081         tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
6082
6083         i_reltableoid = PQfnumber(res, "tableoid");
6084         i_reloid = PQfnumber(res, "oid");
6085         i_relname = PQfnumber(res, "relname");
6086         i_relnamespace = PQfnumber(res, "relnamespace");
6087         i_relacl = PQfnumber(res, "relacl");
6088         i_rrelacl = PQfnumber(res, "rrelacl");
6089         i_initrelacl = PQfnumber(res, "initrelacl");
6090         i_initrrelacl = PQfnumber(res, "initrrelacl");
6091         i_relkind = PQfnumber(res, "relkind");
6092         i_rolname = PQfnumber(res, "rolname");
6093         i_relchecks = PQfnumber(res, "relchecks");
6094         i_relhastriggers = PQfnumber(res, "relhastriggers");
6095         i_relhasindex = PQfnumber(res, "relhasindex");
6096         i_relhasrules = PQfnumber(res, "relhasrules");
6097         i_relrowsec = PQfnumber(res, "relrowsecurity");
6098         i_relforcerowsec = PQfnumber(res, "relforcerowsecurity");
6099         i_relhasoids = PQfnumber(res, "relhasoids");
6100         i_relfrozenxid = PQfnumber(res, "relfrozenxid");
6101         i_relminmxid = PQfnumber(res, "relminmxid");
6102         i_toastoid = PQfnumber(res, "toid");
6103         i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
6104         i_toastminmxid = PQfnumber(res, "tminmxid");
6105         i_relpersistence = PQfnumber(res, "relpersistence");
6106         i_relispopulated = PQfnumber(res, "relispopulated");
6107         i_relreplident = PQfnumber(res, "relreplident");
6108         i_relpages = PQfnumber(res, "relpages");
6109         i_owning_tab = PQfnumber(res, "owning_tab");
6110         i_owning_col = PQfnumber(res, "owning_col");
6111         i_reltablespace = PQfnumber(res, "reltablespace");
6112         i_reloptions = PQfnumber(res, "reloptions");
6113         i_checkoption = PQfnumber(res, "checkoption");
6114         i_toastreloptions = PQfnumber(res, "toast_reloptions");
6115         i_reloftype = PQfnumber(res, "reloftype");
6116         i_is_identity_sequence = PQfnumber(res, "is_identity_sequence");
6117         i_changed_acl = PQfnumber(res, "changed_acl");
6118         i_partkeydef = PQfnumber(res, "partkeydef");
6119         i_ispartition = PQfnumber(res, "ispartition");
6120         i_partbound = PQfnumber(res, "partbound");
6121
6122         if (dopt->lockWaitTimeout)
6123         {
6124                 /*
6125                  * Arrange to fail instead of waiting forever for a table lock.
6126                  *
6127                  * NB: this coding assumes that the only queries issued within the
6128                  * following loop are LOCK TABLEs; else the timeout may be undesirably
6129                  * applied to other things too.
6130                  */
6131                 resetPQExpBuffer(query);
6132                 appendPQExpBufferStr(query, "SET statement_timeout = ");
6133                 appendStringLiteralConn(query, dopt->lockWaitTimeout, GetConnection(fout));
6134                 ExecuteSqlStatement(fout, query->data);
6135         }
6136
6137         for (i = 0; i < ntups; i++)
6138         {
6139                 tblinfo[i].dobj.objType = DO_TABLE;
6140                 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
6141                 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
6142                 AssignDumpId(&tblinfo[i].dobj);
6143                 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
6144                 tblinfo[i].dobj.namespace =
6145                         findNamespace(fout,
6146                                                   atooid(PQgetvalue(res, i, i_relnamespace)));
6147                 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6148                 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
6149                 tblinfo[i].rrelacl = pg_strdup(PQgetvalue(res, i, i_rrelacl));
6150                 tblinfo[i].initrelacl = pg_strdup(PQgetvalue(res, i, i_initrelacl));
6151                 tblinfo[i].initrrelacl = pg_strdup(PQgetvalue(res, i, i_initrrelacl));
6152                 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
6153                 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
6154                 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
6155                 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
6156                 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
6157                 tblinfo[i].rowsec = (strcmp(PQgetvalue(res, i, i_relrowsec), "t") == 0);
6158                 tblinfo[i].forcerowsec = (strcmp(PQgetvalue(res, i, i_relforcerowsec), "t") == 0);
6159                 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
6160                 tblinfo[i].relispopulated = (strcmp(PQgetvalue(res, i, i_relispopulated), "t") == 0);
6161                 tblinfo[i].relreplident = *(PQgetvalue(res, i, i_relreplident));
6162                 tblinfo[i].relpages = atoi(PQgetvalue(res, i, i_relpages));
6163                 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
6164                 tblinfo[i].minmxid = atooid(PQgetvalue(res, i, i_relminmxid));
6165                 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
6166                 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
6167                 tblinfo[i].toast_minmxid = atooid(PQgetvalue(res, i, i_toastminmxid));
6168                 if (PQgetisnull(res, i, i_reloftype))
6169                         tblinfo[i].reloftype = NULL;
6170                 else
6171                         tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
6172                 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
6173                 if (PQgetisnull(res, i, i_owning_tab))
6174                 {
6175                         tblinfo[i].owning_tab = InvalidOid;
6176                         tblinfo[i].owning_col = 0;
6177                 }
6178                 else
6179                 {
6180                         tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
6181                         tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
6182                 }
6183                 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
6184                 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
6185                 if (i_checkoption == -1 || PQgetisnull(res, i, i_checkoption))
6186                         tblinfo[i].checkoption = NULL;
6187                 else
6188                         tblinfo[i].checkoption = pg_strdup(PQgetvalue(res, i, i_checkoption));
6189                 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
6190
6191                 /* other fields were zeroed above */
6192
6193                 /*
6194                  * Decide whether we want to dump this table.
6195                  */
6196                 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
6197                         tblinfo[i].dobj.dump = DUMP_COMPONENT_NONE;
6198                 else
6199                         selectDumpableTable(&tblinfo[i], fout);
6200
6201                 /*
6202                  * If the table-level and all column-level ACLs for this table are
6203                  * unchanged, then we don't need to worry about including the ACLs for
6204                  * this table.  If any column-level ACLs have been changed, the
6205                  * 'changed_acl' column from the query will indicate that.
6206                  *
6207                  * This can result in a significant performance improvement in cases
6208                  * where we are only looking to dump out the ACL (eg: pg_catalog).
6209                  */
6210                 if (PQgetisnull(res, i, i_relacl) && PQgetisnull(res, i, i_rrelacl) &&
6211                         PQgetisnull(res, i, i_initrelacl) &&
6212                         PQgetisnull(res, i, i_initrrelacl) &&
6213                         strcmp(PQgetvalue(res, i, i_changed_acl), "f") == 0)
6214                         tblinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
6215
6216                 tblinfo[i].interesting = tblinfo[i].dobj.dump ? true : false;
6217                 tblinfo[i].dummy_view = false;  /* might get set during sort */
6218                 tblinfo[i].postponed_def = false;       /* might get set during sort */
6219
6220                 tblinfo[i].is_identity_sequence = (i_is_identity_sequence >= 0 &&
6221                                                                                    strcmp(PQgetvalue(res, i, i_is_identity_sequence), "t") == 0);
6222
6223                 /* Partition key string or NULL */
6224                 tblinfo[i].partkeydef = pg_strdup(PQgetvalue(res, i, i_partkeydef));
6225                 tblinfo[i].ispartition = (strcmp(PQgetvalue(res, i, i_ispartition), "t") == 0);
6226                 tblinfo[i].partbound = pg_strdup(PQgetvalue(res, i, i_partbound));
6227
6228                 /*
6229                  * Read-lock target tables to make sure they aren't DROPPED or altered
6230                  * in schema before we get around to dumping them.
6231                  *
6232                  * Note that we don't explicitly lock parents of the target tables; we
6233                  * assume our lock on the child is enough to prevent schema
6234                  * alterations to parent tables.
6235                  *
6236                  * NOTE: it'd be kinda nice to lock other relations too, not only
6237                  * plain tables, but the backend doesn't presently allow that.
6238                  *
6239                  * We only need to lock the table for certain components; see
6240                  * pg_dump.h
6241                  */
6242                 if (tblinfo[i].dobj.dump &&
6243                         (tblinfo[i].relkind == RELKIND_RELATION ||
6244                          tblinfo->relkind == RELKIND_PARTITIONED_TABLE) &&
6245                         (tblinfo[i].dobj.dump & DUMP_COMPONENTS_REQUIRING_LOCK))
6246                 {
6247                         resetPQExpBuffer(query);
6248                         appendPQExpBuffer(query,
6249                                                           "LOCK TABLE %s IN ACCESS SHARE MODE",
6250                                                           fmtQualifiedId(fout->remoteVersion,
6251                                                                                          tblinfo[i].dobj.namespace->dobj.name,
6252                                                                                          tblinfo[i].dobj.name));
6253                         ExecuteSqlStatement(fout, query->data);
6254                 }
6255
6256                 /* Emit notice if join for owner failed */
6257                 if (strlen(tblinfo[i].rolname) == 0)
6258                         write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
6259                                           tblinfo[i].dobj.name);
6260         }
6261
6262         if (dopt->lockWaitTimeout)
6263         {
6264                 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
6265         }
6266
6267         PQclear(res);
6268
6269         destroyPQExpBuffer(query);
6270
6271         return tblinfo;
6272 }
6273
6274 /*
6275  * getOwnedSeqs
6276  *        identify owned sequences and mark them as dumpable if owning table is
6277  *
6278  * We used to do this in getTables(), but it's better to do it after the
6279  * index used by findTableByOid() has been set up.
6280  */
6281 void
6282 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
6283 {
6284         int                     i;
6285
6286         /*
6287          * Force sequences that are "owned" by table columns to be dumped whenever
6288          * their owning table is being dumped.
6289          */
6290         for (i = 0; i < numTables; i++)
6291         {
6292                 TableInfo  *seqinfo = &tblinfo[i];
6293                 TableInfo  *owning_tab;
6294
6295                 if (!OidIsValid(seqinfo->owning_tab))
6296                         continue;                       /* not an owned sequence */
6297
6298                 owning_tab = findTableByOid(seqinfo->owning_tab);
6299                 if (owning_tab == NULL)
6300                         exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
6301                                                   seqinfo->owning_tab, seqinfo->dobj.catId.oid);
6302
6303                 /*
6304                  * We need to dump the components that are being dumped for the table
6305                  * and any components which the sequence is explicitly marked with.
6306                  *
6307                  * We can't simply use the set of components which are being dumped
6308                  * for the table as the table might be in an extension (and only the
6309                  * non-extension components, eg: ACLs if changed, security labels, and
6310                  * policies, are being dumped) while the sequence is not (and
6311                  * therefore the definition and other components should also be
6312                  * dumped).
6313                  *
6314                  * If the sequence is part of the extension then it should be properly
6315                  * marked by checkExtensionMembership() and this will be a no-op as
6316                  * the table will be equivalently marked.
6317                  */
6318                 seqinfo->dobj.dump = seqinfo->dobj.dump | owning_tab->dobj.dump;
6319
6320                 if (seqinfo->dobj.dump != DUMP_COMPONENT_NONE)
6321                         seqinfo->interesting = true;
6322         }
6323 }
6324
6325 /*
6326  * getInherits
6327  *        read all the inheritance information
6328  * from the system catalogs return them in the InhInfo* structure
6329  *
6330  * numInherits is set to the number of pairs read in
6331  */
6332 InhInfo *
6333 getInherits(Archive *fout, int *numInherits)
6334 {
6335         PGresult   *res;
6336         int                     ntups;
6337         int                     i;
6338         PQExpBuffer query = createPQExpBuffer();
6339         InhInfo    *inhinfo;
6340
6341         int                     i_inhrelid;
6342         int                     i_inhparent;
6343
6344         /* Make sure we are in proper schema */
6345         selectSourceSchema(fout, "pg_catalog");
6346
6347         /*
6348          * Find all the inheritance information, excluding implicit inheritance
6349          * via partitioning.  We handle that case using getPartitions(), because
6350          * we want more information about partitions than just the parent-child
6351          * relationship.
6352          */
6353         appendPQExpBufferStr(query, "SELECT inhrelid, inhparent FROM pg_inherits");
6354
6355         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6356
6357         ntups = PQntuples(res);
6358
6359         *numInherits = ntups;
6360
6361         inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
6362
6363         i_inhrelid = PQfnumber(res, "inhrelid");
6364         i_inhparent = PQfnumber(res, "inhparent");
6365
6366         for (i = 0; i < ntups; i++)
6367         {
6368                 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
6369                 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
6370         }
6371
6372         PQclear(res);
6373
6374         destroyPQExpBuffer(query);
6375
6376         return inhinfo;
6377 }
6378
6379 /*
6380  * getIndexes
6381  *        get information about every index on a dumpable table
6382  *
6383  * Note: index data is not returned directly to the caller, but it
6384  * does get entered into the DumpableObject tables.
6385  */
6386 void
6387 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
6388 {
6389         int                     i,
6390                                 j;
6391         PQExpBuffer query = createPQExpBuffer();
6392         PGresult   *res;
6393         IndxInfo   *indxinfo;
6394         ConstraintInfo *constrinfo;
6395         int                     i_tableoid,
6396                                 i_oid,
6397                                 i_indexname,
6398                                 i_indexdef,
6399                                 i_indnkeys,
6400                                 i_indkey,
6401                                 i_indisclustered,
6402                                 i_indisreplident,
6403                                 i_contype,
6404                                 i_conname,
6405                                 i_condeferrable,
6406                                 i_condeferred,
6407                                 i_contableoid,
6408                                 i_conoid,
6409                                 i_condef,
6410                                 i_tablespace,
6411                                 i_indreloptions,
6412                                 i_relpages;
6413         int                     ntups;
6414
6415         for (i = 0; i < numTables; i++)
6416         {
6417                 TableInfo  *tbinfo = &tblinfo[i];
6418
6419                 /* Only plain tables and materialized views have indexes. */
6420                 if (tbinfo->relkind != RELKIND_RELATION &&
6421                         tbinfo->relkind != RELKIND_MATVIEW)
6422                         continue;
6423                 if (!tbinfo->hasindex)
6424                         continue;
6425
6426                 /* Ignore indexes of tables whose definitions are not to be dumped */
6427                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
6428                         continue;
6429
6430                 if (g_verbose)
6431                         write_msg(NULL, "reading indexes for table \"%s.%s\"\n",
6432                                           tbinfo->dobj.namespace->dobj.name,
6433                                           tbinfo->dobj.name);
6434
6435                 /* Make sure we are in proper schema so indexdef is right */
6436                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
6437
6438                 /*
6439                  * The point of the messy-looking outer join is to find a constraint
6440                  * that is related by an internal dependency link to the index. If we
6441                  * find one, create a CONSTRAINT entry linked to the INDEX entry.  We
6442                  * assume an index won't have more than one internal dependency.
6443                  *
6444                  * As of 9.0 we don't need to look at pg_depend but can check for a
6445                  * match to pg_constraint.conindid.  The check on conrelid is
6446                  * redundant but useful because that column is indexed while conindid
6447                  * is not.
6448                  */
6449                 resetPQExpBuffer(query);
6450                 if (fout->remoteVersion >= 90400)
6451                 {
6452                         /*
6453                          * the test on indisready is necessary in 9.2, and harmless in
6454                          * earlier/later versions
6455                          */
6456                         appendPQExpBuffer(query,
6457                                                           "SELECT t.tableoid, t.oid, "
6458                                                           "t.relname AS indexname, "
6459                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6460                                                           "t.relnatts AS indnkeys, "
6461                                                           "i.indkey, i.indisclustered, "
6462                                                           "i.indisreplident, t.relpages, "
6463                                                           "c.contype, c.conname, "
6464                                                           "c.condeferrable, c.condeferred, "
6465                                                           "c.tableoid AS contableoid, "
6466                                                           "c.oid AS conoid, "
6467                                                           "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6468                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6469                                                           "t.reloptions AS indreloptions "
6470                                                           "FROM pg_catalog.pg_index i "
6471                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6472                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6473                                                           "ON (i.indrelid = c.conrelid AND "
6474                                                           "i.indexrelid = c.conindid AND "
6475                                                           "c.contype IN ('p','u','x')) "
6476                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6477                                                           "AND i.indisvalid AND i.indisready "
6478                                                           "ORDER BY indexname",
6479                                                           tbinfo->dobj.catId.oid);
6480                 }
6481                 else if (fout->remoteVersion >= 90000)
6482                 {
6483                         /*
6484                          * the test on indisready is necessary in 9.2, and harmless in
6485                          * earlier/later versions
6486                          */
6487                         appendPQExpBuffer(query,
6488                                                           "SELECT t.tableoid, t.oid, "
6489                                                           "t.relname AS indexname, "
6490                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6491                                                           "t.relnatts AS indnkeys, "
6492                                                           "i.indkey, i.indisclustered, "
6493                                                           "false AS indisreplident, t.relpages, "
6494                                                           "c.contype, c.conname, "
6495                                                           "c.condeferrable, c.condeferred, "
6496                                                           "c.tableoid AS contableoid, "
6497                                                           "c.oid AS conoid, "
6498                                                           "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
6499                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6500                                                           "t.reloptions AS indreloptions "
6501                                                           "FROM pg_catalog.pg_index i "
6502                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6503                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6504                                                           "ON (i.indrelid = c.conrelid AND "
6505                                                           "i.indexrelid = c.conindid AND "
6506                                                           "c.contype IN ('p','u','x')) "
6507                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6508                                                           "AND i.indisvalid AND i.indisready "
6509                                                           "ORDER BY indexname",
6510                                                           tbinfo->dobj.catId.oid);
6511                 }
6512                 else if (fout->remoteVersion >= 80200)
6513                 {
6514                         appendPQExpBuffer(query,
6515                                                           "SELECT t.tableoid, t.oid, "
6516                                                           "t.relname AS indexname, "
6517                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6518                                                           "t.relnatts AS indnkeys, "
6519                                                           "i.indkey, i.indisclustered, "
6520                                                           "false AS indisreplident, t.relpages, "
6521                                                           "c.contype, c.conname, "
6522                                                           "c.condeferrable, c.condeferred, "
6523                                                           "c.tableoid AS contableoid, "
6524                                                           "c.oid AS conoid, "
6525                                                           "null AS condef, "
6526                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6527                                                           "t.reloptions AS indreloptions "
6528                                                           "FROM pg_catalog.pg_index i "
6529                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6530                                                           "LEFT JOIN pg_catalog.pg_depend d "
6531                                                           "ON (d.classid = t.tableoid "
6532                                                           "AND d.objid = t.oid "
6533                                                           "AND d.deptype = 'i') "
6534                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6535                                                           "ON (d.refclassid = c.tableoid "
6536                                                           "AND d.refobjid = c.oid) "
6537                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6538                                                           "AND i.indisvalid "
6539                                                           "ORDER BY indexname",
6540                                                           tbinfo->dobj.catId.oid);
6541                 }
6542                 else
6543                 {
6544                         appendPQExpBuffer(query,
6545                                                           "SELECT t.tableoid, t.oid, "
6546                                                           "t.relname AS indexname, "
6547                                                           "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
6548                                                           "t.relnatts AS indnkeys, "
6549                                                           "i.indkey, i.indisclustered, "
6550                                                           "false AS indisreplident, t.relpages, "
6551                                                           "c.contype, c.conname, "
6552                                                           "c.condeferrable, c.condeferred, "
6553                                                           "c.tableoid AS contableoid, "
6554                                                           "c.oid AS conoid, "
6555                                                           "null AS condef, "
6556                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
6557                                                           "null AS indreloptions "
6558                                                           "FROM pg_catalog.pg_index i "
6559                                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
6560                                                           "LEFT JOIN pg_catalog.pg_depend d "
6561                                                           "ON (d.classid = t.tableoid "
6562                                                           "AND d.objid = t.oid "
6563                                                           "AND d.deptype = 'i') "
6564                                                           "LEFT JOIN pg_catalog.pg_constraint c "
6565                                                           "ON (d.refclassid = c.tableoid "
6566                                                           "AND d.refobjid = c.oid) "
6567                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
6568                                                           "ORDER BY indexname",
6569                                                           tbinfo->dobj.catId.oid);
6570                 }
6571
6572                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6573
6574                 ntups = PQntuples(res);
6575
6576                 i_tableoid = PQfnumber(res, "tableoid");
6577                 i_oid = PQfnumber(res, "oid");
6578                 i_indexname = PQfnumber(res, "indexname");
6579                 i_indexdef = PQfnumber(res, "indexdef");
6580                 i_indnkeys = PQfnumber(res, "indnkeys");
6581                 i_indkey = PQfnumber(res, "indkey");
6582                 i_indisclustered = PQfnumber(res, "indisclustered");
6583                 i_indisreplident = PQfnumber(res, "indisreplident");
6584                 i_relpages = PQfnumber(res, "relpages");
6585                 i_contype = PQfnumber(res, "contype");
6586                 i_conname = PQfnumber(res, "conname");
6587                 i_condeferrable = PQfnumber(res, "condeferrable");
6588                 i_condeferred = PQfnumber(res, "condeferred");
6589                 i_contableoid = PQfnumber(res, "contableoid");
6590                 i_conoid = PQfnumber(res, "conoid");
6591                 i_condef = PQfnumber(res, "condef");
6592                 i_tablespace = PQfnumber(res, "tablespace");
6593                 i_indreloptions = PQfnumber(res, "indreloptions");
6594
6595                 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
6596                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
6597
6598                 for (j = 0; j < ntups; j++)
6599                 {
6600                         char            contype;
6601
6602                         indxinfo[j].dobj.objType = DO_INDEX;
6603                         indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
6604                         indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
6605                         AssignDumpId(&indxinfo[j].dobj);
6606                         indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
6607                         indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6608                         indxinfo[j].indextable = tbinfo;
6609                         indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
6610                         indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
6611                         indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
6612                         indxinfo[j].indreloptions = pg_strdup(PQgetvalue(res, j, i_indreloptions));
6613                         indxinfo[j].indkeys = (Oid *) pg_malloc(indxinfo[j].indnkeys * sizeof(Oid));
6614                         parseOidArray(PQgetvalue(res, j, i_indkey),
6615                                                   indxinfo[j].indkeys, indxinfo[j].indnkeys);
6616                         indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
6617                         indxinfo[j].indisreplident = (PQgetvalue(res, j, i_indisreplident)[0] == 't');
6618                         indxinfo[j].relpages = atoi(PQgetvalue(res, j, i_relpages));
6619                         contype = *(PQgetvalue(res, j, i_contype));
6620
6621                         if (contype == 'p' || contype == 'u' || contype == 'x')
6622                         {
6623                                 /*
6624                                  * If we found a constraint matching the index, create an
6625                                  * entry for it.
6626                                  */
6627                                 constrinfo[j].dobj.objType = DO_CONSTRAINT;
6628                                 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
6629                                 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
6630                                 AssignDumpId(&constrinfo[j].dobj);
6631                                 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
6632                                 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6633                                 constrinfo[j].contable = tbinfo;
6634                                 constrinfo[j].condomain = NULL;
6635                                 constrinfo[j].contype = contype;
6636                                 if (contype == 'x')
6637                                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
6638                                 else
6639                                         constrinfo[j].condef = NULL;
6640                                 constrinfo[j].confrelid = InvalidOid;
6641                                 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
6642                                 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
6643                                 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
6644                                 constrinfo[j].conislocal = true;
6645                                 constrinfo[j].separate = true;
6646
6647                                 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
6648                         }
6649                         else
6650                         {
6651                                 /* Plain secondary index */
6652                                 indxinfo[j].indexconstraint = 0;
6653                         }
6654                 }
6655
6656                 PQclear(res);
6657         }
6658
6659         destroyPQExpBuffer(query);
6660 }
6661
6662 /*
6663  * getExtendedStatistics
6664  *        get information about extended statistics on a dumpable table
6665  *        or materialized view.
6666  *
6667  * Note: extended statistics data is not returned directly to the caller, but
6668  * it does get entered into the DumpableObject tables.
6669  */
6670 void
6671 getExtendedStatistics(Archive *fout, TableInfo tblinfo[], int numTables)
6672 {
6673         int                     i,
6674                                 j;
6675         PQExpBuffer query;
6676         PGresult   *res;
6677         StatsExtInfo *statsextinfo;
6678         int                     ntups;
6679         int                     i_tableoid;
6680         int                     i_oid;
6681         int                     i_stxname;
6682         int                     i_stxdef;
6683
6684         /* Extended statistics were new in v10 */
6685         if (fout->remoteVersion < 100000)
6686                 return;
6687
6688         query = createPQExpBuffer();
6689
6690         for (i = 0; i < numTables; i++)
6691         {
6692                 TableInfo  *tbinfo = &tblinfo[i];
6693
6694                 /*
6695                  * Only plain tables, materialized views, foreign tables and
6696                  * partitioned tables can have extended statistics.
6697                  */
6698                 if (tbinfo->relkind != RELKIND_RELATION &&
6699                         tbinfo->relkind != RELKIND_MATVIEW &&
6700                         tbinfo->relkind != RELKIND_FOREIGN_TABLE &&
6701                         tbinfo->relkind != RELKIND_PARTITIONED_TABLE)
6702                         continue;
6703
6704                 /*
6705                  * Ignore extended statistics of tables whose definitions are not to
6706                  * be dumped.
6707                  */
6708                 if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
6709                         continue;
6710
6711                 if (g_verbose)
6712                         write_msg(NULL, "reading extended statistics for table \"%s.%s\"\n",
6713                                           tbinfo->dobj.namespace->dobj.name,
6714                                           tbinfo->dobj.name);
6715
6716                 /* Make sure we are in proper schema so stadef is right */
6717                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
6718
6719                 resetPQExpBuffer(query);
6720
6721                 appendPQExpBuffer(query,
6722                                                   "SELECT "
6723                                                   "tableoid, "
6724                                                   "oid, "
6725                                                   "stxname, "
6726                                                   "pg_catalog.pg_get_statisticsobjdef(oid) AS stxdef "
6727                                                   "FROM pg_statistic_ext "
6728                                                   "WHERE stxrelid = '%u' "
6729                                                   "ORDER BY stxname", tbinfo->dobj.catId.oid);
6730
6731                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6732
6733                 ntups = PQntuples(res);
6734
6735                 i_tableoid = PQfnumber(res, "tableoid");
6736                 i_oid = PQfnumber(res, "oid");
6737                 i_stxname = PQfnumber(res, "stxname");
6738                 i_stxdef = PQfnumber(res, "stxdef");
6739
6740                 statsextinfo = (StatsExtInfo *) pg_malloc(ntups * sizeof(StatsExtInfo));
6741
6742                 for (j = 0; j < ntups; j++)
6743                 {
6744                         statsextinfo[j].dobj.objType = DO_STATSEXT;
6745                         statsextinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
6746                         statsextinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
6747                         AssignDumpId(&statsextinfo[j].dobj);
6748                         statsextinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_stxname));
6749                         statsextinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6750                         statsextinfo[j].statsexttable = tbinfo;
6751                         statsextinfo[j].statsextdef = pg_strdup(PQgetvalue(res, j, i_stxdef));
6752                 }
6753
6754                 PQclear(res);
6755         }
6756
6757         destroyPQExpBuffer(query);
6758 }
6759
6760 /*
6761  * getConstraints
6762  *
6763  * Get info about constraints on dumpable tables.
6764  *
6765  * Currently handles foreign keys only.
6766  * Unique and primary key constraints are handled with indexes,
6767  * while check constraints are processed in getTableAttrs().
6768  */
6769 void
6770 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
6771 {
6772         int                     i,
6773                                 j;
6774         ConstraintInfo *constrinfo;
6775         PQExpBuffer query;
6776         PGresult   *res;
6777         int                     i_contableoid,
6778                                 i_conoid,
6779                                 i_conname,
6780                                 i_confrelid,
6781                                 i_condef;
6782         int                     ntups;
6783
6784         query = createPQExpBuffer();
6785
6786         for (i = 0; i < numTables; i++)
6787         {
6788                 TableInfo  *tbinfo = &tblinfo[i];
6789
6790                 if (!tbinfo->hastriggers ||
6791                         !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
6792                         continue;
6793
6794                 if (g_verbose)
6795                         write_msg(NULL, "reading foreign key constraints for table \"%s.%s\"\n",
6796                                           tbinfo->dobj.namespace->dobj.name,
6797                                           tbinfo->dobj.name);
6798
6799                 /*
6800                  * select table schema to ensure constraint expr is qualified if
6801                  * needed
6802                  */
6803                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
6804
6805                 resetPQExpBuffer(query);
6806                 appendPQExpBuffer(query,
6807                                                   "SELECT tableoid, oid, conname, confrelid, "
6808                                                   "pg_catalog.pg_get_constraintdef(oid) AS condef "
6809                                                   "FROM pg_catalog.pg_constraint "
6810                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6811                                                   "AND contype = 'f'",
6812                                                   tbinfo->dobj.catId.oid);
6813                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6814
6815                 ntups = PQntuples(res);
6816
6817                 i_contableoid = PQfnumber(res, "tableoid");
6818                 i_conoid = PQfnumber(res, "oid");
6819                 i_conname = PQfnumber(res, "conname");
6820                 i_confrelid = PQfnumber(res, "confrelid");
6821                 i_condef = PQfnumber(res, "condef");
6822
6823                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
6824
6825                 for (j = 0; j < ntups; j++)
6826                 {
6827                         constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
6828                         constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
6829                         constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
6830                         AssignDumpId(&constrinfo[j].dobj);
6831                         constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
6832                         constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
6833                         constrinfo[j].contable = tbinfo;
6834                         constrinfo[j].condomain = NULL;
6835                         constrinfo[j].contype = 'f';
6836                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
6837                         constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
6838                         constrinfo[j].conindex = 0;
6839                         constrinfo[j].condeferrable = false;
6840                         constrinfo[j].condeferred = false;
6841                         constrinfo[j].conislocal = true;
6842                         constrinfo[j].separate = true;
6843                 }
6844
6845                 PQclear(res);
6846         }
6847
6848         destroyPQExpBuffer(query);
6849 }
6850
6851 /*
6852  * getDomainConstraints
6853  *
6854  * Get info about constraints on a domain.
6855  */
6856 static void
6857 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
6858 {
6859         int                     i;
6860         ConstraintInfo *constrinfo;
6861         PQExpBuffer query;
6862         PGresult   *res;
6863         int                     i_tableoid,
6864                                 i_oid,
6865                                 i_conname,
6866                                 i_consrc;
6867         int                     ntups;
6868
6869         /*
6870          * select appropriate schema to ensure names in constraint are properly
6871          * qualified
6872          */
6873         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
6874
6875         query = createPQExpBuffer();
6876
6877         if (fout->remoteVersion >= 90100)
6878                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
6879                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6880                                                   "convalidated "
6881                                                   "FROM pg_catalog.pg_constraint "
6882                                                   "WHERE contypid = '%u'::pg_catalog.oid "
6883                                                   "ORDER BY conname",
6884                                                   tyinfo->dobj.catId.oid);
6885
6886         else
6887                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
6888                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6889                                                   "true as convalidated "
6890                                                   "FROM pg_catalog.pg_constraint "
6891                                                   "WHERE contypid = '%u'::pg_catalog.oid "
6892                                                   "ORDER BY conname",
6893                                                   tyinfo->dobj.catId.oid);
6894
6895         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6896
6897         ntups = PQntuples(res);
6898
6899         i_tableoid = PQfnumber(res, "tableoid");
6900         i_oid = PQfnumber(res, "oid");
6901         i_conname = PQfnumber(res, "conname");
6902         i_consrc = PQfnumber(res, "consrc");
6903
6904         constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
6905
6906         tyinfo->nDomChecks = ntups;
6907         tyinfo->domChecks = constrinfo;
6908
6909         for (i = 0; i < ntups; i++)
6910         {
6911                 bool            validated = PQgetvalue(res, i, 4)[0] == 't';
6912
6913                 constrinfo[i].dobj.objType = DO_CONSTRAINT;
6914                 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6915                 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6916                 AssignDumpId(&constrinfo[i].dobj);
6917                 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
6918                 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
6919                 constrinfo[i].contable = NULL;
6920                 constrinfo[i].condomain = tyinfo;
6921                 constrinfo[i].contype = 'c';
6922                 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
6923                 constrinfo[i].confrelid = InvalidOid;
6924                 constrinfo[i].conindex = 0;
6925                 constrinfo[i].condeferrable = false;
6926                 constrinfo[i].condeferred = false;
6927                 constrinfo[i].conislocal = true;
6928
6929                 constrinfo[i].separate = !validated;
6930
6931                 /*
6932                  * Make the domain depend on the constraint, ensuring it won't be
6933                  * output till any constraint dependencies are OK.  If the constraint
6934                  * has not been validated, it's going to be dumped after the domain
6935                  * anyway, so this doesn't matter.
6936                  */
6937                 if (validated)
6938                         addObjectDependency(&tyinfo->dobj,
6939                                                                 constrinfo[i].dobj.dumpId);
6940         }
6941
6942         PQclear(res);
6943
6944         destroyPQExpBuffer(query);
6945 }
6946
6947 /*
6948  * getRules
6949  *        get basic information about every rule in the system
6950  *
6951  * numRules is set to the number of rules read in
6952  */
6953 RuleInfo *
6954 getRules(Archive *fout, int *numRules)
6955 {
6956         PGresult   *res;
6957         int                     ntups;
6958         int                     i;
6959         PQExpBuffer query = createPQExpBuffer();
6960         RuleInfo   *ruleinfo;
6961         int                     i_tableoid;
6962         int                     i_oid;
6963         int                     i_rulename;
6964         int                     i_ruletable;
6965         int                     i_ev_type;
6966         int                     i_is_instead;
6967         int                     i_ev_enabled;
6968
6969         /* Make sure we are in proper schema */
6970         selectSourceSchema(fout, "pg_catalog");
6971
6972         if (fout->remoteVersion >= 80300)
6973         {
6974                 appendPQExpBufferStr(query, "SELECT "
6975                                                          "tableoid, oid, rulename, "
6976                                                          "ev_class AS ruletable, ev_type, is_instead, "
6977                                                          "ev_enabled "
6978                                                          "FROM pg_rewrite "
6979                                                          "ORDER BY oid");
6980         }
6981         else
6982         {
6983                 appendPQExpBufferStr(query, "SELECT "
6984                                                          "tableoid, oid, rulename, "
6985                                                          "ev_class AS ruletable, ev_type, is_instead, "
6986                                                          "'O'::char AS ev_enabled "
6987                                                          "FROM pg_rewrite "
6988                                                          "ORDER BY oid");
6989         }
6990
6991         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6992
6993         ntups = PQntuples(res);
6994
6995         *numRules = ntups;
6996
6997         ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
6998
6999         i_tableoid = PQfnumber(res, "tableoid");
7000         i_oid = PQfnumber(res, "oid");
7001         i_rulename = PQfnumber(res, "rulename");
7002         i_ruletable = PQfnumber(res, "ruletable");
7003         i_ev_type = PQfnumber(res, "ev_type");
7004         i_is_instead = PQfnumber(res, "is_instead");
7005         i_ev_enabled = PQfnumber(res, "ev_enabled");
7006
7007         for (i = 0; i < ntups; i++)
7008         {
7009                 Oid                     ruletableoid;
7010
7011                 ruleinfo[i].dobj.objType = DO_RULE;
7012                 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7013                 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7014                 AssignDumpId(&ruleinfo[i].dobj);
7015                 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
7016                 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
7017                 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
7018                 if (ruleinfo[i].ruletable == NULL)
7019                         exit_horribly(NULL, "failed sanity check, parent table with OID %u of pg_rewrite entry with OID %u not found\n",
7020                                                   ruletableoid, ruleinfo[i].dobj.catId.oid);
7021                 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
7022                 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
7023                 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
7024                 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
7025                 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
7026                 if (ruleinfo[i].ruletable)
7027                 {
7028                         /*
7029                          * If the table is a view or materialized view, force its ON
7030                          * SELECT rule to be sorted before the view itself --- this
7031                          * ensures that any dependencies for the rule affect the table's
7032                          * positioning. Other rules are forced to appear after their
7033                          * table.
7034                          */
7035                         if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
7036                                  ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
7037                                 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
7038                         {
7039                                 addObjectDependency(&ruleinfo[i].ruletable->dobj,
7040                                                                         ruleinfo[i].dobj.dumpId);
7041                                 /* We'll merge the rule into CREATE VIEW, if possible */
7042                                 ruleinfo[i].separate = false;
7043                         }
7044                         else
7045                         {
7046                                 addObjectDependency(&ruleinfo[i].dobj,
7047                                                                         ruleinfo[i].ruletable->dobj.dumpId);
7048                                 ruleinfo[i].separate = true;
7049                         }
7050                 }
7051                 else
7052                         ruleinfo[i].separate = true;
7053         }
7054
7055         PQclear(res);
7056
7057         destroyPQExpBuffer(query);
7058
7059         return ruleinfo;
7060 }
7061
7062 /*
7063  * getTriggers
7064  *        get information about every trigger on a dumpable table
7065  *
7066  * Note: trigger data is not returned directly to the caller, but it
7067  * does get entered into the DumpableObject tables.
7068  */
7069 void
7070 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
7071 {
7072         int                     i,
7073                                 j;
7074         PQExpBuffer query = createPQExpBuffer();
7075         PGresult   *res;
7076         TriggerInfo *tginfo;
7077         int                     i_tableoid,
7078                                 i_oid,
7079                                 i_tgname,
7080                                 i_tgfname,
7081                                 i_tgtype,
7082                                 i_tgnargs,
7083                                 i_tgargs,
7084                                 i_tgisconstraint,
7085                                 i_tgconstrname,
7086                                 i_tgconstrrelid,
7087                                 i_tgconstrrelname,
7088                                 i_tgenabled,
7089                                 i_tgdeferrable,
7090                                 i_tginitdeferred,
7091                                 i_tgdef;
7092         int                     ntups;
7093
7094         for (i = 0; i < numTables; i++)
7095         {
7096                 TableInfo  *tbinfo = &tblinfo[i];
7097
7098                 if (!tbinfo->hastriggers ||
7099                         !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7100                         continue;
7101
7102                 if (g_verbose)
7103                         write_msg(NULL, "reading triggers for table \"%s.%s\"\n",
7104                                           tbinfo->dobj.namespace->dobj.name,
7105                                           tbinfo->dobj.name);
7106
7107                 /*
7108                  * select table schema to ensure regproc name is qualified if needed
7109                  */
7110                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
7111
7112                 resetPQExpBuffer(query);
7113                 if (fout->remoteVersion >= 90000)
7114                 {
7115                         /*
7116                          * NB: think not to use pretty=true in pg_get_triggerdef.  It
7117                          * could result in non-forward-compatible dumps of WHEN clauses
7118                          * due to under-parenthesization.
7119                          */
7120                         appendPQExpBuffer(query,
7121                                                           "SELECT tgname, "
7122                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
7123                                                           "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
7124                                                           "tgenabled, tableoid, oid "
7125                                                           "FROM pg_catalog.pg_trigger t "
7126                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
7127                                                           "AND NOT tgisinternal",
7128                                                           tbinfo->dobj.catId.oid);
7129                 }
7130                 else if (fout->remoteVersion >= 80300)
7131                 {
7132                         /*
7133                          * We ignore triggers that are tied to a foreign-key constraint
7134                          */
7135                         appendPQExpBuffer(query,
7136                                                           "SELECT tgname, "
7137                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
7138                                                           "tgtype, tgnargs, tgargs, tgenabled, "
7139                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
7140                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
7141                                                           "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7142                                                           "FROM pg_catalog.pg_trigger t "
7143                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
7144                                                           "AND tgconstraint = 0",
7145                                                           tbinfo->dobj.catId.oid);
7146                 }
7147                 else
7148                 {
7149                         /*
7150                          * We ignore triggers that are tied to a foreign-key constraint,
7151                          * but in these versions we have to grovel through pg_constraint
7152                          * to find out
7153                          */
7154                         appendPQExpBuffer(query,
7155                                                           "SELECT tgname, "
7156                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
7157                                                           "tgtype, tgnargs, tgargs, tgenabled, "
7158                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
7159                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
7160                                                           "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7161                                                           "FROM pg_catalog.pg_trigger t "
7162                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
7163                                                           "AND (NOT tgisconstraint "
7164                                                           " OR NOT EXISTS"
7165                                                           "  (SELECT 1 FROM pg_catalog.pg_depend d "
7166                                                           "   JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
7167                                                           "   WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
7168                                                           tbinfo->dobj.catId.oid);
7169                 }
7170
7171                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7172
7173                 ntups = PQntuples(res);
7174
7175                 i_tableoid = PQfnumber(res, "tableoid");
7176                 i_oid = PQfnumber(res, "oid");
7177                 i_tgname = PQfnumber(res, "tgname");
7178                 i_tgfname = PQfnumber(res, "tgfname");
7179                 i_tgtype = PQfnumber(res, "tgtype");
7180                 i_tgnargs = PQfnumber(res, "tgnargs");
7181                 i_tgargs = PQfnumber(res, "tgargs");
7182                 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
7183                 i_tgconstrname = PQfnumber(res, "tgconstrname");
7184                 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
7185                 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
7186                 i_tgenabled = PQfnumber(res, "tgenabled");
7187                 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
7188                 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
7189                 i_tgdef = PQfnumber(res, "tgdef");
7190
7191                 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
7192
7193                 tbinfo->numTriggers = ntups;
7194                 tbinfo->triggers = tginfo;
7195
7196                 for (j = 0; j < ntups; j++)
7197                 {
7198                         tginfo[j].dobj.objType = DO_TRIGGER;
7199                         tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
7200                         tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
7201                         AssignDumpId(&tginfo[j].dobj);
7202                         tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
7203                         tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
7204                         tginfo[j].tgtable = tbinfo;
7205                         tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
7206                         if (i_tgdef >= 0)
7207                         {
7208                                 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
7209
7210                                 /* remaining fields are not valid if we have tgdef */
7211                                 tginfo[j].tgfname = NULL;
7212                                 tginfo[j].tgtype = 0;
7213                                 tginfo[j].tgnargs = 0;
7214                                 tginfo[j].tgargs = NULL;
7215                                 tginfo[j].tgisconstraint = false;
7216                                 tginfo[j].tgdeferrable = false;
7217                                 tginfo[j].tginitdeferred = false;
7218                                 tginfo[j].tgconstrname = NULL;
7219                                 tginfo[j].tgconstrrelid = InvalidOid;
7220                                 tginfo[j].tgconstrrelname = NULL;
7221                         }
7222                         else
7223                         {
7224                                 tginfo[j].tgdef = NULL;
7225
7226                                 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
7227                                 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
7228                                 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
7229                                 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
7230                                 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
7231                                 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
7232                                 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
7233
7234                                 if (tginfo[j].tgisconstraint)
7235                                 {
7236                                         tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
7237                                         tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
7238                                         if (OidIsValid(tginfo[j].tgconstrrelid))
7239                                         {
7240                                                 if (PQgetisnull(res, j, i_tgconstrrelname))
7241                                                         exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
7242                                                                                   tginfo[j].dobj.name,
7243                                                                                   tbinfo->dobj.name,
7244                                                                                   tginfo[j].tgconstrrelid);
7245                                                 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
7246                                         }
7247                                         else
7248                                                 tginfo[j].tgconstrrelname = NULL;
7249                                 }
7250                                 else
7251                                 {
7252                                         tginfo[j].tgconstrname = NULL;
7253                                         tginfo[j].tgconstrrelid = InvalidOid;
7254                                         tginfo[j].tgconstrrelname = NULL;
7255                                 }
7256                         }
7257                 }
7258
7259                 PQclear(res);
7260         }
7261
7262         destroyPQExpBuffer(query);
7263 }
7264
7265 /*
7266  * getEventTriggers
7267  *        get information about event triggers
7268  */
7269 EventTriggerInfo *
7270 getEventTriggers(Archive *fout, int *numEventTriggers)
7271 {
7272         int                     i;
7273         PQExpBuffer query;
7274         PGresult   *res;
7275         EventTriggerInfo *evtinfo;
7276         int                     i_tableoid,
7277                                 i_oid,
7278                                 i_evtname,
7279                                 i_evtevent,
7280                                 i_evtowner,
7281                                 i_evttags,
7282                                 i_evtfname,
7283                                 i_evtenabled;
7284         int                     ntups;
7285
7286         /* Before 9.3, there are no event triggers */
7287         if (fout->remoteVersion < 90300)
7288         {
7289                 *numEventTriggers = 0;
7290                 return NULL;
7291         }
7292
7293         query = createPQExpBuffer();
7294
7295         /* Make sure we are in proper schema */
7296         selectSourceSchema(fout, "pg_catalog");
7297
7298         appendPQExpBuffer(query,
7299                                           "SELECT e.tableoid, e.oid, evtname, evtenabled, "
7300                                           "evtevent, (%s evtowner) AS evtowner, "
7301                                           "array_to_string(array("
7302                                           "select quote_literal(x) "
7303                                           " from unnest(evttags) as t(x)), ', ') as evttags, "
7304                                           "e.evtfoid::regproc as evtfname "
7305                                           "FROM pg_event_trigger e "
7306                                           "ORDER BY e.oid",
7307                                           username_subquery);
7308
7309         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7310
7311         ntups = PQntuples(res);
7312
7313         *numEventTriggers = ntups;
7314
7315         evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
7316
7317         i_tableoid = PQfnumber(res, "tableoid");
7318         i_oid = PQfnumber(res, "oid");
7319         i_evtname = PQfnumber(res, "evtname");
7320         i_evtevent = PQfnumber(res, "evtevent");
7321         i_evtowner = PQfnumber(res, "evtowner");
7322         i_evttags = PQfnumber(res, "evttags");
7323         i_evtfname = PQfnumber(res, "evtfname");
7324         i_evtenabled = PQfnumber(res, "evtenabled");
7325
7326         for (i = 0; i < ntups; i++)
7327         {
7328                 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
7329                 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7330                 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7331                 AssignDumpId(&evtinfo[i].dobj);
7332                 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
7333                 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
7334                 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
7335                 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
7336                 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
7337                 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
7338                 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
7339
7340                 /* Decide whether we want to dump it */
7341                 selectDumpableObject(&(evtinfo[i].dobj), fout);
7342
7343                 /* Event Triggers do not currently have ACLs. */
7344                 evtinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7345         }
7346
7347         PQclear(res);
7348
7349         destroyPQExpBuffer(query);
7350
7351         return evtinfo;
7352 }
7353
7354 /*
7355  * getProcLangs
7356  *        get basic information about every procedural language in the system
7357  *
7358  * numProcLangs is set to the number of langs read in
7359  *
7360  * NB: this must run after getFuncs() because we assume we can do
7361  * findFuncByOid().
7362  */
7363 ProcLangInfo *
7364 getProcLangs(Archive *fout, int *numProcLangs)
7365 {
7366         DumpOptions *dopt = fout->dopt;
7367         PGresult   *res;
7368         int                     ntups;
7369         int                     i;
7370         PQExpBuffer query = createPQExpBuffer();
7371         ProcLangInfo *planginfo;
7372         int                     i_tableoid;
7373         int                     i_oid;
7374         int                     i_lanname;
7375         int                     i_lanpltrusted;
7376         int                     i_lanplcallfoid;
7377         int                     i_laninline;
7378         int                     i_lanvalidator;
7379         int                     i_lanacl;
7380         int                     i_rlanacl;
7381         int                     i_initlanacl;
7382         int                     i_initrlanacl;
7383         int                     i_lanowner;
7384
7385         /* Make sure we are in proper schema */
7386         selectSourceSchema(fout, "pg_catalog");
7387
7388         if (fout->remoteVersion >= 90600)
7389         {
7390                 PQExpBuffer acl_subquery = createPQExpBuffer();
7391                 PQExpBuffer racl_subquery = createPQExpBuffer();
7392                 PQExpBuffer initacl_subquery = createPQExpBuffer();
7393                 PQExpBuffer initracl_subquery = createPQExpBuffer();
7394
7395                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
7396                                                 initracl_subquery, "l.lanacl", "l.lanowner", "'l'",
7397                                                 dopt->binary_upgrade);
7398
7399                 /* pg_language has a laninline column */
7400                 appendPQExpBuffer(query, "SELECT l.tableoid, l.oid, "
7401                                                   "l.lanname, l.lanpltrusted, l.lanplcallfoid, "
7402                                                   "l.laninline, l.lanvalidator, "
7403                                                   "%s AS lanacl, "
7404                                                   "%s AS rlanacl, "
7405                                                   "%s AS initlanacl, "
7406                                                   "%s AS initrlanacl, "
7407                                                   "(%s l.lanowner) AS lanowner "
7408                                                   "FROM pg_language l "
7409                                                   "LEFT JOIN pg_init_privs pip ON "
7410                                                   "(l.oid = pip.objoid "
7411                                                   "AND pip.classoid = 'pg_language'::regclass "
7412                                                   "AND pip.objsubid = 0) "
7413                                                   "WHERE l.lanispl "
7414                                                   "ORDER BY l.oid",
7415                                                   acl_subquery->data,
7416                                                   racl_subquery->data,
7417                                                   initacl_subquery->data,
7418                                                   initracl_subquery->data,
7419                                                   username_subquery);
7420
7421                 destroyPQExpBuffer(acl_subquery);
7422                 destroyPQExpBuffer(racl_subquery);
7423                 destroyPQExpBuffer(initacl_subquery);
7424                 destroyPQExpBuffer(initracl_subquery);
7425         }
7426         else if (fout->remoteVersion >= 90000)
7427         {
7428                 /* pg_language has a laninline column */
7429                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7430                                                   "lanname, lanpltrusted, lanplcallfoid, "
7431                                                   "laninline, lanvalidator, lanacl, NULL AS rlanacl, "
7432                                                   "NULL AS initlanacl, NULL AS initrlanacl, "
7433                                                   "(%s lanowner) AS lanowner "
7434                                                   "FROM pg_language "
7435                                                   "WHERE lanispl "
7436                                                   "ORDER BY oid",
7437                                                   username_subquery);
7438         }
7439         else if (fout->remoteVersion >= 80300)
7440         {
7441                 /* pg_language has a lanowner column */
7442                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7443                                                   "lanname, lanpltrusted, lanplcallfoid, "
7444                                                   "0 AS laninline, lanvalidator, lanacl, "
7445                                                   "NULL AS rlanacl, "
7446                                                   "NULL AS initlanacl, NULL AS initrlanacl, "
7447                                                   "(%s lanowner) AS lanowner "
7448                                                   "FROM pg_language "
7449                                                   "WHERE lanispl "
7450                                                   "ORDER BY oid",
7451                                                   username_subquery);
7452         }
7453         else if (fout->remoteVersion >= 80100)
7454         {
7455                 /* Languages are owned by the bootstrap superuser, OID 10 */
7456                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7457                                                   "lanname, lanpltrusted, lanplcallfoid, "
7458                                                   "0 AS laninline, lanvalidator, lanacl, "
7459                                                   "NULL AS rlanacl, "
7460                                                   "NULL AS initlanacl, NULL AS initrlanacl, "
7461                                                   "(%s '10') AS lanowner "
7462                                                   "FROM pg_language "
7463                                                   "WHERE lanispl "
7464                                                   "ORDER BY oid",
7465                                                   username_subquery);
7466         }
7467         else
7468         {
7469                 /* Languages are owned by the bootstrap superuser, sysid 1 */
7470                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
7471                                                   "lanname, lanpltrusted, lanplcallfoid, "
7472                                                   "0 AS laninline, lanvalidator, lanacl, "
7473                                                   "NULL AS rlanacl, "
7474                                                   "NULL AS initlanacl, NULL AS initrlanacl, "
7475                                                   "(%s '1') AS lanowner "
7476                                                   "FROM pg_language "
7477                                                   "WHERE lanispl "
7478                                                   "ORDER BY oid",
7479                                                   username_subquery);
7480         }
7481
7482         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7483
7484         ntups = PQntuples(res);
7485
7486         *numProcLangs = ntups;
7487
7488         planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
7489
7490         i_tableoid = PQfnumber(res, "tableoid");
7491         i_oid = PQfnumber(res, "oid");
7492         i_lanname = PQfnumber(res, "lanname");
7493         i_lanpltrusted = PQfnumber(res, "lanpltrusted");
7494         i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
7495         i_laninline = PQfnumber(res, "laninline");
7496         i_lanvalidator = PQfnumber(res, "lanvalidator");
7497         i_lanacl = PQfnumber(res, "lanacl");
7498         i_rlanacl = PQfnumber(res, "rlanacl");
7499         i_initlanacl = PQfnumber(res, "initlanacl");
7500         i_initrlanacl = PQfnumber(res, "initrlanacl");
7501         i_lanowner = PQfnumber(res, "lanowner");
7502
7503         for (i = 0; i < ntups; i++)
7504         {
7505                 planginfo[i].dobj.objType = DO_PROCLANG;
7506                 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7507                 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7508                 AssignDumpId(&planginfo[i].dobj);
7509
7510                 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
7511                 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
7512                 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
7513                 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
7514                 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
7515                 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
7516                 planginfo[i].rlanacl = pg_strdup(PQgetvalue(res, i, i_rlanacl));
7517                 planginfo[i].initlanacl = pg_strdup(PQgetvalue(res, i, i_initlanacl));
7518                 planginfo[i].initrlanacl = pg_strdup(PQgetvalue(res, i, i_initrlanacl));
7519                 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
7520
7521                 /* Decide whether we want to dump it */
7522                 selectDumpableProcLang(&(planginfo[i]), fout);
7523
7524                 /* Do not try to dump ACL if no ACL exists. */
7525                 if (PQgetisnull(res, i, i_lanacl) && PQgetisnull(res, i, i_rlanacl) &&
7526                         PQgetisnull(res, i, i_initlanacl) &&
7527                         PQgetisnull(res, i, i_initrlanacl))
7528                         planginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7529         }
7530
7531         PQclear(res);
7532
7533         destroyPQExpBuffer(query);
7534
7535         return planginfo;
7536 }
7537
7538 /*
7539  * getCasts
7540  *        get basic information about every cast in the system
7541  *
7542  * numCasts is set to the number of casts read in
7543  */
7544 CastInfo *
7545 getCasts(Archive *fout, int *numCasts)
7546 {
7547         PGresult   *res;
7548         int                     ntups;
7549         int                     i;
7550         PQExpBuffer query = createPQExpBuffer();
7551         CastInfo   *castinfo;
7552         int                     i_tableoid;
7553         int                     i_oid;
7554         int                     i_castsource;
7555         int                     i_casttarget;
7556         int                     i_castfunc;
7557         int                     i_castcontext;
7558         int                     i_castmethod;
7559
7560         /* Make sure we are in proper schema */
7561         selectSourceSchema(fout, "pg_catalog");
7562
7563         if (fout->remoteVersion >= 80400)
7564         {
7565                 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7566                                                          "castsource, casttarget, castfunc, castcontext, "
7567                                                          "castmethod "
7568                                                          "FROM pg_cast ORDER BY 3,4");
7569         }
7570         else
7571         {
7572                 appendPQExpBufferStr(query, "SELECT tableoid, oid, "
7573                                                          "castsource, casttarget, castfunc, castcontext, "
7574                                                          "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
7575                                                          "FROM pg_cast ORDER BY 3,4");
7576         }
7577
7578         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7579
7580         ntups = PQntuples(res);
7581
7582         *numCasts = ntups;
7583
7584         castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
7585
7586         i_tableoid = PQfnumber(res, "tableoid");
7587         i_oid = PQfnumber(res, "oid");
7588         i_castsource = PQfnumber(res, "castsource");
7589         i_casttarget = PQfnumber(res, "casttarget");
7590         i_castfunc = PQfnumber(res, "castfunc");
7591         i_castcontext = PQfnumber(res, "castcontext");
7592         i_castmethod = PQfnumber(res, "castmethod");
7593
7594         for (i = 0; i < ntups; i++)
7595         {
7596                 PQExpBufferData namebuf;
7597                 TypeInfo   *sTypeInfo;
7598                 TypeInfo   *tTypeInfo;
7599
7600                 castinfo[i].dobj.objType = DO_CAST;
7601                 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7602                 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7603                 AssignDumpId(&castinfo[i].dobj);
7604                 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
7605                 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
7606                 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
7607                 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
7608                 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
7609
7610                 /*
7611                  * Try to name cast as concatenation of typnames.  This is only used
7612                  * for purposes of sorting.  If we fail to find either type, the name
7613                  * will be an empty string.
7614                  */
7615                 initPQExpBuffer(&namebuf);
7616                 sTypeInfo = findTypeByOid(castinfo[i].castsource);
7617                 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
7618                 if (sTypeInfo && tTypeInfo)
7619                         appendPQExpBuffer(&namebuf, "%s %s",
7620                                                           sTypeInfo->dobj.name, tTypeInfo->dobj.name);
7621                 castinfo[i].dobj.name = namebuf.data;
7622
7623                 /* Decide whether we want to dump it */
7624                 selectDumpableCast(&(castinfo[i]), fout);
7625
7626                 /* Casts do not currently have ACLs. */
7627                 castinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
7628         }
7629
7630         PQclear(res);
7631
7632         destroyPQExpBuffer(query);
7633
7634         return castinfo;
7635 }
7636
7637 static char *
7638 get_language_name(Archive *fout, Oid langid)
7639 {
7640         PQExpBuffer query;
7641         PGresult   *res;
7642         char       *lanname;
7643
7644         query = createPQExpBuffer();
7645         appendPQExpBuffer(query, "SELECT lanname FROM pg_language WHERE oid = %u", langid);
7646         res = ExecuteSqlQueryForSingleRow(fout, query->data);
7647         lanname = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
7648         destroyPQExpBuffer(query);
7649         PQclear(res);
7650
7651         return lanname;
7652 }
7653
7654 /*
7655  * getTransforms
7656  *        get basic information about every transform in the system
7657  *
7658  * numTransforms is set to the number of transforms read in
7659  */
7660 TransformInfo *
7661 getTransforms(Archive *fout, int *numTransforms)
7662 {
7663         PGresult   *res;
7664         int                     ntups;
7665         int                     i;
7666         PQExpBuffer query;
7667         TransformInfo *transforminfo;
7668         int                     i_tableoid;
7669         int                     i_oid;
7670         int                     i_trftype;
7671         int                     i_trflang;
7672         int                     i_trffromsql;
7673         int                     i_trftosql;
7674
7675         /* Transforms didn't exist pre-9.5 */
7676         if (fout->remoteVersion < 90500)
7677         {
7678                 *numTransforms = 0;
7679                 return NULL;
7680         }
7681
7682         query = createPQExpBuffer();
7683
7684         /* Make sure we are in proper schema */
7685         selectSourceSchema(fout, "pg_catalog");
7686
7687         appendPQExpBuffer(query, "SELECT tableoid, oid, "
7688                                           "trftype, trflang, trffromsql::oid, trftosql::oid "
7689                                           "FROM pg_transform "
7690                                           "ORDER BY 3,4");
7691
7692         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7693
7694         ntups = PQntuples(res);
7695
7696         *numTransforms = ntups;
7697
7698         transforminfo = (TransformInfo *) pg_malloc(ntups * sizeof(TransformInfo));
7699
7700         i_tableoid = PQfnumber(res, "tableoid");
7701         i_oid = PQfnumber(res, "oid");
7702         i_trftype = PQfnumber(res, "trftype");
7703         i_trflang = PQfnumber(res, "trflang");
7704         i_trffromsql = PQfnumber(res, "trffromsql");
7705         i_trftosql = PQfnumber(res, "trftosql");
7706
7707         for (i = 0; i < ntups; i++)
7708         {
7709                 PQExpBufferData namebuf;
7710                 TypeInfo   *typeInfo;
7711                 char       *lanname;
7712
7713                 transforminfo[i].dobj.objType = DO_TRANSFORM;
7714                 transforminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7715                 transforminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7716                 AssignDumpId(&transforminfo[i].dobj);
7717                 transforminfo[i].trftype = atooid(PQgetvalue(res, i, i_trftype));
7718                 transforminfo[i].trflang = atooid(PQgetvalue(res, i, i_trflang));
7719                 transforminfo[i].trffromsql = atooid(PQgetvalue(res, i, i_trffromsql));
7720                 transforminfo[i].trftosql = atooid(PQgetvalue(res, i, i_trftosql));
7721
7722                 /*
7723                  * Try to name transform as concatenation of type and language name.
7724                  * This is only used for purposes of sorting.  If we fail to find
7725                  * either, the name will be an empty string.
7726                  */
7727                 initPQExpBuffer(&namebuf);
7728                 typeInfo = findTypeByOid(transforminfo[i].trftype);
7729                 lanname = get_language_name(fout, transforminfo[i].trflang);
7730                 if (typeInfo && lanname)
7731                         appendPQExpBuffer(&namebuf, "%s %s",
7732                                                           typeInfo->dobj.name, lanname);
7733                 transforminfo[i].dobj.name = namebuf.data;
7734                 free(lanname);
7735
7736                 /* Decide whether we want to dump it */
7737                 selectDumpableObject(&(transforminfo[i].dobj), fout);
7738         }
7739
7740         PQclear(res);
7741
7742         destroyPQExpBuffer(query);
7743
7744         return transforminfo;
7745 }
7746
7747 /*
7748  * getTableAttrs -
7749  *        for each interesting table, read info about its attributes
7750  *        (names, types, default values, CHECK constraints, etc)
7751  *
7752  * This is implemented in a very inefficient way right now, looping
7753  * through the tblinfo and doing a join per table to find the attrs and their
7754  * types.  However, because we want type names and so forth to be named
7755  * relative to the schema of each table, we couldn't do it in just one
7756  * query.  (Maybe one query per schema?)
7757  *
7758  *      modifies tblinfo
7759  */
7760 void
7761 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
7762 {
7763         DumpOptions *dopt = fout->dopt;
7764         int                     i,
7765                                 j;
7766         PQExpBuffer q = createPQExpBuffer();
7767         int                     i_attnum;
7768         int                     i_attname;
7769         int                     i_atttypname;
7770         int                     i_atttypmod;
7771         int                     i_attstattarget;
7772         int                     i_attstorage;
7773         int                     i_typstorage;
7774         int                     i_attnotnull;
7775         int                     i_atthasdef;
7776         int                     i_attidentity;
7777         int                     i_attisdropped;
7778         int                     i_attlen;
7779         int                     i_attalign;
7780         int                     i_attislocal;
7781         int                     i_attoptions;
7782         int                     i_attcollation;
7783         int                     i_attfdwoptions;
7784         PGresult   *res;
7785         int                     ntups;
7786         bool            hasdefaults;
7787
7788         for (i = 0; i < numTables; i++)
7789         {
7790                 TableInfo  *tbinfo = &tblinfo[i];
7791
7792                 /* Don't bother to collect info for sequences */
7793                 if (tbinfo->relkind == RELKIND_SEQUENCE)
7794                         continue;
7795
7796                 /* Don't bother with uninteresting tables, either */
7797                 if (!tbinfo->interesting)
7798                         continue;
7799
7800                 /*
7801                  * Make sure we are in proper schema for this table; this allows
7802                  * correct retrieval of formatted type names and default exprs
7803                  */
7804                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
7805
7806                 /* find all the user attributes and their types */
7807
7808                 /*
7809                  * we must read the attribute names in attribute number order! because
7810                  * we will use the attnum to index into the attnames array later.
7811                  */
7812                 if (g_verbose)
7813                         write_msg(NULL, "finding the columns and types of table \"%s.%s\"\n",
7814                                           tbinfo->dobj.namespace->dobj.name,
7815                                           tbinfo->dobj.name);
7816
7817                 resetPQExpBuffer(q);
7818
7819                 if (fout->remoteVersion >= 100000)
7820                 {
7821                         /*
7822                          * attidentity is new in version 10.
7823                          */
7824                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
7825                                                           "a.attstattarget, a.attstorage, t.typstorage, "
7826                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
7827                                                           "a.attlen, a.attalign, a.attislocal, "
7828                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
7829                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
7830                                                           "CASE WHEN a.attcollation <> t.typcollation "
7831                                                           "THEN a.attcollation ELSE 0 END AS attcollation, "
7832                                                           "a.attidentity, "
7833                                                           "pg_catalog.array_to_string(ARRAY("
7834                                                           "SELECT pg_catalog.quote_ident(option_name) || "
7835                                                           "' ' || pg_catalog.quote_literal(option_value) "
7836                                                           "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
7837                                                           "ORDER BY option_name"
7838                                                           "), E',\n    ') AS attfdwoptions "
7839                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
7840                                                           "ON a.atttypid = t.oid "
7841                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
7842                                                           "AND a.attnum > 0::pg_catalog.int2 "
7843                                                           "ORDER BY a.attnum",
7844                                                           tbinfo->dobj.catId.oid);
7845                 }
7846                 else if (fout->remoteVersion >= 90200)
7847                 {
7848                         /*
7849                          * attfdwoptions is new in 9.2.
7850                          */
7851                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
7852                                                           "a.attstattarget, a.attstorage, t.typstorage, "
7853                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
7854                                                           "a.attlen, a.attalign, a.attislocal, "
7855                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
7856                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
7857                                                           "CASE WHEN a.attcollation <> t.typcollation "
7858                                                           "THEN a.attcollation ELSE 0 END AS attcollation, "
7859                                                           "pg_catalog.array_to_string(ARRAY("
7860                                                           "SELECT pg_catalog.quote_ident(option_name) || "
7861                                                           "' ' || pg_catalog.quote_literal(option_value) "
7862                                                           "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
7863                                                           "ORDER BY option_name"
7864                                                           "), E',\n    ') AS attfdwoptions "
7865                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
7866                                                           "ON a.atttypid = t.oid "
7867                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
7868                                                           "AND a.attnum > 0::pg_catalog.int2 "
7869                                                           "ORDER BY a.attnum",
7870                                                           tbinfo->dobj.catId.oid);
7871                 }
7872                 else if (fout->remoteVersion >= 90100)
7873                 {
7874                         /*
7875                          * attcollation is new in 9.1.  Since we only want to dump COLLATE
7876                          * clauses for attributes whose collation is different from their
7877                          * type's default, we use a CASE here to suppress uninteresting
7878                          * attcollations cheaply.
7879                          */
7880                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
7881                                                           "a.attstattarget, a.attstorage, t.typstorage, "
7882                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
7883                                                           "a.attlen, a.attalign, a.attislocal, "
7884                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
7885                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
7886                                                           "CASE WHEN a.attcollation <> t.typcollation "
7887                                                           "THEN a.attcollation ELSE 0 END AS attcollation, "
7888                                                           "NULL AS attfdwoptions "
7889                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
7890                                                           "ON a.atttypid = t.oid "
7891                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
7892                                                           "AND a.attnum > 0::pg_catalog.int2 "
7893                                                           "ORDER BY a.attnum",
7894                                                           tbinfo->dobj.catId.oid);
7895                 }
7896                 else if (fout->remoteVersion >= 90000)
7897                 {
7898                         /* attoptions is new in 9.0 */
7899                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
7900                                                           "a.attstattarget, a.attstorage, t.typstorage, "
7901                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
7902                                                           "a.attlen, a.attalign, a.attislocal, "
7903                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
7904                                                           "array_to_string(a.attoptions, ', ') AS attoptions, "
7905                                                           "0 AS attcollation, "
7906                                                           "NULL AS attfdwoptions "
7907                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
7908                                                           "ON a.atttypid = t.oid "
7909                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
7910                                                           "AND a.attnum > 0::pg_catalog.int2 "
7911                                                           "ORDER BY a.attnum",
7912                                                           tbinfo->dobj.catId.oid);
7913                 }
7914                 else
7915                 {
7916                         /* need left join here to not fail on dropped columns ... */
7917                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
7918                                                           "a.attstattarget, a.attstorage, t.typstorage, "
7919                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
7920                                                           "a.attlen, a.attalign, a.attislocal, "
7921                                                           "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
7922                                                           "'' AS attoptions, 0 AS attcollation, "
7923                                                           "NULL AS attfdwoptions "
7924                                                           "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
7925                                                           "ON a.atttypid = t.oid "
7926                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
7927                                                           "AND a.attnum > 0::pg_catalog.int2 "
7928                                                           "ORDER BY a.attnum",
7929                                                           tbinfo->dobj.catId.oid);
7930                 }
7931
7932                 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
7933
7934                 ntups = PQntuples(res);
7935
7936                 i_attnum = PQfnumber(res, "attnum");
7937                 i_attname = PQfnumber(res, "attname");
7938                 i_atttypname = PQfnumber(res, "atttypname");
7939                 i_atttypmod = PQfnumber(res, "atttypmod");
7940                 i_attstattarget = PQfnumber(res, "attstattarget");
7941                 i_attstorage = PQfnumber(res, "attstorage");
7942                 i_typstorage = PQfnumber(res, "typstorage");
7943                 i_attnotnull = PQfnumber(res, "attnotnull");
7944                 i_atthasdef = PQfnumber(res, "atthasdef");
7945                 i_attidentity = PQfnumber(res, "attidentity");
7946                 i_attisdropped = PQfnumber(res, "attisdropped");
7947                 i_attlen = PQfnumber(res, "attlen");
7948                 i_attalign = PQfnumber(res, "attalign");
7949                 i_attislocal = PQfnumber(res, "attislocal");
7950                 i_attoptions = PQfnumber(res, "attoptions");
7951                 i_attcollation = PQfnumber(res, "attcollation");
7952                 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
7953
7954                 tbinfo->numatts = ntups;
7955                 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
7956                 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
7957                 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
7958                 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
7959                 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
7960                 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
7961                 tbinfo->attidentity = (char *) pg_malloc(ntups * sizeof(char));
7962                 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
7963                 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
7964                 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
7965                 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
7966                 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
7967                 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
7968                 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
7969                 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
7970                 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
7971                 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
7972                 hasdefaults = false;
7973
7974                 for (j = 0; j < ntups; j++)
7975                 {
7976                         if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
7977                                 exit_horribly(NULL,
7978                                                           "invalid column numbering in table \"%s\"\n",
7979                                                           tbinfo->dobj.name);
7980                         tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
7981                         tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
7982                         tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
7983                         tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
7984                         tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
7985                         tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
7986                         tbinfo->attidentity[j] = (i_attidentity >= 0 ? *(PQgetvalue(res, j, i_attidentity)) : '\0');
7987                         tbinfo->needs_override = tbinfo->needs_override || (tbinfo->attidentity[j] == ATTRIBUTE_IDENTITY_ALWAYS);
7988                         tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
7989                         tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
7990                         tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
7991                         tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
7992                         tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
7993                         tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
7994                         tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
7995                         tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
7996                         tbinfo->attrdefs[j] = NULL; /* fix below */
7997                         if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
7998                                 hasdefaults = true;
7999                         /* these flags will be set in flagInhAttrs() */
8000                         tbinfo->inhNotNull[j] = false;
8001                 }
8002
8003                 PQclear(res);
8004
8005                 /*
8006                  * Get info about column defaults
8007                  */
8008                 if (hasdefaults)
8009                 {
8010                         AttrDefInfo *attrdefs;
8011                         int                     numDefaults;
8012
8013                         if (g_verbose)
8014                                 write_msg(NULL, "finding default expressions of table \"%s.%s\"\n",
8015                                                   tbinfo->dobj.namespace->dobj.name,
8016                                                   tbinfo->dobj.name);
8017
8018                         printfPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
8019                                                           "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
8020                                                           "FROM pg_catalog.pg_attrdef "
8021                                                           "WHERE adrelid = '%u'::pg_catalog.oid",
8022                                                           tbinfo->dobj.catId.oid);
8023
8024                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8025
8026                         numDefaults = PQntuples(res);
8027                         attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
8028
8029                         for (j = 0; j < numDefaults; j++)
8030                         {
8031                                 int                     adnum;
8032
8033                                 adnum = atoi(PQgetvalue(res, j, 2));
8034
8035                                 if (adnum <= 0 || adnum > ntups)
8036                                         exit_horribly(NULL,
8037                                                                   "invalid adnum value %d for table \"%s\"\n",
8038                                                                   adnum, tbinfo->dobj.name);
8039
8040                                 /*
8041                                  * dropped columns shouldn't have defaults, but just in case,
8042                                  * ignore 'em
8043                                  */
8044                                 if (tbinfo->attisdropped[adnum - 1])
8045                                         continue;
8046
8047                                 attrdefs[j].dobj.objType = DO_ATTRDEF;
8048                                 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8049                                 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8050                                 AssignDumpId(&attrdefs[j].dobj);
8051                                 attrdefs[j].adtable = tbinfo;
8052                                 attrdefs[j].adnum = adnum;
8053                                 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
8054
8055                                 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
8056                                 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
8057
8058                                 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
8059
8060                                 /*
8061                                  * Defaults on a VIEW must always be dumped as separate ALTER
8062                                  * TABLE commands.  Defaults on regular tables are dumped as
8063                                  * part of the CREATE TABLE if possible, which it won't be if
8064                                  * the column is not going to be emitted explicitly.
8065                                  */
8066                                 if (tbinfo->relkind == RELKIND_VIEW)
8067                                 {
8068                                         attrdefs[j].separate = true;
8069                                 }
8070                                 else if (!shouldPrintColumn(dopt, tbinfo, adnum - 1))
8071                                 {
8072                                         /* column will be suppressed, print default separately */
8073                                         attrdefs[j].separate = true;
8074                                 }
8075                                 else
8076                                 {
8077                                         attrdefs[j].separate = false;
8078
8079                                         /*
8080                                          * Mark the default as needing to appear before the table,
8081                                          * so that any dependencies it has must be emitted before
8082                                          * the CREATE TABLE.  If this is not possible, we'll
8083                                          * change to "separate" mode while sorting dependencies.
8084                                          */
8085                                         addObjectDependency(&tbinfo->dobj,
8086                                                                                 attrdefs[j].dobj.dumpId);
8087                                 }
8088
8089                                 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
8090                         }
8091                         PQclear(res);
8092                 }
8093
8094                 /*
8095                  * Get info about table CHECK constraints
8096                  */
8097                 if (tbinfo->ncheck > 0)
8098                 {
8099                         ConstraintInfo *constrs;
8100                         int                     numConstrs;
8101
8102                         if (g_verbose)
8103                                 write_msg(NULL, "finding check constraints for table \"%s.%s\"\n",
8104                                                   tbinfo->dobj.namespace->dobj.name,
8105                                                   tbinfo->dobj.name);
8106
8107                         resetPQExpBuffer(q);
8108                         if (fout->remoteVersion >= 90200)
8109                         {
8110                                 /*
8111                                  * convalidated is new in 9.2 (actually, it is there in 9.1,
8112                                  * but it wasn't ever false for check constraints until 9.2).
8113                                  */
8114                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8115                                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8116                                                                   "conislocal, convalidated "
8117                                                                   "FROM pg_catalog.pg_constraint "
8118                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
8119                                                                   "   AND contype = 'c' "
8120                                                                   "ORDER BY conname",
8121                                                                   tbinfo->dobj.catId.oid);
8122                         }
8123                         else if (fout->remoteVersion >= 80400)
8124                         {
8125                                 /* conislocal is new in 8.4 */
8126                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8127                                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8128                                                                   "conislocal, true AS convalidated "
8129                                                                   "FROM pg_catalog.pg_constraint "
8130                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
8131                                                                   "   AND contype = 'c' "
8132                                                                   "ORDER BY conname",
8133                                                                   tbinfo->dobj.catId.oid);
8134                         }
8135                         else
8136                         {
8137                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
8138                                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8139                                                                   "true AS conislocal, true AS convalidated "
8140                                                                   "FROM pg_catalog.pg_constraint "
8141                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
8142                                                                   "   AND contype = 'c' "
8143                                                                   "ORDER BY conname",
8144                                                                   tbinfo->dobj.catId.oid);
8145                         }
8146
8147                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8148
8149                         numConstrs = PQntuples(res);
8150                         if (numConstrs != tbinfo->ncheck)
8151                         {
8152                                 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
8153                                                                                  "expected %d check constraints on table \"%s\" but found %d\n",
8154                                                                                  tbinfo->ncheck),
8155                                                   tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
8156                                 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
8157                                 exit_nicely(1);
8158                         }
8159
8160                         constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
8161                         tbinfo->checkexprs = constrs;
8162
8163                         for (j = 0; j < numConstrs; j++)
8164                         {
8165                                 bool            validated = PQgetvalue(res, j, 5)[0] == 't';
8166
8167                                 constrs[j].dobj.objType = DO_CONSTRAINT;
8168                                 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
8169                                 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
8170                                 AssignDumpId(&constrs[j].dobj);
8171                                 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
8172                                 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
8173                                 constrs[j].contable = tbinfo;
8174                                 constrs[j].condomain = NULL;
8175                                 constrs[j].contype = 'c';
8176                                 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
8177                                 constrs[j].confrelid = InvalidOid;
8178                                 constrs[j].conindex = 0;
8179                                 constrs[j].condeferrable = false;
8180                                 constrs[j].condeferred = false;
8181                                 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
8182
8183                                 /*
8184                                  * An unvalidated constraint needs to be dumped separately, so
8185                                  * that potentially-violating existing data is loaded before
8186                                  * the constraint.
8187                                  */
8188                                 constrs[j].separate = !validated;
8189
8190                                 constrs[j].dobj.dump = tbinfo->dobj.dump;
8191
8192                                 /*
8193                                  * Mark the constraint as needing to appear before the table
8194                                  * --- this is so that any other dependencies of the
8195                                  * constraint will be emitted before we try to create the
8196                                  * table.  If the constraint is to be dumped separately, it
8197                                  * will be dumped after data is loaded anyway, so don't do it.
8198                                  * (There's an automatic dependency in the opposite direction
8199                                  * anyway, so don't need to add one manually here.)
8200                                  */
8201                                 if (!constrs[j].separate)
8202                                         addObjectDependency(&tbinfo->dobj,
8203                                                                                 constrs[j].dobj.dumpId);
8204
8205                                 /*
8206                                  * If the constraint is inherited, this will be detected later
8207                                  * (in pre-8.4 databases).  We also detect later if the
8208                                  * constraint must be split out from the table definition.
8209                                  */
8210                         }
8211                         PQclear(res);
8212                 }
8213         }
8214
8215         destroyPQExpBuffer(q);
8216 }
8217
8218 /*
8219  * Test whether a column should be printed as part of table's CREATE TABLE.
8220  * Column number is zero-based.
8221  *
8222  * Normally this is always true, but it's false for dropped columns, as well
8223  * as those that were inherited without any local definition.  (If we print
8224  * such a column it will mistakenly get pg_attribute.attislocal set to true.)
8225  * However, in binary_upgrade mode, we must print all such columns anyway and
8226  * fix the attislocal/attisdropped state later, so as to keep control of the
8227  * physical column order.
8228  *
8229  * This function exists because there are scattered nonobvious places that
8230  * must be kept in sync with this decision.
8231  */
8232 bool
8233 shouldPrintColumn(DumpOptions *dopt, TableInfo *tbinfo, int colno)
8234 {
8235         if (dopt->binary_upgrade)
8236                 return true;
8237         return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
8238 }
8239
8240
8241 /*
8242  * getTSParsers:
8243  *        read all text search parsers in the system catalogs and return them
8244  *        in the TSParserInfo* structure
8245  *
8246  *      numTSParsers is set to the number of parsers read in
8247  */
8248 TSParserInfo *
8249 getTSParsers(Archive *fout, int *numTSParsers)
8250 {
8251         PGresult   *res;
8252         int                     ntups;
8253         int                     i;
8254         PQExpBuffer query;
8255         TSParserInfo *prsinfo;
8256         int                     i_tableoid;
8257         int                     i_oid;
8258         int                     i_prsname;
8259         int                     i_prsnamespace;
8260         int                     i_prsstart;
8261         int                     i_prstoken;
8262         int                     i_prsend;
8263         int                     i_prsheadline;
8264         int                     i_prslextype;
8265
8266         /* Before 8.3, there is no built-in text search support */
8267         if (fout->remoteVersion < 80300)
8268         {
8269                 *numTSParsers = 0;
8270                 return NULL;
8271         }
8272
8273         query = createPQExpBuffer();
8274
8275         /*
8276          * find all text search objects, including builtin ones; we filter out
8277          * system-defined objects at dump-out time.
8278          */
8279
8280         /* Make sure we are in proper schema */
8281         selectSourceSchema(fout, "pg_catalog");
8282
8283         appendPQExpBufferStr(query, "SELECT tableoid, oid, prsname, prsnamespace, "
8284                                                  "prsstart::oid, prstoken::oid, "
8285                                                  "prsend::oid, prsheadline::oid, prslextype::oid "
8286                                                  "FROM pg_ts_parser");
8287
8288         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8289
8290         ntups = PQntuples(res);
8291         *numTSParsers = ntups;
8292
8293         prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
8294
8295         i_tableoid = PQfnumber(res, "tableoid");
8296         i_oid = PQfnumber(res, "oid");
8297         i_prsname = PQfnumber(res, "prsname");
8298         i_prsnamespace = PQfnumber(res, "prsnamespace");
8299         i_prsstart = PQfnumber(res, "prsstart");
8300         i_prstoken = PQfnumber(res, "prstoken");
8301         i_prsend = PQfnumber(res, "prsend");
8302         i_prsheadline = PQfnumber(res, "prsheadline");
8303         i_prslextype = PQfnumber(res, "prslextype");
8304
8305         for (i = 0; i < ntups; i++)
8306         {
8307                 prsinfo[i].dobj.objType = DO_TSPARSER;
8308                 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8309                 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8310                 AssignDumpId(&prsinfo[i].dobj);
8311                 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
8312                 prsinfo[i].dobj.namespace =
8313                         findNamespace(fout,
8314                                                   atooid(PQgetvalue(res, i, i_prsnamespace)));
8315                 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
8316                 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
8317                 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
8318                 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
8319                 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
8320
8321                 /* Decide whether we want to dump it */
8322                 selectDumpableObject(&(prsinfo[i].dobj), fout);
8323
8324                 /* Text Search Parsers do not currently have ACLs. */
8325                 prsinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8326         }
8327
8328         PQclear(res);
8329
8330         destroyPQExpBuffer(query);
8331
8332         return prsinfo;
8333 }
8334
8335 /*
8336  * getTSDictionaries:
8337  *        read all text search dictionaries in the system catalogs and return them
8338  *        in the TSDictInfo* structure
8339  *
8340  *      numTSDicts is set to the number of dictionaries read in
8341  */
8342 TSDictInfo *
8343 getTSDictionaries(Archive *fout, int *numTSDicts)
8344 {
8345         PGresult   *res;
8346         int                     ntups;
8347         int                     i;
8348         PQExpBuffer query;
8349         TSDictInfo *dictinfo;
8350         int                     i_tableoid;
8351         int                     i_oid;
8352         int                     i_dictname;
8353         int                     i_dictnamespace;
8354         int                     i_rolname;
8355         int                     i_dicttemplate;
8356         int                     i_dictinitoption;
8357
8358         /* Before 8.3, there is no built-in text search support */
8359         if (fout->remoteVersion < 80300)
8360         {
8361                 *numTSDicts = 0;
8362                 return NULL;
8363         }
8364
8365         query = createPQExpBuffer();
8366
8367         /* Make sure we are in proper schema */
8368         selectSourceSchema(fout, "pg_catalog");
8369
8370         appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
8371                                           "dictnamespace, (%s dictowner) AS rolname, "
8372                                           "dicttemplate, dictinitoption "
8373                                           "FROM pg_ts_dict",
8374                                           username_subquery);
8375
8376         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8377
8378         ntups = PQntuples(res);
8379         *numTSDicts = ntups;
8380
8381         dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
8382
8383         i_tableoid = PQfnumber(res, "tableoid");
8384         i_oid = PQfnumber(res, "oid");
8385         i_dictname = PQfnumber(res, "dictname");
8386         i_dictnamespace = PQfnumber(res, "dictnamespace");
8387         i_rolname = PQfnumber(res, "rolname");
8388         i_dictinitoption = PQfnumber(res, "dictinitoption");
8389         i_dicttemplate = PQfnumber(res, "dicttemplate");
8390
8391         for (i = 0; i < ntups; i++)
8392         {
8393                 dictinfo[i].dobj.objType = DO_TSDICT;
8394                 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8395                 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8396                 AssignDumpId(&dictinfo[i].dobj);
8397                 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
8398                 dictinfo[i].dobj.namespace =
8399                         findNamespace(fout,
8400                                                   atooid(PQgetvalue(res, i, i_dictnamespace)));
8401                 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8402                 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
8403                 if (PQgetisnull(res, i, i_dictinitoption))
8404                         dictinfo[i].dictinitoption = NULL;
8405                 else
8406                         dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
8407
8408                 /* Decide whether we want to dump it */
8409                 selectDumpableObject(&(dictinfo[i].dobj), fout);
8410
8411                 /* Text Search Dictionaries do not currently have ACLs. */
8412                 dictinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8413         }
8414
8415         PQclear(res);
8416
8417         destroyPQExpBuffer(query);
8418
8419         return dictinfo;
8420 }
8421
8422 /*
8423  * getTSTemplates:
8424  *        read all text search templates in the system catalogs and return them
8425  *        in the TSTemplateInfo* structure
8426  *
8427  *      numTSTemplates is set to the number of templates read in
8428  */
8429 TSTemplateInfo *
8430 getTSTemplates(Archive *fout, int *numTSTemplates)
8431 {
8432         PGresult   *res;
8433         int                     ntups;
8434         int                     i;
8435         PQExpBuffer query;
8436         TSTemplateInfo *tmplinfo;
8437         int                     i_tableoid;
8438         int                     i_oid;
8439         int                     i_tmplname;
8440         int                     i_tmplnamespace;
8441         int                     i_tmplinit;
8442         int                     i_tmpllexize;
8443
8444         /* Before 8.3, there is no built-in text search support */
8445         if (fout->remoteVersion < 80300)
8446         {
8447                 *numTSTemplates = 0;
8448                 return NULL;
8449         }
8450
8451         query = createPQExpBuffer();
8452
8453         /* Make sure we are in proper schema */
8454         selectSourceSchema(fout, "pg_catalog");
8455
8456         appendPQExpBufferStr(query, "SELECT tableoid, oid, tmplname, "
8457                                                  "tmplnamespace, tmplinit::oid, tmpllexize::oid "
8458                                                  "FROM pg_ts_template");
8459
8460         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8461
8462         ntups = PQntuples(res);
8463         *numTSTemplates = ntups;
8464
8465         tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
8466
8467         i_tableoid = PQfnumber(res, "tableoid");
8468         i_oid = PQfnumber(res, "oid");
8469         i_tmplname = PQfnumber(res, "tmplname");
8470         i_tmplnamespace = PQfnumber(res, "tmplnamespace");
8471         i_tmplinit = PQfnumber(res, "tmplinit");
8472         i_tmpllexize = PQfnumber(res, "tmpllexize");
8473
8474         for (i = 0; i < ntups; i++)
8475         {
8476                 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
8477                 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8478                 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8479                 AssignDumpId(&tmplinfo[i].dobj);
8480                 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
8481                 tmplinfo[i].dobj.namespace =
8482                         findNamespace(fout,
8483                                                   atooid(PQgetvalue(res, i, i_tmplnamespace)));
8484                 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
8485                 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
8486
8487                 /* Decide whether we want to dump it */
8488                 selectDumpableObject(&(tmplinfo[i].dobj), fout);
8489
8490                 /* Text Search Templates do not currently have ACLs. */
8491                 tmplinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8492         }
8493
8494         PQclear(res);
8495
8496         destroyPQExpBuffer(query);
8497
8498         return tmplinfo;
8499 }
8500
8501 /*
8502  * getTSConfigurations:
8503  *        read all text search configurations in the system catalogs and return
8504  *        them in the TSConfigInfo* structure
8505  *
8506  *      numTSConfigs is set to the number of configurations read in
8507  */
8508 TSConfigInfo *
8509 getTSConfigurations(Archive *fout, int *numTSConfigs)
8510 {
8511         PGresult   *res;
8512         int                     ntups;
8513         int                     i;
8514         PQExpBuffer query;
8515         TSConfigInfo *cfginfo;
8516         int                     i_tableoid;
8517         int                     i_oid;
8518         int                     i_cfgname;
8519         int                     i_cfgnamespace;
8520         int                     i_rolname;
8521         int                     i_cfgparser;
8522
8523         /* Before 8.3, there is no built-in text search support */
8524         if (fout->remoteVersion < 80300)
8525         {
8526                 *numTSConfigs = 0;
8527                 return NULL;
8528         }
8529
8530         query = createPQExpBuffer();
8531
8532         /* Make sure we are in proper schema */
8533         selectSourceSchema(fout, "pg_catalog");
8534
8535         appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
8536                                           "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
8537                                           "FROM pg_ts_config",
8538                                           username_subquery);
8539
8540         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8541
8542         ntups = PQntuples(res);
8543         *numTSConfigs = ntups;
8544
8545         cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
8546
8547         i_tableoid = PQfnumber(res, "tableoid");
8548         i_oid = PQfnumber(res, "oid");
8549         i_cfgname = PQfnumber(res, "cfgname");
8550         i_cfgnamespace = PQfnumber(res, "cfgnamespace");
8551         i_rolname = PQfnumber(res, "rolname");
8552         i_cfgparser = PQfnumber(res, "cfgparser");
8553
8554         for (i = 0; i < ntups; i++)
8555         {
8556                 cfginfo[i].dobj.objType = DO_TSCONFIG;
8557                 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8558                 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8559                 AssignDumpId(&cfginfo[i].dobj);
8560                 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
8561                 cfginfo[i].dobj.namespace =
8562                         findNamespace(fout,
8563                                                   atooid(PQgetvalue(res, i, i_cfgnamespace)));
8564                 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8565                 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
8566
8567                 /* Decide whether we want to dump it */
8568                 selectDumpableObject(&(cfginfo[i].dobj), fout);
8569
8570                 /* Text Search Configurations do not currently have ACLs. */
8571                 cfginfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8572         }
8573
8574         PQclear(res);
8575
8576         destroyPQExpBuffer(query);
8577
8578         return cfginfo;
8579 }
8580
8581 /*
8582  * getForeignDataWrappers:
8583  *        read all foreign-data wrappers in the system catalogs and return
8584  *        them in the FdwInfo* structure
8585  *
8586  *      numForeignDataWrappers is set to the number of fdws read in
8587  */
8588 FdwInfo *
8589 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
8590 {
8591         DumpOptions *dopt = fout->dopt;
8592         PGresult   *res;
8593         int                     ntups;
8594         int                     i;
8595         PQExpBuffer query;
8596         FdwInfo    *fdwinfo;
8597         int                     i_tableoid;
8598         int                     i_oid;
8599         int                     i_fdwname;
8600         int                     i_rolname;
8601         int                     i_fdwhandler;
8602         int                     i_fdwvalidator;
8603         int                     i_fdwacl;
8604         int                     i_rfdwacl;
8605         int                     i_initfdwacl;
8606         int                     i_initrfdwacl;
8607         int                     i_fdwoptions;
8608
8609         /* Before 8.4, there are no foreign-data wrappers */
8610         if (fout->remoteVersion < 80400)
8611         {
8612                 *numForeignDataWrappers = 0;
8613                 return NULL;
8614         }
8615
8616         query = createPQExpBuffer();
8617
8618         /* Make sure we are in proper schema */
8619         selectSourceSchema(fout, "pg_catalog");
8620
8621         if (fout->remoteVersion >= 90600)
8622         {
8623                 PQExpBuffer acl_subquery = createPQExpBuffer();
8624                 PQExpBuffer racl_subquery = createPQExpBuffer();
8625                 PQExpBuffer initacl_subquery = createPQExpBuffer();
8626                 PQExpBuffer initracl_subquery = createPQExpBuffer();
8627
8628                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
8629                                                 initracl_subquery, "f.fdwacl", "f.fdwowner", "'F'",
8630                                                 dopt->binary_upgrade);
8631
8632                 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.fdwname, "
8633                                                   "(%s f.fdwowner) AS rolname, "
8634                                                   "f.fdwhandler::pg_catalog.regproc, "
8635                                                   "f.fdwvalidator::pg_catalog.regproc, "
8636                                                   "%s AS fdwacl, "
8637                                                   "%s AS rfdwacl, "
8638                                                   "%s AS initfdwacl, "
8639                                                   "%s AS initrfdwacl, "
8640                                                   "array_to_string(ARRAY("
8641                                                   "SELECT quote_ident(option_name) || ' ' || "
8642                                                   "quote_literal(option_value) "
8643                                                   "FROM pg_options_to_table(f.fdwoptions) "
8644                                                   "ORDER BY option_name"
8645                                                   "), E',\n    ') AS fdwoptions "
8646                                                   "FROM pg_foreign_data_wrapper f "
8647                                                   "LEFT JOIN pg_init_privs pip ON "
8648                                                   "(f.oid = pip.objoid "
8649                                                   "AND pip.classoid = 'pg_foreign_data_wrapper'::regclass "
8650                                                   "AND pip.objsubid = 0) ",
8651                                                   username_subquery,
8652                                                   acl_subquery->data,
8653                                                   racl_subquery->data,
8654                                                   initacl_subquery->data,
8655                                                   initracl_subquery->data);
8656
8657                 destroyPQExpBuffer(acl_subquery);
8658                 destroyPQExpBuffer(racl_subquery);
8659                 destroyPQExpBuffer(initacl_subquery);
8660                 destroyPQExpBuffer(initracl_subquery);
8661         }
8662         else if (fout->remoteVersion >= 90100)
8663         {
8664                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
8665                                                   "(%s fdwowner) AS rolname, "
8666                                                   "fdwhandler::pg_catalog.regproc, "
8667                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
8668                                                   "NULL as rfdwacl, "
8669                                                   "NULL as initfdwacl, NULL AS initrfdwacl, "
8670                                                   "array_to_string(ARRAY("
8671                                                   "SELECT quote_ident(option_name) || ' ' || "
8672                                                   "quote_literal(option_value) "
8673                                                   "FROM pg_options_to_table(fdwoptions) "
8674                                                   "ORDER BY option_name"
8675                                                   "), E',\n    ') AS fdwoptions "
8676                                                   "FROM pg_foreign_data_wrapper",
8677                                                   username_subquery);
8678         }
8679         else
8680         {
8681                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
8682                                                   "(%s fdwowner) AS rolname, "
8683                                                   "'-' AS fdwhandler, "
8684                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
8685                                                   "NULL as rfdwacl, "
8686                                                   "NULL as initfdwacl, NULL AS initrfdwacl, "
8687                                                   "array_to_string(ARRAY("
8688                                                   "SELECT quote_ident(option_name) || ' ' || "
8689                                                   "quote_literal(option_value) "
8690                                                   "FROM pg_options_to_table(fdwoptions) "
8691                                                   "ORDER BY option_name"
8692                                                   "), E',\n    ') AS fdwoptions "
8693                                                   "FROM pg_foreign_data_wrapper",
8694                                                   username_subquery);
8695         }
8696
8697         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8698
8699         ntups = PQntuples(res);
8700         *numForeignDataWrappers = ntups;
8701
8702         fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
8703
8704         i_tableoid = PQfnumber(res, "tableoid");
8705         i_oid = PQfnumber(res, "oid");
8706         i_fdwname = PQfnumber(res, "fdwname");
8707         i_rolname = PQfnumber(res, "rolname");
8708         i_fdwhandler = PQfnumber(res, "fdwhandler");
8709         i_fdwvalidator = PQfnumber(res, "fdwvalidator");
8710         i_fdwacl = PQfnumber(res, "fdwacl");
8711         i_rfdwacl = PQfnumber(res, "rfdwacl");
8712         i_initfdwacl = PQfnumber(res, "initfdwacl");
8713         i_initrfdwacl = PQfnumber(res, "initrfdwacl");
8714         i_fdwoptions = PQfnumber(res, "fdwoptions");
8715
8716         for (i = 0; i < ntups; i++)
8717         {
8718                 fdwinfo[i].dobj.objType = DO_FDW;
8719                 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8720                 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8721                 AssignDumpId(&fdwinfo[i].dobj);
8722                 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
8723                 fdwinfo[i].dobj.namespace = NULL;
8724                 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8725                 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
8726                 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
8727                 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
8728                 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
8729                 fdwinfo[i].rfdwacl = pg_strdup(PQgetvalue(res, i, i_rfdwacl));
8730                 fdwinfo[i].initfdwacl = pg_strdup(PQgetvalue(res, i, i_initfdwacl));
8731                 fdwinfo[i].initrfdwacl = pg_strdup(PQgetvalue(res, i, i_initrfdwacl));
8732
8733                 /* Decide whether we want to dump it */
8734                 selectDumpableObject(&(fdwinfo[i].dobj), fout);
8735
8736                 /* Do not try to dump ACL if no ACL exists. */
8737                 if (PQgetisnull(res, i, i_fdwacl) && PQgetisnull(res, i, i_rfdwacl) &&
8738                         PQgetisnull(res, i, i_initfdwacl) &&
8739                         PQgetisnull(res, i, i_initrfdwacl))
8740                         fdwinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8741         }
8742
8743         PQclear(res);
8744
8745         destroyPQExpBuffer(query);
8746
8747         return fdwinfo;
8748 }
8749
8750 /*
8751  * getForeignServers:
8752  *        read all foreign servers in the system catalogs and return
8753  *        them in the ForeignServerInfo * structure
8754  *
8755  *      numForeignServers is set to the number of servers read in
8756  */
8757 ForeignServerInfo *
8758 getForeignServers(Archive *fout, int *numForeignServers)
8759 {
8760         DumpOptions *dopt = fout->dopt;
8761         PGresult   *res;
8762         int                     ntups;
8763         int                     i;
8764         PQExpBuffer query;
8765         ForeignServerInfo *srvinfo;
8766         int                     i_tableoid;
8767         int                     i_oid;
8768         int                     i_srvname;
8769         int                     i_rolname;
8770         int                     i_srvfdw;
8771         int                     i_srvtype;
8772         int                     i_srvversion;
8773         int                     i_srvacl;
8774         int                     i_rsrvacl;
8775         int                     i_initsrvacl;
8776         int                     i_initrsrvacl;
8777         int                     i_srvoptions;
8778
8779         /* Before 8.4, there are no foreign servers */
8780         if (fout->remoteVersion < 80400)
8781         {
8782                 *numForeignServers = 0;
8783                 return NULL;
8784         }
8785
8786         query = createPQExpBuffer();
8787
8788         /* Make sure we are in proper schema */
8789         selectSourceSchema(fout, "pg_catalog");
8790
8791         if (fout->remoteVersion >= 90600)
8792         {
8793                 PQExpBuffer acl_subquery = createPQExpBuffer();
8794                 PQExpBuffer racl_subquery = createPQExpBuffer();
8795                 PQExpBuffer initacl_subquery = createPQExpBuffer();
8796                 PQExpBuffer initracl_subquery = createPQExpBuffer();
8797
8798                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
8799                                                 initracl_subquery, "f.srvacl", "f.srvowner", "'S'",
8800                                                 dopt->binary_upgrade);
8801
8802                 appendPQExpBuffer(query, "SELECT f.tableoid, f.oid, f.srvname, "
8803                                                   "(%s f.srvowner) AS rolname, "
8804                                                   "f.srvfdw, f.srvtype, f.srvversion, "
8805                                                   "%s AS srvacl, "
8806                                                   "%s AS rsrvacl, "
8807                                                   "%s AS initsrvacl, "
8808                                                   "%s AS initrsrvacl, "
8809                                                   "array_to_string(ARRAY("
8810                                                   "SELECT quote_ident(option_name) || ' ' || "
8811                                                   "quote_literal(option_value) "
8812                                                   "FROM pg_options_to_table(f.srvoptions) "
8813                                                   "ORDER BY option_name"
8814                                                   "), E',\n    ') AS srvoptions "
8815                                                   "FROM pg_foreign_server f "
8816                                                   "LEFT JOIN pg_init_privs pip "
8817                                                   "ON (f.oid = pip.objoid "
8818                                                   "AND pip.classoid = 'pg_foreign_server'::regclass "
8819                                                   "AND pip.objsubid = 0) ",
8820                                                   username_subquery,
8821                                                   acl_subquery->data,
8822                                                   racl_subquery->data,
8823                                                   initacl_subquery->data,
8824                                                   initracl_subquery->data);
8825
8826                 destroyPQExpBuffer(acl_subquery);
8827                 destroyPQExpBuffer(racl_subquery);
8828                 destroyPQExpBuffer(initacl_subquery);
8829                 destroyPQExpBuffer(initracl_subquery);
8830         }
8831         else
8832         {
8833                 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
8834                                                   "(%s srvowner) AS rolname, "
8835                                                   "srvfdw, srvtype, srvversion, srvacl, "
8836                                                   "NULL AS rsrvacl, "
8837                                                   "NULL AS initsrvacl, NULL AS initrsrvacl, "
8838                                                   "array_to_string(ARRAY("
8839                                                   "SELECT quote_ident(option_name) || ' ' || "
8840                                                   "quote_literal(option_value) "
8841                                                   "FROM pg_options_to_table(srvoptions) "
8842                                                   "ORDER BY option_name"
8843                                                   "), E',\n    ') AS srvoptions "
8844                                                   "FROM pg_foreign_server",
8845                                                   username_subquery);
8846         }
8847
8848         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8849
8850         ntups = PQntuples(res);
8851         *numForeignServers = ntups;
8852
8853         srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
8854
8855         i_tableoid = PQfnumber(res, "tableoid");
8856         i_oid = PQfnumber(res, "oid");
8857         i_srvname = PQfnumber(res, "srvname");
8858         i_rolname = PQfnumber(res, "rolname");
8859         i_srvfdw = PQfnumber(res, "srvfdw");
8860         i_srvtype = PQfnumber(res, "srvtype");
8861         i_srvversion = PQfnumber(res, "srvversion");
8862         i_srvacl = PQfnumber(res, "srvacl");
8863         i_rsrvacl = PQfnumber(res, "rsrvacl");
8864         i_initsrvacl = PQfnumber(res, "initsrvacl");
8865         i_initrsrvacl = PQfnumber(res, "initrsrvacl");
8866         i_srvoptions = PQfnumber(res, "srvoptions");
8867
8868         for (i = 0; i < ntups; i++)
8869         {
8870                 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
8871                 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8872                 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8873                 AssignDumpId(&srvinfo[i].dobj);
8874                 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
8875                 srvinfo[i].dobj.namespace = NULL;
8876                 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
8877                 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
8878                 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
8879                 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
8880                 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
8881                 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
8882                 srvinfo[i].rsrvacl = pg_strdup(PQgetvalue(res, i, i_rsrvacl));
8883                 srvinfo[i].initsrvacl = pg_strdup(PQgetvalue(res, i, i_initsrvacl));
8884                 srvinfo[i].initrsrvacl = pg_strdup(PQgetvalue(res, i, i_initrsrvacl));
8885
8886                 /* Decide whether we want to dump it */
8887                 selectDumpableObject(&(srvinfo[i].dobj), fout);
8888
8889                 /* Do not try to dump ACL if no ACL exists. */
8890                 if (PQgetisnull(res, i, i_srvacl) && PQgetisnull(res, i, i_rsrvacl) &&
8891                         PQgetisnull(res, i, i_initsrvacl) &&
8892                         PQgetisnull(res, i, i_initrsrvacl))
8893                         srvinfo[i].dobj.dump &= ~DUMP_COMPONENT_ACL;
8894         }
8895
8896         PQclear(res);
8897
8898         destroyPQExpBuffer(query);
8899
8900         return srvinfo;
8901 }
8902
8903 /*
8904  * getDefaultACLs:
8905  *        read all default ACL information in the system catalogs and return
8906  *        them in the DefaultACLInfo structure
8907  *
8908  *      numDefaultACLs is set to the number of ACLs read in
8909  */
8910 DefaultACLInfo *
8911 getDefaultACLs(Archive *fout, int *numDefaultACLs)
8912 {
8913         DumpOptions *dopt = fout->dopt;
8914         DefaultACLInfo *daclinfo;
8915         PQExpBuffer query;
8916         PGresult   *res;
8917         int                     i_oid;
8918         int                     i_tableoid;
8919         int                     i_defaclrole;
8920         int                     i_defaclnamespace;
8921         int                     i_defaclobjtype;
8922         int                     i_defaclacl;
8923         int                     i_rdefaclacl;
8924         int                     i_initdefaclacl;
8925         int                     i_initrdefaclacl;
8926         int                     i,
8927                                 ntups;
8928
8929         if (fout->remoteVersion < 90000)
8930         {
8931                 *numDefaultACLs = 0;
8932                 return NULL;
8933         }
8934
8935         query = createPQExpBuffer();
8936
8937         /* Make sure we are in proper schema */
8938         selectSourceSchema(fout, "pg_catalog");
8939
8940         if (fout->remoteVersion >= 90600)
8941         {
8942                 PQExpBuffer acl_subquery = createPQExpBuffer();
8943                 PQExpBuffer racl_subquery = createPQExpBuffer();
8944                 PQExpBuffer initacl_subquery = createPQExpBuffer();
8945                 PQExpBuffer initracl_subquery = createPQExpBuffer();
8946
8947                 buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
8948                                                 initracl_subquery, "defaclacl", "defaclrole",
8949                                                 "CASE WHEN defaclobjtype = 'S' THEN 's' ELSE defaclobjtype END::\"char\"",
8950                                                 dopt->binary_upgrade);
8951
8952                 appendPQExpBuffer(query, "SELECT d.oid, d.tableoid, "
8953                                                   "(%s d.defaclrole) AS defaclrole, "
8954                                                   "d.defaclnamespace, "
8955                                                   "d.defaclobjtype, "
8956                                                   "%s AS defaclacl, "
8957                                                   "%s AS rdefaclacl, "
8958                                                   "%s AS initdefaclacl, "
8959                                                   "%s AS initrdefaclacl "
8960                                                   "FROM pg_default_acl d "
8961                                                   "LEFT JOIN pg_init_privs pip ON "
8962                                                   "(d.oid = pip.objoid "
8963                                                   "AND pip.classoid = 'pg_default_acl'::regclass "
8964                                                   "AND pip.objsubid = 0) ",
8965                                                   username_subquery,
8966                                                   acl_subquery->data,
8967                                                   racl_subquery->data,
8968                                                   initacl_subquery->data,
8969                                                   initracl_subquery->data);
8970         }
8971         else
8972         {
8973                 appendPQExpBuffer(query, "SELECT oid, tableoid, "
8974                                                   "(%s defaclrole) AS defaclrole, "
8975                                                   "defaclnamespace, "
8976                                                   "defaclobjtype, "
8977                                                   "defaclacl, "
8978                                                   "NULL AS rdefaclacl, "
8979                                                   "NULL AS initdefaclacl, "
8980                                                   "NULL AS initrdefaclacl "
8981                                                   "FROM pg_default_acl",
8982                                                   username_subquery);
8983         }
8984
8985         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8986
8987         ntups = PQntuples(res);
8988         *numDefaultACLs = ntups;
8989
8990         daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
8991
8992         i_oid = PQfnumber(res, "oid");
8993         i_tableoid = PQfnumber(res, "tableoid");
8994         i_defaclrole = PQfnumber(res, "defaclrole");
8995         i_defaclnamespace = PQfnumber(res, "defaclnamespace");
8996         i_defaclobjtype = PQfnumber(res, "defaclobjtype");
8997         i_defaclacl = PQfnumber(res, "defaclacl");
8998         i_rdefaclacl = PQfnumber(res, "rdefaclacl");
8999         i_initdefaclacl = PQfnumber(res, "initdefaclacl");
9000         i_initrdefaclacl = PQfnumber(res, "initrdefaclacl");
9001
9002         for (i = 0; i < ntups; i++)
9003         {
9004                 Oid                     nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
9005
9006                 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
9007                 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9008                 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9009                 AssignDumpId(&daclinfo[i].dobj);
9010                 /* cheesy ... is it worth coming up with a better object name? */
9011                 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
9012
9013                 if (nspid != InvalidOid)
9014                         daclinfo[i].dobj.namespace = findNamespace(fout, nspid);
9015                 else
9016                         daclinfo[i].dobj.namespace = NULL;
9017
9018                 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
9019                 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
9020                 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
9021                 daclinfo[i].rdefaclacl = pg_strdup(PQgetvalue(res, i, i_rdefaclacl));
9022                 daclinfo[i].initdefaclacl = pg_strdup(PQgetvalue(res, i, i_initdefaclacl));
9023                 daclinfo[i].initrdefaclacl = pg_strdup(PQgetvalue(res, i, i_initrdefaclacl));
9024
9025                 /* Decide whether we want to dump it */
9026                 selectDumpableDefaultACL(&(daclinfo[i]), dopt);
9027         }
9028
9029         PQclear(res);
9030
9031         destroyPQExpBuffer(query);
9032
9033         return daclinfo;
9034 }
9035
9036 /*
9037  * dumpComment --
9038  *
9039  * This routine is used to dump any comments associated with the
9040  * object handed to this routine. The routine takes a constant character
9041  * string for the target part of the comment-creation command, plus
9042  * the namespace and owner of the object (for labeling the ArchiveEntry),
9043  * plus catalog ID and subid which are the lookup key for pg_description,
9044  * plus the dump ID for the object (for setting a dependency).
9045  * If a matching pg_description entry is found, it is dumped.
9046  *
9047  * Note: although this routine takes a dumpId for dependency purposes,
9048  * that purpose is just to mark the dependency in the emitted dump file
9049  * for possible future use by pg_restore.  We do NOT use it for determining
9050  * ordering of the comment in the dump file, because this routine is called
9051  * after dependency sorting occurs.  This routine should be called just after
9052  * calling ArchiveEntry() for the specified object.
9053  */
9054 static void
9055 dumpComment(Archive *fout, const char *target,
9056                         const char *namespace, const char *owner,
9057                         CatalogId catalogId, int subid, DumpId dumpId)
9058 {
9059         DumpOptions *dopt = fout->dopt;
9060         CommentItem *comments;
9061         int                     ncomments;
9062
9063         /* Comments are schema not data ... except blob comments are data */
9064         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
9065         {
9066                 if (dopt->dataOnly)
9067                         return;
9068         }
9069         else
9070         {
9071                 /* We do dump blob comments in binary-upgrade mode */
9072                 if (dopt->schemaOnly && !dopt->binary_upgrade)
9073                         return;
9074         }
9075
9076         /* Search for comments associated with catalogId, using table */
9077         ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
9078                                                          &comments);
9079
9080         /* Is there one matching the subid? */
9081         while (ncomments > 0)
9082         {
9083                 if (comments->objsubid == subid)
9084                         break;
9085                 comments++;
9086                 ncomments--;
9087         }
9088
9089         /* If a comment exists, build COMMENT ON statement */
9090         if (ncomments > 0)
9091         {
9092                 PQExpBuffer query = createPQExpBuffer();
9093
9094                 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
9095                 appendStringLiteralAH(query, comments->descr, fout);
9096                 appendPQExpBufferStr(query, ";\n");
9097
9098                 /*
9099                  * We mark comments as SECTION_NONE because they really belong in the
9100                  * same section as their parent, whether that is pre-data or
9101                  * post-data.
9102                  */
9103                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9104                                          target, namespace, NULL, owner,
9105                                          false, "COMMENT", SECTION_NONE,
9106                                          query->data, "", NULL,
9107                                          &(dumpId), 1,
9108                                          NULL, NULL);
9109
9110                 destroyPQExpBuffer(query);
9111         }
9112 }
9113
9114 /*
9115  * dumpTableComment --
9116  *
9117  * As above, but dump comments for both the specified table (or view)
9118  * and its columns.
9119  */
9120 static void
9121 dumpTableComment(Archive *fout, TableInfo *tbinfo,
9122                                  const char *reltypename)
9123 {
9124         DumpOptions *dopt = fout->dopt;
9125         CommentItem *comments;
9126         int                     ncomments;
9127         PQExpBuffer query;
9128         PQExpBuffer target;
9129
9130         /* Comments are SCHEMA not data */
9131         if (dopt->dataOnly)
9132                 return;
9133
9134         /* Search for comments associated with relation, using table */
9135         ncomments = findComments(fout,
9136                                                          tbinfo->dobj.catId.tableoid,
9137                                                          tbinfo->dobj.catId.oid,
9138                                                          &comments);
9139
9140         /* If comments exist, build COMMENT ON statements */
9141         if (ncomments <= 0)
9142                 return;
9143
9144         query = createPQExpBuffer();
9145         target = createPQExpBuffer();
9146
9147         while (ncomments > 0)
9148         {
9149                 const char *descr = comments->descr;
9150                 int                     objsubid = comments->objsubid;
9151
9152                 if (objsubid == 0)
9153                 {
9154                         resetPQExpBuffer(target);
9155                         appendPQExpBuffer(target, "%s %s", reltypename,
9156                                                           fmtId(tbinfo->dobj.name));
9157
9158                         resetPQExpBuffer(query);
9159                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
9160                         appendStringLiteralAH(query, descr, fout);
9161                         appendPQExpBufferStr(query, ";\n");
9162
9163                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
9164                                                  target->data,
9165                                                  tbinfo->dobj.namespace->dobj.name,
9166                                                  NULL, tbinfo->rolname,
9167                                                  false, "COMMENT", SECTION_NONE,
9168                                                  query->data, "", NULL,
9169                                                  &(tbinfo->dobj.dumpId), 1,
9170                                                  NULL, NULL);
9171                 }
9172                 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
9173                 {
9174                         resetPQExpBuffer(target);
9175                         appendPQExpBuffer(target, "COLUMN %s.",
9176                                                           fmtId(tbinfo->dobj.name));
9177                         appendPQExpBufferStr(target, fmtId(tbinfo->attnames[objsubid - 1]));
9178
9179                         resetPQExpBuffer(query);
9180                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
9181                         appendStringLiteralAH(query, descr, fout);
9182                         appendPQExpBufferStr(query, ";\n");
9183
9184                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
9185                                                  target->data,
9186                                                  tbinfo->dobj.namespace->dobj.name,
9187                                                  NULL, tbinfo->rolname,
9188                                                  false, "COMMENT", SECTION_NONE,
9189                                                  query->data, "", NULL,
9190                                                  &(tbinfo->dobj.dumpId), 1,
9191                                                  NULL, NULL);
9192                 }
9193
9194                 comments++;
9195                 ncomments--;
9196         }
9197
9198         destroyPQExpBuffer(query);
9199         destroyPQExpBuffer(target);
9200 }
9201
9202 /*
9203  * findComments --
9204  *
9205  * Find the comment(s), if any, associated with the given object.  All the
9206  * objsubid values associated with the given classoid/objoid are found with
9207  * one search.
9208  */
9209 static int
9210 findComments(Archive *fout, Oid classoid, Oid objoid,
9211                          CommentItem **items)
9212 {
9213         /* static storage for table of comments */
9214         static CommentItem *comments = NULL;
9215         static int      ncomments = -1;
9216
9217         CommentItem *middle = NULL;
9218         CommentItem *low;
9219         CommentItem *high;
9220         int                     nmatch;
9221
9222         /* Get comments if we didn't already */
9223         if (ncomments < 0)
9224                 ncomments = collectComments(fout, &comments);
9225
9226         /*
9227          * Do binary search to find some item matching the object.
9228          */
9229         low = &comments[0];
9230         high = &comments[ncomments - 1];
9231         while (low <= high)
9232         {
9233                 middle = low + (high - low) / 2;
9234
9235                 if (classoid < middle->classoid)
9236                         high = middle - 1;
9237                 else if (classoid > middle->classoid)
9238                         low = middle + 1;
9239                 else if (objoid < middle->objoid)
9240                         high = middle - 1;
9241                 else if (objoid > middle->objoid)
9242                         low = middle + 1;
9243                 else
9244                         break;                          /* found a match */
9245         }
9246
9247         if (low > high)                         /* no matches */
9248         {
9249                 *items = NULL;
9250                 return 0;
9251         }
9252
9253         /*
9254          * Now determine how many items match the object.  The search loop
9255          * invariant still holds: only items between low and high inclusive could
9256          * match.
9257          */
9258         nmatch = 1;
9259         while (middle > low)
9260         {
9261                 if (classoid != middle[-1].classoid ||
9262                         objoid != middle[-1].objoid)
9263                         break;
9264                 middle--;
9265                 nmatch++;
9266         }
9267
9268         *items = middle;
9269
9270         middle += nmatch;
9271         while (middle <= high)
9272         {
9273                 if (classoid != middle->classoid ||
9274                         objoid != middle->objoid)
9275                         break;
9276                 middle++;
9277                 nmatch++;
9278         }
9279
9280         return nmatch;
9281 }
9282
9283 /*
9284  * collectComments --
9285  *
9286  * Construct a table of all comments available for database objects.
9287  * We used to do per-object queries for the comments, but it's much faster
9288  * to pull them all over at once, and on most databases the memory cost
9289  * isn't high.
9290  *
9291  * The table is sorted by classoid/objid/objsubid for speed in lookup.
9292  */
9293 static int
9294 collectComments(Archive *fout, CommentItem **items)
9295 {
9296         PGresult   *res;
9297         PQExpBuffer query;
9298         int                     i_description;
9299         int                     i_classoid;
9300         int                     i_objoid;
9301         int                     i_objsubid;
9302         int                     ntups;
9303         int                     i;
9304         CommentItem *comments;
9305
9306         /*
9307          * Note we do NOT change source schema here; preserve the caller's
9308          * setting, instead.
9309          */
9310
9311         query = createPQExpBuffer();
9312
9313         appendPQExpBufferStr(query, "SELECT description, classoid, objoid, objsubid "
9314                                                  "FROM pg_catalog.pg_description "
9315                                                  "ORDER BY classoid, objoid, objsubid");
9316
9317         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9318
9319         /* Construct lookup table containing OIDs in numeric form */
9320
9321         i_description = PQfnumber(res, "description");
9322         i_classoid = PQfnumber(res, "classoid");
9323         i_objoid = PQfnumber(res, "objoid");
9324         i_objsubid = PQfnumber(res, "objsubid");
9325
9326         ntups = PQntuples(res);
9327
9328         comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
9329
9330         for (i = 0; i < ntups; i++)
9331         {
9332                 comments[i].descr = PQgetvalue(res, i, i_description);
9333                 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
9334                 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
9335                 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
9336         }
9337
9338         /* Do NOT free the PGresult since we are keeping pointers into it */
9339         destroyPQExpBuffer(query);
9340
9341         *items = comments;
9342         return ntups;
9343 }
9344
9345 /*
9346  * dumpDumpableObject
9347  *
9348  * This routine and its subsidiaries are responsible for creating
9349  * ArchiveEntries (TOC objects) for each object to be dumped.
9350  */
9351 static void
9352 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
9353 {
9354         switch (dobj->objType)
9355         {
9356                 case DO_NAMESPACE:
9357                         dumpNamespace(fout, (NamespaceInfo *) dobj);
9358                         break;
9359                 case DO_EXTENSION:
9360                         dumpExtension(fout, (ExtensionInfo *) dobj);
9361                         break;
9362                 case DO_TYPE:
9363                         dumpType(fout, (TypeInfo *) dobj);
9364                         break;
9365                 case DO_SHELL_TYPE:
9366                         dumpShellType(fout, (ShellTypeInfo *) dobj);
9367                         break;
9368                 case DO_FUNC:
9369                         dumpFunc(fout, (FuncInfo *) dobj);
9370                         break;
9371                 case DO_AGG:
9372                         dumpAgg(fout, (AggInfo *) dobj);
9373                         break;
9374                 case DO_OPERATOR:
9375                         dumpOpr(fout, (OprInfo *) dobj);
9376                         break;
9377                 case DO_ACCESS_METHOD:
9378                         dumpAccessMethod(fout, (AccessMethodInfo *) dobj);
9379                         break;
9380                 case DO_OPCLASS:
9381                         dumpOpclass(fout, (OpclassInfo *) dobj);
9382                         break;
9383                 case DO_OPFAMILY:
9384                         dumpOpfamily(fout, (OpfamilyInfo *) dobj);
9385                         break;
9386                 case DO_COLLATION:
9387                         dumpCollation(fout, (CollInfo *) dobj);
9388                         break;
9389                 case DO_CONVERSION:
9390                         dumpConversion(fout, (ConvInfo *) dobj);
9391                         break;
9392                 case DO_TABLE:
9393                         dumpTable(fout, (TableInfo *) dobj);
9394                         break;
9395                 case DO_ATTRDEF:
9396                         dumpAttrDef(fout, (AttrDefInfo *) dobj);
9397                         break;
9398                 case DO_INDEX:
9399                         dumpIndex(fout, (IndxInfo *) dobj);
9400                         break;
9401                 case DO_STATSEXT:
9402                         dumpStatisticsExt(fout, (StatsExtInfo *) dobj);
9403                         break;
9404                 case DO_REFRESH_MATVIEW:
9405                         refreshMatViewData(fout, (TableDataInfo *) dobj);
9406                         break;
9407                 case DO_RULE:
9408                         dumpRule(fout, (RuleInfo *) dobj);
9409                         break;
9410                 case DO_TRIGGER:
9411                         dumpTrigger(fout, (TriggerInfo *) dobj);
9412                         break;
9413                 case DO_EVENT_TRIGGER:
9414                         dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
9415                         break;
9416                 case DO_CONSTRAINT:
9417                         dumpConstraint(fout, (ConstraintInfo *) dobj);
9418                         break;
9419                 case DO_FK_CONSTRAINT:
9420                         dumpConstraint(fout, (ConstraintInfo *) dobj);
9421                         break;
9422                 case DO_PROCLANG:
9423                         dumpProcLang(fout, (ProcLangInfo *) dobj);
9424                         break;
9425                 case DO_CAST:
9426                         dumpCast(fout, (CastInfo *) dobj);
9427                         break;
9428                 case DO_TRANSFORM:
9429                         dumpTransform(fout, (TransformInfo *) dobj);
9430                         break;
9431                 case DO_SEQUENCE_SET:
9432                         dumpSequenceData(fout, (TableDataInfo *) dobj);
9433                         break;
9434                 case DO_TABLE_DATA:
9435                         dumpTableData(fout, (TableDataInfo *) dobj);
9436                         break;
9437                 case DO_DUMMY_TYPE:
9438                         /* table rowtypes and array types are never dumped separately */
9439                         break;
9440                 case DO_TSPARSER:
9441                         dumpTSParser(fout, (TSParserInfo *) dobj);
9442                         break;
9443                 case DO_TSDICT:
9444                         dumpTSDictionary(fout, (TSDictInfo *) dobj);
9445                         break;
9446                 case DO_TSTEMPLATE:
9447                         dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
9448                         break;
9449                 case DO_TSCONFIG:
9450                         dumpTSConfig(fout, (TSConfigInfo *) dobj);
9451                         break;
9452                 case DO_FDW:
9453                         dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
9454                         break;
9455                 case DO_FOREIGN_SERVER:
9456                         dumpForeignServer(fout, (ForeignServerInfo *) dobj);
9457                         break;
9458                 case DO_DEFAULT_ACL:
9459                         dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
9460                         break;
9461                 case DO_BLOB:
9462                         dumpBlob(fout, (BlobInfo *) dobj);
9463                         break;
9464                 case DO_BLOB_DATA:
9465                         if (dobj->dump & DUMP_COMPONENT_DATA)
9466                                 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
9467                                                          dobj->name, NULL, NULL, "",
9468                                                          false, "BLOBS", SECTION_DATA,
9469                                                          "", "", NULL,
9470                                                          NULL, 0,
9471                                                          dumpBlobs, NULL);
9472                         break;
9473                 case DO_POLICY:
9474                         dumpPolicy(fout, (PolicyInfo *) dobj);
9475                         break;
9476                 case DO_PUBLICATION:
9477                         dumpPublication(fout, (PublicationInfo *) dobj);
9478                         break;
9479                 case DO_PUBLICATION_REL:
9480                         dumpPublicationTable(fout, (PublicationRelInfo *) dobj);
9481                         break;
9482                 case DO_SUBSCRIPTION:
9483                         dumpSubscription(fout, (SubscriptionInfo *) dobj);
9484                         break;
9485                 case DO_PRE_DATA_BOUNDARY:
9486                 case DO_POST_DATA_BOUNDARY:
9487                         /* never dumped, nothing to do */
9488                         break;
9489         }
9490 }
9491
9492 /*
9493  * dumpNamespace
9494  *        writes out to fout the queries to recreate a user-defined namespace
9495  */
9496 static void
9497 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
9498 {
9499         DumpOptions *dopt = fout->dopt;
9500         PQExpBuffer q;
9501         PQExpBuffer delq;
9502         PQExpBuffer labelq;
9503         char       *qnspname;
9504
9505         /* Skip if not to be dumped */
9506         if (!nspinfo->dobj.dump || dopt->dataOnly)
9507                 return;
9508
9509         q = createPQExpBuffer();
9510         delq = createPQExpBuffer();
9511         labelq = createPQExpBuffer();
9512
9513         qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
9514
9515         appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
9516
9517         appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
9518
9519         appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
9520
9521         if (dopt->binary_upgrade)
9522                 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
9523
9524         if (nspinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9525                 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
9526                                          nspinfo->dobj.name,
9527                                          NULL, NULL,
9528                                          nspinfo->rolname,
9529                                          false, "SCHEMA", SECTION_PRE_DATA,
9530                                          q->data, delq->data, NULL,
9531                                          NULL, 0,
9532                                          NULL, NULL);
9533
9534         /* Dump Schema Comments and Security Labels */
9535         if (nspinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9536                 dumpComment(fout, labelq->data,
9537                                         NULL, nspinfo->rolname,
9538                                         nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9539
9540         if (nspinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9541                 dumpSecLabel(fout, labelq->data,
9542                                          NULL, nspinfo->rolname,
9543                                          nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
9544
9545         if (nspinfo->dobj.dump & DUMP_COMPONENT_ACL)
9546                 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
9547                                 qnspname, NULL, nspinfo->dobj.name, NULL,
9548                                 nspinfo->rolname, nspinfo->nspacl, nspinfo->rnspacl,
9549                                 nspinfo->initnspacl, nspinfo->initrnspacl);
9550
9551         free(qnspname);
9552
9553         destroyPQExpBuffer(q);
9554         destroyPQExpBuffer(delq);
9555         destroyPQExpBuffer(labelq);
9556 }
9557
9558 /*
9559  * dumpExtension
9560  *        writes out to fout the queries to recreate an extension
9561  */
9562 static void
9563 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
9564 {
9565         DumpOptions *dopt = fout->dopt;
9566         PQExpBuffer q;
9567         PQExpBuffer delq;
9568         PQExpBuffer labelq;
9569         char       *qextname;
9570
9571         /* Skip if not to be dumped */
9572         if (!extinfo->dobj.dump || dopt->dataOnly)
9573                 return;
9574
9575         q = createPQExpBuffer();
9576         delq = createPQExpBuffer();
9577         labelq = createPQExpBuffer();
9578
9579         qextname = pg_strdup(fmtId(extinfo->dobj.name));
9580
9581         appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
9582
9583         if (!dopt->binary_upgrade)
9584         {
9585                 /*
9586                  * In a regular dump, we use IF NOT EXISTS so that there isn't a
9587                  * problem if the extension already exists in the target database;
9588                  * this is essential for installed-by-default extensions such as
9589                  * plpgsql.
9590                  *
9591                  * In binary-upgrade mode, that doesn't work well, so instead we skip
9592                  * built-in extensions based on their OIDs; see
9593                  * selectDumpableExtension.
9594                  */
9595                 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
9596                                                   qextname, fmtId(extinfo->namespace));
9597         }
9598         else
9599         {
9600                 int                     i;
9601                 int                     n;
9602
9603                 appendPQExpBufferStr(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
9604
9605                 /*
9606                  * We unconditionally create the extension, so we must drop it if it
9607                  * exists.  This could happen if the user deleted 'plpgsql' and then
9608                  * readded it, causing its oid to be greater than g_last_builtin_oid.
9609                  * The g_last_builtin_oid test was kept to avoid repeatedly dropping
9610                  * and recreating extensions like 'plpgsql'.
9611                  */
9612                 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
9613
9614                 appendPQExpBufferStr(q,
9615                                                          "SELECT pg_catalog.binary_upgrade_create_empty_extension(");
9616                 appendStringLiteralAH(q, extinfo->dobj.name, fout);
9617                 appendPQExpBufferStr(q, ", ");
9618                 appendStringLiteralAH(q, extinfo->namespace, fout);
9619                 appendPQExpBufferStr(q, ", ");
9620                 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
9621                 appendStringLiteralAH(q, extinfo->extversion, fout);
9622                 appendPQExpBufferStr(q, ", ");
9623
9624                 /*
9625                  * Note that we're pushing extconfig (an OID array) back into
9626                  * pg_extension exactly as-is.  This is OK because pg_class OIDs are
9627                  * preserved in binary upgrade.
9628                  */
9629                 if (strlen(extinfo->extconfig) > 2)
9630                         appendStringLiteralAH(q, extinfo->extconfig, fout);
9631                 else
9632                         appendPQExpBufferStr(q, "NULL");
9633                 appendPQExpBufferStr(q, ", ");
9634                 if (strlen(extinfo->extcondition) > 2)
9635                         appendStringLiteralAH(q, extinfo->extcondition, fout);
9636                 else
9637                         appendPQExpBufferStr(q, "NULL");
9638                 appendPQExpBufferStr(q, ", ");
9639                 appendPQExpBufferStr(q, "ARRAY[");
9640                 n = 0;
9641                 for (i = 0; i < extinfo->dobj.nDeps; i++)
9642                 {
9643                         DumpableObject *extobj;
9644
9645                         extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
9646                         if (extobj && extobj->objType == DO_EXTENSION)
9647                         {
9648                                 if (n++ > 0)
9649                                         appendPQExpBufferChar(q, ',');
9650                                 appendStringLiteralAH(q, extobj->name, fout);
9651                         }
9652                 }
9653                 appendPQExpBufferStr(q, "]::pg_catalog.text[]");
9654                 appendPQExpBufferStr(q, ");\n");
9655         }
9656
9657         appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
9658
9659         if (extinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9660                 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
9661                                          extinfo->dobj.name,
9662                                          NULL, NULL,
9663                                          "",
9664                                          false, "EXTENSION", SECTION_PRE_DATA,
9665                                          q->data, delq->data, NULL,
9666                                          NULL, 0,
9667                                          NULL, NULL);
9668
9669         /* Dump Extension Comments and Security Labels */
9670         if (extinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9671                 dumpComment(fout, labelq->data,
9672                                         NULL, "",
9673                                         extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
9674
9675         if (extinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9676                 dumpSecLabel(fout, labelq->data,
9677                                          NULL, "",
9678                                          extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
9679
9680         free(qextname);
9681
9682         destroyPQExpBuffer(q);
9683         destroyPQExpBuffer(delq);
9684         destroyPQExpBuffer(labelq);
9685 }
9686
9687 /*
9688  * dumpType
9689  *        writes out to fout the queries to recreate a user-defined type
9690  */
9691 static void
9692 dumpType(Archive *fout, TypeInfo *tyinfo)
9693 {
9694         DumpOptions *dopt = fout->dopt;
9695
9696         /* Skip if not to be dumped */
9697         if (!tyinfo->dobj.dump || dopt->dataOnly)
9698                 return;
9699
9700         /* Dump out in proper style */
9701         if (tyinfo->typtype == TYPTYPE_BASE)
9702                 dumpBaseType(fout, tyinfo);
9703         else if (tyinfo->typtype == TYPTYPE_DOMAIN)
9704                 dumpDomain(fout, tyinfo);
9705         else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
9706                 dumpCompositeType(fout, tyinfo);
9707         else if (tyinfo->typtype == TYPTYPE_ENUM)
9708                 dumpEnumType(fout, tyinfo);
9709         else if (tyinfo->typtype == TYPTYPE_RANGE)
9710                 dumpRangeType(fout, tyinfo);
9711         else if (tyinfo->typtype == TYPTYPE_PSEUDO && !tyinfo->isDefined)
9712                 dumpUndefinedType(fout, tyinfo);
9713         else
9714                 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
9715                                   tyinfo->dobj.name);
9716 }
9717
9718 /*
9719  * dumpEnumType
9720  *        writes out to fout the queries to recreate a user-defined enum type
9721  */
9722 static void
9723 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
9724 {
9725         DumpOptions *dopt = fout->dopt;
9726         PQExpBuffer q = createPQExpBuffer();
9727         PQExpBuffer delq = createPQExpBuffer();
9728         PQExpBuffer labelq = createPQExpBuffer();
9729         PQExpBuffer query = createPQExpBuffer();
9730         PGresult   *res;
9731         int                     num,
9732                                 i;
9733         Oid                     enum_oid;
9734         char       *qtypname;
9735         char       *label;
9736
9737         /* Set proper schema search path */
9738         selectSourceSchema(fout, "pg_catalog");
9739
9740         if (fout->remoteVersion >= 90100)
9741                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
9742                                                   "FROM pg_catalog.pg_enum "
9743                                                   "WHERE enumtypid = '%u'"
9744                                                   "ORDER BY enumsortorder",
9745                                                   tyinfo->dobj.catId.oid);
9746         else
9747                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
9748                                                   "FROM pg_catalog.pg_enum "
9749                                                   "WHERE enumtypid = '%u'"
9750                                                   "ORDER BY oid",
9751                                                   tyinfo->dobj.catId.oid);
9752
9753         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9754
9755         num = PQntuples(res);
9756
9757         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
9758
9759         /*
9760          * DROP must be fully qualified in case same name appears in pg_catalog.
9761          * CASCADE shouldn't be required here as for normal types since the I/O
9762          * functions are generic and do not get dropped.
9763          */
9764         appendPQExpBuffer(delq, "DROP TYPE %s.",
9765                                           fmtId(tyinfo->dobj.namespace->dobj.name));
9766         appendPQExpBuffer(delq, "%s;\n",
9767                                           qtypname);
9768
9769         if (dopt->binary_upgrade)
9770                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
9771                                                                                                  tyinfo->dobj.catId.oid);
9772
9773         appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
9774                                           qtypname);
9775
9776         if (!dopt->binary_upgrade)
9777         {
9778                 /* Labels with server-assigned oids */
9779                 for (i = 0; i < num; i++)
9780                 {
9781                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
9782                         if (i > 0)
9783                                 appendPQExpBufferChar(q, ',');
9784                         appendPQExpBufferStr(q, "\n    ");
9785                         appendStringLiteralAH(q, label, fout);
9786                 }
9787         }
9788
9789         appendPQExpBufferStr(q, "\n);\n");
9790
9791         if (dopt->binary_upgrade)
9792         {
9793                 /* Labels with dump-assigned (preserved) oids */
9794                 for (i = 0; i < num; i++)
9795                 {
9796                         enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
9797                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
9798
9799                         if (i == 0)
9800                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
9801                         appendPQExpBuffer(q,
9802                                                           "SELECT pg_catalog.binary_upgrade_set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
9803                                                           enum_oid);
9804                         appendPQExpBuffer(q, "ALTER TYPE %s.",
9805                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
9806                         appendPQExpBuffer(q, "%s ADD VALUE ",
9807                                                           qtypname);
9808                         appendStringLiteralAH(q, label, fout);
9809                         appendPQExpBufferStr(q, ";\n\n");
9810                 }
9811         }
9812
9813         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
9814
9815         if (dopt->binary_upgrade)
9816                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
9817
9818         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9819                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
9820                                          tyinfo->dobj.name,
9821                                          tyinfo->dobj.namespace->dobj.name,
9822                                          NULL,
9823                                          tyinfo->rolname, false,
9824                                          "TYPE", SECTION_PRE_DATA,
9825                                          q->data, delq->data, NULL,
9826                                          NULL, 0,
9827                                          NULL, NULL);
9828
9829         /* Dump Type Comments and Security Labels */
9830         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9831                 dumpComment(fout, labelq->data,
9832                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
9833                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
9834
9835         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9836                 dumpSecLabel(fout, labelq->data,
9837                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
9838                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
9839
9840         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
9841                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
9842                                 qtypname, NULL, tyinfo->dobj.name,
9843                                 tyinfo->dobj.namespace->dobj.name,
9844                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
9845                                 tyinfo->inittypacl, tyinfo->initrtypacl);
9846
9847         PQclear(res);
9848         destroyPQExpBuffer(q);
9849         destroyPQExpBuffer(delq);
9850         destroyPQExpBuffer(labelq);
9851         destroyPQExpBuffer(query);
9852 }
9853
9854 /*
9855  * dumpRangeType
9856  *        writes out to fout the queries to recreate a user-defined range type
9857  */
9858 static void
9859 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
9860 {
9861         DumpOptions *dopt = fout->dopt;
9862         PQExpBuffer q = createPQExpBuffer();
9863         PQExpBuffer delq = createPQExpBuffer();
9864         PQExpBuffer labelq = createPQExpBuffer();
9865         PQExpBuffer query = createPQExpBuffer();
9866         PGresult   *res;
9867         Oid                     collationOid;
9868         char       *qtypname;
9869         char       *procname;
9870
9871         /*
9872          * select appropriate schema to ensure names in CREATE are properly
9873          * qualified
9874          */
9875         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
9876
9877         appendPQExpBuffer(query,
9878                                           "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
9879                                           "opc.opcname AS opcname, "
9880                                           "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
9881                                           "  WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
9882                                           "opc.opcdefault, "
9883                                           "CASE WHEN rngcollation = st.typcollation THEN 0 "
9884                                           "     ELSE rngcollation END AS collation, "
9885                                           "rngcanonical, rngsubdiff "
9886                                           "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
9887                                           "     pg_catalog.pg_opclass opc "
9888                                           "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
9889                                           "rngtypid = '%u'",
9890                                           tyinfo->dobj.catId.oid);
9891
9892         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9893
9894         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
9895
9896         /*
9897          * DROP must be fully qualified in case same name appears in pg_catalog.
9898          * CASCADE shouldn't be required here as for normal types since the I/O
9899          * functions are generic and do not get dropped.
9900          */
9901         appendPQExpBuffer(delq, "DROP TYPE %s.",
9902                                           fmtId(tyinfo->dobj.namespace->dobj.name));
9903         appendPQExpBuffer(delq, "%s;\n",
9904                                           qtypname);
9905
9906         if (dopt->binary_upgrade)
9907                 binary_upgrade_set_type_oids_by_type_oid(fout,
9908                                                                                                  q, tyinfo->dobj.catId.oid);
9909
9910         appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
9911                                           qtypname);
9912
9913         appendPQExpBuffer(q, "\n    subtype = %s",
9914                                           PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
9915
9916         /* print subtype_opclass only if not default for subtype */
9917         if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
9918         {
9919                 char       *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
9920                 char       *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
9921
9922                 /* always schema-qualify, don't try to be smart */
9923                 appendPQExpBuffer(q, ",\n    subtype_opclass = %s.",
9924                                                   fmtId(nspname));
9925                 appendPQExpBufferStr(q, fmtId(opcname));
9926         }
9927
9928         collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
9929         if (OidIsValid(collationOid))
9930         {
9931                 CollInfo   *coll = findCollationByOid(collationOid);
9932
9933                 if (coll)
9934                 {
9935                         /* always schema-qualify, don't try to be smart */
9936                         appendPQExpBuffer(q, ",\n    collation = %s.",
9937                                                           fmtId(coll->dobj.namespace->dobj.name));
9938                         appendPQExpBufferStr(q, fmtId(coll->dobj.name));
9939                 }
9940         }
9941
9942         procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
9943         if (strcmp(procname, "-") != 0)
9944                 appendPQExpBuffer(q, ",\n    canonical = %s", procname);
9945
9946         procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
9947         if (strcmp(procname, "-") != 0)
9948                 appendPQExpBuffer(q, ",\n    subtype_diff = %s", procname);
9949
9950         appendPQExpBufferStr(q, "\n);\n");
9951
9952         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
9953
9954         if (dopt->binary_upgrade)
9955                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
9956
9957         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
9958                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
9959                                          tyinfo->dobj.name,
9960                                          tyinfo->dobj.namespace->dobj.name,
9961                                          NULL,
9962                                          tyinfo->rolname, false,
9963                                          "TYPE", SECTION_PRE_DATA,
9964                                          q->data, delq->data, NULL,
9965                                          NULL, 0,
9966                                          NULL, NULL);
9967
9968         /* Dump Type Comments and Security Labels */
9969         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
9970                 dumpComment(fout, labelq->data,
9971                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
9972                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
9973
9974         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
9975                 dumpSecLabel(fout, labelq->data,
9976                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
9977                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
9978
9979         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
9980                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
9981                                 qtypname, NULL, tyinfo->dobj.name,
9982                                 tyinfo->dobj.namespace->dobj.name,
9983                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
9984                                 tyinfo->inittypacl, tyinfo->initrtypacl);
9985
9986         PQclear(res);
9987         destroyPQExpBuffer(q);
9988         destroyPQExpBuffer(delq);
9989         destroyPQExpBuffer(labelq);
9990         destroyPQExpBuffer(query);
9991 }
9992
9993 /*
9994  * dumpUndefinedType
9995  *        writes out to fout the queries to recreate a !typisdefined type
9996  *
9997  * This is a shell type, but we use different terminology to distinguish
9998  * this case from where we have to emit a shell type definition to break
9999  * circular dependencies.  An undefined type shouldn't ever have anything
10000  * depending on it.
10001  */
10002 static void
10003 dumpUndefinedType(Archive *fout, TypeInfo *tyinfo)
10004 {
10005         DumpOptions *dopt = fout->dopt;
10006         PQExpBuffer q = createPQExpBuffer();
10007         PQExpBuffer delq = createPQExpBuffer();
10008         PQExpBuffer labelq = createPQExpBuffer();
10009         char       *qtypname;
10010
10011         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10012
10013         /*
10014          * DROP must be fully qualified in case same name appears in pg_catalog.
10015          */
10016         appendPQExpBuffer(delq, "DROP TYPE %s.",
10017                                           fmtId(tyinfo->dobj.namespace->dobj.name));
10018         appendPQExpBuffer(delq, "%s;\n",
10019                                           qtypname);
10020
10021         if (dopt->binary_upgrade)
10022                 binary_upgrade_set_type_oids_by_type_oid(fout,
10023                                                                                                  q, tyinfo->dobj.catId.oid);
10024
10025         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
10026                                           qtypname);
10027
10028         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
10029
10030         if (dopt->binary_upgrade)
10031                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
10032
10033         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10034                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10035                                          tyinfo->dobj.name,
10036                                          tyinfo->dobj.namespace->dobj.name,
10037                                          NULL,
10038                                          tyinfo->rolname, false,
10039                                          "TYPE", SECTION_PRE_DATA,
10040                                          q->data, delq->data, NULL,
10041                                          NULL, 0,
10042                                          NULL, NULL);
10043
10044         /* Dump Type Comments and Security Labels */
10045         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10046                 dumpComment(fout, labelq->data,
10047                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10048                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10049
10050         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10051                 dumpSecLabel(fout, labelq->data,
10052                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10053                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10054
10055         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10056                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10057                                 qtypname, NULL, tyinfo->dobj.name,
10058                                 tyinfo->dobj.namespace->dobj.name,
10059                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10060                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10061
10062         destroyPQExpBuffer(q);
10063         destroyPQExpBuffer(delq);
10064         destroyPQExpBuffer(labelq);
10065 }
10066
10067 /*
10068  * dumpBaseType
10069  *        writes out to fout the queries to recreate a user-defined base type
10070  */
10071 static void
10072 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
10073 {
10074         DumpOptions *dopt = fout->dopt;
10075         PQExpBuffer q = createPQExpBuffer();
10076         PQExpBuffer delq = createPQExpBuffer();
10077         PQExpBuffer labelq = createPQExpBuffer();
10078         PQExpBuffer query = createPQExpBuffer();
10079         PGresult   *res;
10080         char       *qtypname;
10081         char       *typlen;
10082         char       *typinput;
10083         char       *typoutput;
10084         char       *typreceive;
10085         char       *typsend;
10086         char       *typmodin;
10087         char       *typmodout;
10088         char       *typanalyze;
10089         Oid                     typreceiveoid;
10090         Oid                     typsendoid;
10091         Oid                     typmodinoid;
10092         Oid                     typmodoutoid;
10093         Oid                     typanalyzeoid;
10094         char       *typcategory;
10095         char       *typispreferred;
10096         char       *typdelim;
10097         char       *typbyval;
10098         char       *typalign;
10099         char       *typstorage;
10100         char       *typcollatable;
10101         char       *typdefault;
10102         bool            typdefault_is_literal = false;
10103
10104         /* Set proper schema search path so regproc references list correctly */
10105         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
10106
10107         /* Fetch type-specific details */
10108         if (fout->remoteVersion >= 90100)
10109         {
10110                 appendPQExpBuffer(query, "SELECT typlen, "
10111                                                   "typinput, typoutput, typreceive, typsend, "
10112                                                   "typmodin, typmodout, typanalyze, "
10113                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
10114                                                   "typsend::pg_catalog.oid AS typsendoid, "
10115                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
10116                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
10117                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10118                                                   "typcategory, typispreferred, "
10119                                                   "typdelim, typbyval, typalign, typstorage, "
10120                                                   "(typcollation <> 0) AS typcollatable, "
10121                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10122                                                   "FROM pg_catalog.pg_type "
10123                                                   "WHERE oid = '%u'::pg_catalog.oid",
10124                                                   tyinfo->dobj.catId.oid);
10125         }
10126         else if (fout->remoteVersion >= 80400)
10127         {
10128                 appendPQExpBuffer(query, "SELECT typlen, "
10129                                                   "typinput, typoutput, typreceive, typsend, "
10130                                                   "typmodin, typmodout, typanalyze, "
10131                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
10132                                                   "typsend::pg_catalog.oid AS typsendoid, "
10133                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
10134                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
10135                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10136                                                   "typcategory, typispreferred, "
10137                                                   "typdelim, typbyval, typalign, typstorage, "
10138                                                   "false AS typcollatable, "
10139                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10140                                                   "FROM pg_catalog.pg_type "
10141                                                   "WHERE oid = '%u'::pg_catalog.oid",
10142                                                   tyinfo->dobj.catId.oid);
10143         }
10144         else if (fout->remoteVersion >= 80300)
10145         {
10146                 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
10147                 appendPQExpBuffer(query, "SELECT typlen, "
10148                                                   "typinput, typoutput, typreceive, typsend, "
10149                                                   "typmodin, typmodout, typanalyze, "
10150                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
10151                                                   "typsend::pg_catalog.oid AS typsendoid, "
10152                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
10153                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
10154                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10155                                                   "'U' AS typcategory, false AS typispreferred, "
10156                                                   "typdelim, typbyval, typalign, typstorage, "
10157                                                   "false AS typcollatable, "
10158                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10159                                                   "FROM pg_catalog.pg_type "
10160                                                   "WHERE oid = '%u'::pg_catalog.oid",
10161                                                   tyinfo->dobj.catId.oid);
10162         }
10163         else
10164         {
10165                 appendPQExpBuffer(query, "SELECT typlen, "
10166                                                   "typinput, typoutput, typreceive, typsend, "
10167                                                   "'-' AS typmodin, '-' AS typmodout, "
10168                                                   "typanalyze, "
10169                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
10170                                                   "typsend::pg_catalog.oid AS typsendoid, "
10171                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
10172                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10173                                                   "'U' AS typcategory, false AS typispreferred, "
10174                                                   "typdelim, typbyval, typalign, typstorage, "
10175                                                   "false AS typcollatable, "
10176                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10177                                                   "FROM pg_catalog.pg_type "
10178                                                   "WHERE oid = '%u'::pg_catalog.oid",
10179                                                   tyinfo->dobj.catId.oid);
10180         }
10181
10182         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10183
10184         typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
10185         typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
10186         typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
10187         typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
10188         typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
10189         typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
10190         typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
10191         typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
10192         typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
10193         typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
10194         typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
10195         typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
10196         typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
10197         typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
10198         typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
10199         typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
10200         typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
10201         typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
10202         typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
10203         typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
10204         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10205                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10206         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10207         {
10208                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10209                 typdefault_is_literal = true;   /* it needs quotes */
10210         }
10211         else
10212                 typdefault = NULL;
10213
10214         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10215
10216         /*
10217          * DROP must be fully qualified in case same name appears in pg_catalog.
10218          * The reason we include CASCADE is that the circular dependency between
10219          * the type and its I/O functions makes it impossible to drop the type any
10220          * other way.
10221          */
10222         appendPQExpBuffer(delq, "DROP TYPE %s.",
10223                                           fmtId(tyinfo->dobj.namespace->dobj.name));
10224         appendPQExpBuffer(delq, "%s CASCADE;\n",
10225                                           qtypname);
10226
10227         /* We might already have a shell type, but setting pg_type_oid is harmless */
10228         if (dopt->binary_upgrade)
10229                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10230                                                                                                  tyinfo->dobj.catId.oid);
10231
10232         appendPQExpBuffer(q,
10233                                           "CREATE TYPE %s (\n"
10234                                           "    INTERNALLENGTH = %s",
10235                                           qtypname,
10236                                           (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
10237
10238         /* regproc result is sufficiently quoted already */
10239         appendPQExpBuffer(q, ",\n    INPUT = %s", typinput);
10240         appendPQExpBuffer(q, ",\n    OUTPUT = %s", typoutput);
10241         if (OidIsValid(typreceiveoid))
10242                 appendPQExpBuffer(q, ",\n    RECEIVE = %s", typreceive);
10243         if (OidIsValid(typsendoid))
10244                 appendPQExpBuffer(q, ",\n    SEND = %s", typsend);
10245         if (OidIsValid(typmodinoid))
10246                 appendPQExpBuffer(q, ",\n    TYPMOD_IN = %s", typmodin);
10247         if (OidIsValid(typmodoutoid))
10248                 appendPQExpBuffer(q, ",\n    TYPMOD_OUT = %s", typmodout);
10249         if (OidIsValid(typanalyzeoid))
10250                 appendPQExpBuffer(q, ",\n    ANALYZE = %s", typanalyze);
10251
10252         if (strcmp(typcollatable, "t") == 0)
10253                 appendPQExpBufferStr(q, ",\n    COLLATABLE = true");
10254
10255         if (typdefault != NULL)
10256         {
10257                 appendPQExpBufferStr(q, ",\n    DEFAULT = ");
10258                 if (typdefault_is_literal)
10259                         appendStringLiteralAH(q, typdefault, fout);
10260                 else
10261                         appendPQExpBufferStr(q, typdefault);
10262         }
10263
10264         if (OidIsValid(tyinfo->typelem))
10265         {
10266                 char       *elemType;
10267
10268                 /* reselect schema in case changed by function dump */
10269                 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
10270                 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
10271                 appendPQExpBuffer(q, ",\n    ELEMENT = %s", elemType);
10272                 free(elemType);
10273         }
10274
10275         if (strcmp(typcategory, "U") != 0)
10276         {
10277                 appendPQExpBufferStr(q, ",\n    CATEGORY = ");
10278                 appendStringLiteralAH(q, typcategory, fout);
10279         }
10280
10281         if (strcmp(typispreferred, "t") == 0)
10282                 appendPQExpBufferStr(q, ",\n    PREFERRED = true");
10283
10284         if (typdelim && strcmp(typdelim, ",") != 0)
10285         {
10286                 appendPQExpBufferStr(q, ",\n    DELIMITER = ");
10287                 appendStringLiteralAH(q, typdelim, fout);
10288         }
10289
10290         if (strcmp(typalign, "c") == 0)
10291                 appendPQExpBufferStr(q, ",\n    ALIGNMENT = char");
10292         else if (strcmp(typalign, "s") == 0)
10293                 appendPQExpBufferStr(q, ",\n    ALIGNMENT = int2");
10294         else if (strcmp(typalign, "i") == 0)
10295                 appendPQExpBufferStr(q, ",\n    ALIGNMENT = int4");
10296         else if (strcmp(typalign, "d") == 0)
10297                 appendPQExpBufferStr(q, ",\n    ALIGNMENT = double");
10298
10299         if (strcmp(typstorage, "p") == 0)
10300                 appendPQExpBufferStr(q, ",\n    STORAGE = plain");
10301         else if (strcmp(typstorage, "e") == 0)
10302                 appendPQExpBufferStr(q, ",\n    STORAGE = external");
10303         else if (strcmp(typstorage, "x") == 0)
10304                 appendPQExpBufferStr(q, ",\n    STORAGE = extended");
10305         else if (strcmp(typstorage, "m") == 0)
10306                 appendPQExpBufferStr(q, ",\n    STORAGE = main");
10307
10308         if (strcmp(typbyval, "t") == 0)
10309                 appendPQExpBufferStr(q, ",\n    PASSEDBYVALUE");
10310
10311         appendPQExpBufferStr(q, "\n);\n");
10312
10313         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
10314
10315         if (dopt->binary_upgrade)
10316                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
10317
10318         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10319                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10320                                          tyinfo->dobj.name,
10321                                          tyinfo->dobj.namespace->dobj.name,
10322                                          NULL,
10323                                          tyinfo->rolname, false,
10324                                          "TYPE", SECTION_PRE_DATA,
10325                                          q->data, delq->data, NULL,
10326                                          NULL, 0,
10327                                          NULL, NULL);
10328
10329         /* Dump Type Comments and Security Labels */
10330         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10331                 dumpComment(fout, labelq->data,
10332                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10333                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10334
10335         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10336                 dumpSecLabel(fout, labelq->data,
10337                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10338                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10339
10340         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10341                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10342                                 qtypname, NULL, tyinfo->dobj.name,
10343                                 tyinfo->dobj.namespace->dobj.name,
10344                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10345                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10346
10347         PQclear(res);
10348         destroyPQExpBuffer(q);
10349         destroyPQExpBuffer(delq);
10350         destroyPQExpBuffer(labelq);
10351         destroyPQExpBuffer(query);
10352 }
10353
10354 /*
10355  * dumpDomain
10356  *        writes out to fout the queries to recreate a user-defined domain
10357  */
10358 static void
10359 dumpDomain(Archive *fout, TypeInfo *tyinfo)
10360 {
10361         DumpOptions *dopt = fout->dopt;
10362         PQExpBuffer q = createPQExpBuffer();
10363         PQExpBuffer delq = createPQExpBuffer();
10364         PQExpBuffer labelq = createPQExpBuffer();
10365         PQExpBuffer query = createPQExpBuffer();
10366         PGresult   *res;
10367         int                     i;
10368         char       *qtypname;
10369         char       *typnotnull;
10370         char       *typdefn;
10371         char       *typdefault;
10372         Oid                     typcollation;
10373         bool            typdefault_is_literal = false;
10374
10375         /* Set proper schema search path so type references list correctly */
10376         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
10377
10378         /* Fetch domain specific details */
10379         if (fout->remoteVersion >= 90100)
10380         {
10381                 /* typcollation is new in 9.1 */
10382                 appendPQExpBuffer(query, "SELECT t.typnotnull, "
10383                                                   "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
10384                                                   "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10385                                                   "t.typdefault, "
10386                                                   "CASE WHEN t.typcollation <> u.typcollation "
10387                                                   "THEN t.typcollation ELSE 0 END AS typcollation "
10388                                                   "FROM pg_catalog.pg_type t "
10389                                                   "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
10390                                                   "WHERE t.oid = '%u'::pg_catalog.oid",
10391                                                   tyinfo->dobj.catId.oid);
10392         }
10393         else
10394         {
10395                 appendPQExpBuffer(query, "SELECT typnotnull, "
10396                                                   "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
10397                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
10398                                                   "typdefault, 0 AS typcollation "
10399                                                   "FROM pg_catalog.pg_type "
10400                                                   "WHERE oid = '%u'::pg_catalog.oid",
10401                                                   tyinfo->dobj.catId.oid);
10402         }
10403
10404         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10405
10406         typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
10407         typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
10408         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
10409                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
10410         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
10411         {
10412                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
10413                 typdefault_is_literal = true;   /* it needs quotes */
10414         }
10415         else
10416                 typdefault = NULL;
10417         typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
10418
10419         if (dopt->binary_upgrade)
10420                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10421                                                                                                  tyinfo->dobj.catId.oid);
10422
10423         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10424
10425         appendPQExpBuffer(q,
10426                                           "CREATE DOMAIN %s AS %s",
10427                                           qtypname,
10428                                           typdefn);
10429
10430         /* Print collation only if different from base type's collation */
10431         if (OidIsValid(typcollation))
10432         {
10433                 CollInfo   *coll;
10434
10435                 coll = findCollationByOid(typcollation);
10436                 if (coll)
10437                 {
10438                         /* always schema-qualify, don't try to be smart */
10439                         appendPQExpBuffer(q, " COLLATE %s.",
10440                                                           fmtId(coll->dobj.namespace->dobj.name));
10441                         appendPQExpBufferStr(q, fmtId(coll->dobj.name));
10442                 }
10443         }
10444
10445         if (typnotnull[0] == 't')
10446                 appendPQExpBufferStr(q, " NOT NULL");
10447
10448         if (typdefault != NULL)
10449         {
10450                 appendPQExpBufferStr(q, " DEFAULT ");
10451                 if (typdefault_is_literal)
10452                         appendStringLiteralAH(q, typdefault, fout);
10453                 else
10454                         appendPQExpBufferStr(q, typdefault);
10455         }
10456
10457         PQclear(res);
10458
10459         /*
10460          * Add any CHECK constraints for the domain
10461          */
10462         for (i = 0; i < tyinfo->nDomChecks; i++)
10463         {
10464                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10465
10466                 if (!domcheck->separate)
10467                         appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
10468                                                           fmtId(domcheck->dobj.name), domcheck->condef);
10469         }
10470
10471         appendPQExpBufferStr(q, ";\n");
10472
10473         /*
10474          * DROP must be fully qualified in case same name appears in pg_catalog
10475          */
10476         appendPQExpBuffer(delq, "DROP DOMAIN %s.",
10477                                           fmtId(tyinfo->dobj.namespace->dobj.name));
10478         appendPQExpBuffer(delq, "%s;\n",
10479                                           qtypname);
10480
10481         appendPQExpBuffer(labelq, "DOMAIN %s", qtypname);
10482
10483         if (dopt->binary_upgrade)
10484                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
10485
10486         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10487                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10488                                          tyinfo->dobj.name,
10489                                          tyinfo->dobj.namespace->dobj.name,
10490                                          NULL,
10491                                          tyinfo->rolname, false,
10492                                          "DOMAIN", SECTION_PRE_DATA,
10493                                          q->data, delq->data, NULL,
10494                                          NULL, 0,
10495                                          NULL, NULL);
10496
10497         /* Dump Domain Comments and Security Labels */
10498         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10499                 dumpComment(fout, labelq->data,
10500                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10501                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10502
10503         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10504                 dumpSecLabel(fout, labelq->data,
10505                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10506                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10507
10508         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10509                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10510                                 qtypname, NULL, tyinfo->dobj.name,
10511                                 tyinfo->dobj.namespace->dobj.name,
10512                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10513                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10514
10515         /* Dump any per-constraint comments */
10516         for (i = 0; i < tyinfo->nDomChecks; i++)
10517         {
10518                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
10519                 PQExpBuffer labelq = createPQExpBuffer();
10520
10521                 appendPQExpBuffer(labelq, "CONSTRAINT %s ",
10522                                                   fmtId(domcheck->dobj.name));
10523                 appendPQExpBuffer(labelq, "ON DOMAIN %s",
10524                                                   qtypname);
10525
10526                 if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10527                         dumpComment(fout, labelq->data,
10528                                                 tyinfo->dobj.namespace->dobj.name,
10529                                                 tyinfo->rolname,
10530                                                 domcheck->dobj.catId, 0, tyinfo->dobj.dumpId);
10531
10532                 destroyPQExpBuffer(labelq);
10533         }
10534
10535         destroyPQExpBuffer(q);
10536         destroyPQExpBuffer(delq);
10537         destroyPQExpBuffer(labelq);
10538         destroyPQExpBuffer(query);
10539 }
10540
10541 /*
10542  * dumpCompositeType
10543  *        writes out to fout the queries to recreate a user-defined stand-alone
10544  *        composite type
10545  */
10546 static void
10547 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
10548 {
10549         DumpOptions *dopt = fout->dopt;
10550         PQExpBuffer q = createPQExpBuffer();
10551         PQExpBuffer dropped = createPQExpBuffer();
10552         PQExpBuffer delq = createPQExpBuffer();
10553         PQExpBuffer labelq = createPQExpBuffer();
10554         PQExpBuffer query = createPQExpBuffer();
10555         PGresult   *res;
10556         char       *qtypname;
10557         int                     ntups;
10558         int                     i_attname;
10559         int                     i_atttypdefn;
10560         int                     i_attlen;
10561         int                     i_attalign;
10562         int                     i_attisdropped;
10563         int                     i_attcollation;
10564         int                     i;
10565         int                     actual_atts;
10566
10567         /* Set proper schema search path so type references list correctly */
10568         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
10569
10570         /* Fetch type specific details */
10571         if (fout->remoteVersion >= 90100)
10572         {
10573                 /*
10574                  * attcollation is new in 9.1.  Since we only want to dump COLLATE
10575                  * clauses for attributes whose collation is different from their
10576                  * type's default, we use a CASE here to suppress uninteresting
10577                  * attcollations cheaply.  atttypid will be 0 for dropped columns;
10578                  * collation does not matter for those.
10579                  */
10580                 appendPQExpBuffer(query, "SELECT a.attname, "
10581                                                   "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10582                                                   "a.attlen, a.attalign, a.attisdropped, "
10583                                                   "CASE WHEN a.attcollation <> at.typcollation "
10584                                                   "THEN a.attcollation ELSE 0 END AS attcollation "
10585                                                   "FROM pg_catalog.pg_type ct "
10586                                                   "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
10587                                                   "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
10588                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
10589                                                   "ORDER BY a.attnum ",
10590                                                   tyinfo->dobj.catId.oid);
10591         }
10592         else
10593         {
10594                 /*
10595                  * Since ALTER TYPE could not drop columns until 9.1, attisdropped
10596                  * should always be false.
10597                  */
10598                 appendPQExpBuffer(query, "SELECT a.attname, "
10599                                                   "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
10600                                                   "a.attlen, a.attalign, a.attisdropped, "
10601                                                   "0 AS attcollation "
10602                                                   "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
10603                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
10604                                                   "AND a.attrelid = ct.typrelid "
10605                                                   "ORDER BY a.attnum ",
10606                                                   tyinfo->dobj.catId.oid);
10607         }
10608
10609         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10610
10611         ntups = PQntuples(res);
10612
10613         i_attname = PQfnumber(res, "attname");
10614         i_atttypdefn = PQfnumber(res, "atttypdefn");
10615         i_attlen = PQfnumber(res, "attlen");
10616         i_attalign = PQfnumber(res, "attalign");
10617         i_attisdropped = PQfnumber(res, "attisdropped");
10618         i_attcollation = PQfnumber(res, "attcollation");
10619
10620         if (dopt->binary_upgrade)
10621         {
10622                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10623                                                                                                  tyinfo->dobj.catId.oid);
10624                 binary_upgrade_set_pg_class_oids(fout, q, tyinfo->typrelid, false);
10625         }
10626
10627         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
10628
10629         appendPQExpBuffer(q, "CREATE TYPE %s AS (",
10630                                           qtypname);
10631
10632         actual_atts = 0;
10633         for (i = 0; i < ntups; i++)
10634         {
10635                 char       *attname;
10636                 char       *atttypdefn;
10637                 char       *attlen;
10638                 char       *attalign;
10639                 bool            attisdropped;
10640                 Oid                     attcollation;
10641
10642                 attname = PQgetvalue(res, i, i_attname);
10643                 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
10644                 attlen = PQgetvalue(res, i, i_attlen);
10645                 attalign = PQgetvalue(res, i, i_attalign);
10646                 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
10647                 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
10648
10649                 if (attisdropped && !dopt->binary_upgrade)
10650                         continue;
10651
10652                 /* Format properly if not first attr */
10653                 if (actual_atts++ > 0)
10654                         appendPQExpBufferChar(q, ',');
10655                 appendPQExpBufferStr(q, "\n\t");
10656
10657                 if (!attisdropped)
10658                 {
10659                         appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
10660
10661                         /* Add collation if not default for the column type */
10662                         if (OidIsValid(attcollation))
10663                         {
10664                                 CollInfo   *coll;
10665
10666                                 coll = findCollationByOid(attcollation);
10667                                 if (coll)
10668                                 {
10669                                         /* always schema-qualify, don't try to be smart */
10670                                         appendPQExpBuffer(q, " COLLATE %s.",
10671                                                                           fmtId(coll->dobj.namespace->dobj.name));
10672                                         appendPQExpBufferStr(q, fmtId(coll->dobj.name));
10673                                 }
10674                         }
10675                 }
10676                 else
10677                 {
10678                         /*
10679                          * This is a dropped attribute and we're in binary_upgrade mode.
10680                          * Insert a placeholder for it in the CREATE TYPE command, and set
10681                          * length and alignment with direct UPDATE to the catalogs
10682                          * afterwards. See similar code in dumpTableSchema().
10683                          */
10684                         appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
10685
10686                         /* stash separately for insertion after the CREATE TYPE */
10687                         appendPQExpBufferStr(dropped,
10688                                                                  "\n-- For binary upgrade, recreate dropped column.\n");
10689                         appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
10690                                                           "SET attlen = %s, "
10691                                                           "attalign = '%s', attbyval = false\n"
10692                                                           "WHERE attname = ", attlen, attalign);
10693                         appendStringLiteralAH(dropped, attname, fout);
10694                         appendPQExpBufferStr(dropped, "\n  AND attrelid = ");
10695                         appendStringLiteralAH(dropped, qtypname, fout);
10696                         appendPQExpBufferStr(dropped, "::pg_catalog.regclass;\n");
10697
10698                         appendPQExpBuffer(dropped, "ALTER TYPE %s ",
10699                                                           qtypname);
10700                         appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
10701                                                           fmtId(attname));
10702                 }
10703         }
10704         appendPQExpBufferStr(q, "\n);\n");
10705         appendPQExpBufferStr(q, dropped->data);
10706
10707         /*
10708          * DROP must be fully qualified in case same name appears in pg_catalog
10709          */
10710         appendPQExpBuffer(delq, "DROP TYPE %s.",
10711                                           fmtId(tyinfo->dobj.namespace->dobj.name));
10712         appendPQExpBuffer(delq, "%s;\n",
10713                                           qtypname);
10714
10715         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
10716
10717         if (dopt->binary_upgrade)
10718                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
10719
10720         if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10721                 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
10722                                          tyinfo->dobj.name,
10723                                          tyinfo->dobj.namespace->dobj.name,
10724                                          NULL,
10725                                          tyinfo->rolname, false,
10726                                          "TYPE", SECTION_PRE_DATA,
10727                                          q->data, delq->data, NULL,
10728                                          NULL, 0,
10729                                          NULL, NULL);
10730
10731
10732         /* Dump Type Comments and Security Labels */
10733         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10734                 dumpComment(fout, labelq->data,
10735                                         tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10736                                         tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10737
10738         if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10739                 dumpSecLabel(fout, labelq->data,
10740                                          tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
10741                                          tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
10742
10743         if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
10744                 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
10745                                 qtypname, NULL, tyinfo->dobj.name,
10746                                 tyinfo->dobj.namespace->dobj.name,
10747                                 tyinfo->rolname, tyinfo->typacl, tyinfo->rtypacl,
10748                                 tyinfo->inittypacl, tyinfo->initrtypacl);
10749
10750         PQclear(res);
10751         destroyPQExpBuffer(q);
10752         destroyPQExpBuffer(dropped);
10753         destroyPQExpBuffer(delq);
10754         destroyPQExpBuffer(labelq);
10755         destroyPQExpBuffer(query);
10756
10757         /* Dump any per-column comments */
10758         if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10759                 dumpCompositeTypeColComments(fout, tyinfo);
10760 }
10761
10762 /*
10763  * dumpCompositeTypeColComments
10764  *        writes out to fout the queries to recreate comments on the columns of
10765  *        a user-defined stand-alone composite type
10766  */
10767 static void
10768 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
10769 {
10770         CommentItem *comments;
10771         int                     ncomments;
10772         PGresult   *res;
10773         PQExpBuffer query;
10774         PQExpBuffer target;
10775         Oid                     pgClassOid;
10776         int                     i;
10777         int                     ntups;
10778         int                     i_attname;
10779         int                     i_attnum;
10780
10781         query = createPQExpBuffer();
10782
10783         appendPQExpBuffer(query,
10784                                           "SELECT c.tableoid, a.attname, a.attnum "
10785                                           "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
10786                                           "WHERE c.oid = '%u' AND c.oid = a.attrelid "
10787                                           "  AND NOT a.attisdropped "
10788                                           "ORDER BY a.attnum ",
10789                                           tyinfo->typrelid);
10790
10791         /* Fetch column attnames */
10792         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10793
10794         ntups = PQntuples(res);
10795         if (ntups < 1)
10796         {
10797                 PQclear(res);
10798                 destroyPQExpBuffer(query);
10799                 return;
10800         }
10801
10802         pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
10803
10804         /* Search for comments associated with type's pg_class OID */
10805         ncomments = findComments(fout,
10806                                                          pgClassOid,
10807                                                          tyinfo->typrelid,
10808                                                          &comments);
10809
10810         /* If no comments exist, we're done */
10811         if (ncomments <= 0)
10812         {
10813                 PQclear(res);
10814                 destroyPQExpBuffer(query);
10815                 return;
10816         }
10817
10818         /* Build COMMENT ON statements */
10819         target = createPQExpBuffer();
10820
10821         i_attnum = PQfnumber(res, "attnum");
10822         i_attname = PQfnumber(res, "attname");
10823         while (ncomments > 0)
10824         {
10825                 const char *attname;
10826
10827                 attname = NULL;
10828                 for (i = 0; i < ntups; i++)
10829                 {
10830                         if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
10831                         {
10832                                 attname = PQgetvalue(res, i, i_attname);
10833                                 break;
10834                         }
10835                 }
10836                 if (attname)                    /* just in case we don't find it */
10837                 {
10838                         const char *descr = comments->descr;
10839
10840                         resetPQExpBuffer(target);
10841                         appendPQExpBuffer(target, "COLUMN %s.",
10842                                                           fmtId(tyinfo->dobj.name));
10843                         appendPQExpBufferStr(target, fmtId(attname));
10844
10845                         resetPQExpBuffer(query);
10846                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
10847                         appendStringLiteralAH(query, descr, fout);
10848                         appendPQExpBufferStr(query, ";\n");
10849
10850                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
10851                                                  target->data,
10852                                                  tyinfo->dobj.namespace->dobj.name,
10853                                                  NULL, tyinfo->rolname,
10854                                                  false, "COMMENT", SECTION_NONE,
10855                                                  query->data, "", NULL,
10856                                                  &(tyinfo->dobj.dumpId), 1,
10857                                                  NULL, NULL);
10858                 }
10859
10860                 comments++;
10861                 ncomments--;
10862         }
10863
10864         PQclear(res);
10865         destroyPQExpBuffer(query);
10866         destroyPQExpBuffer(target);
10867 }
10868
10869 /*
10870  * dumpShellType
10871  *        writes out to fout the queries to create a shell type
10872  *
10873  * We dump a shell definition in advance of the I/O functions for the type.
10874  */
10875 static void
10876 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
10877 {
10878         DumpOptions *dopt = fout->dopt;
10879         PQExpBuffer q;
10880
10881         /* Skip if not to be dumped */
10882         if (!stinfo->dobj.dump || dopt->dataOnly)
10883                 return;
10884
10885         q = createPQExpBuffer();
10886
10887         /*
10888          * Note the lack of a DROP command for the shell type; any required DROP
10889          * is driven off the base type entry, instead.  This interacts with
10890          * _printTocEntry()'s use of the presence of a DROP command to decide
10891          * whether an entry needs an ALTER OWNER command.  We don't want to alter
10892          * the shell type's owner immediately on creation; that should happen only
10893          * after it's filled in, otherwise the backend complains.
10894          */
10895
10896         if (dopt->binary_upgrade)
10897                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
10898                                                                                                  stinfo->baseType->dobj.catId.oid);
10899
10900         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
10901                                           fmtId(stinfo->dobj.name));
10902
10903         if (stinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10904                 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
10905                                          stinfo->dobj.name,
10906                                          stinfo->dobj.namespace->dobj.name,
10907                                          NULL,
10908                                          stinfo->baseType->rolname, false,
10909                                          "SHELL TYPE", SECTION_PRE_DATA,
10910                                          q->data, "", NULL,
10911                                          NULL, 0,
10912                                          NULL, NULL);
10913
10914         destroyPQExpBuffer(q);
10915 }
10916
10917 /*
10918  * dumpProcLang
10919  *                writes out to fout the queries to recreate a user-defined
10920  *                procedural language
10921  */
10922 static void
10923 dumpProcLang(Archive *fout, ProcLangInfo *plang)
10924 {
10925         DumpOptions *dopt = fout->dopt;
10926         PQExpBuffer defqry;
10927         PQExpBuffer delqry;
10928         PQExpBuffer labelq;
10929         bool            useParams;
10930         char       *qlanname;
10931         char       *lanschema;
10932         FuncInfo   *funcInfo;
10933         FuncInfo   *inlineInfo = NULL;
10934         FuncInfo   *validatorInfo = NULL;
10935
10936         /* Skip if not to be dumped */
10937         if (!plang->dobj.dump || dopt->dataOnly)
10938                 return;
10939
10940         /*
10941          * Try to find the support function(s).  It is not an error if we don't
10942          * find them --- if the functions are in the pg_catalog schema, as is
10943          * standard in 8.1 and up, then we won't have loaded them. (In this case
10944          * we will emit a parameterless CREATE LANGUAGE command, which will
10945          * require PL template knowledge in the backend to reload.)
10946          */
10947
10948         funcInfo = findFuncByOid(plang->lanplcallfoid);
10949         if (funcInfo != NULL && !funcInfo->dobj.dump)
10950                 funcInfo = NULL;                /* treat not-dumped same as not-found */
10951
10952         if (OidIsValid(plang->laninline))
10953         {
10954                 inlineInfo = findFuncByOid(plang->laninline);
10955                 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
10956                         inlineInfo = NULL;
10957         }
10958
10959         if (OidIsValid(plang->lanvalidator))
10960         {
10961                 validatorInfo = findFuncByOid(plang->lanvalidator);
10962                 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
10963                         validatorInfo = NULL;
10964         }
10965
10966         /*
10967          * If the functions are dumpable then emit a traditional CREATE LANGUAGE
10968          * with parameters.  Otherwise, we'll write a parameterless command, which
10969          * will rely on data from pg_pltemplate.
10970          */
10971         useParams = (funcInfo != NULL &&
10972                                  (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
10973                                  (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
10974
10975         defqry = createPQExpBuffer();
10976         delqry = createPQExpBuffer();
10977         labelq = createPQExpBuffer();
10978
10979         qlanname = pg_strdup(fmtId(plang->dobj.name));
10980
10981         /*
10982          * If dumping a HANDLER clause, treat the language as being in the handler
10983          * function's schema; this avoids cluttering the HANDLER clause. Otherwise
10984          * it doesn't really have a schema.
10985          */
10986         if (useParams)
10987                 lanschema = funcInfo->dobj.namespace->dobj.name;
10988         else
10989                 lanschema = NULL;
10990
10991         appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
10992                                           qlanname);
10993
10994         if (useParams)
10995         {
10996                 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
10997                                                   plang->lanpltrusted ? "TRUSTED " : "",
10998                                                   qlanname);
10999                 appendPQExpBuffer(defqry, " HANDLER %s",
11000                                                   fmtId(funcInfo->dobj.name));
11001                 if (OidIsValid(plang->laninline))
11002                 {
11003                         appendPQExpBufferStr(defqry, " INLINE ");
11004                         /* Cope with possibility that inline is in different schema */
11005                         if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
11006                                 appendPQExpBuffer(defqry, "%s.",
11007                                                                   fmtId(inlineInfo->dobj.namespace->dobj.name));
11008                         appendPQExpBufferStr(defqry, fmtId(inlineInfo->dobj.name));
11009                 }
11010                 if (OidIsValid(plang->lanvalidator))
11011                 {
11012                         appendPQExpBufferStr(defqry, " VALIDATOR ");
11013                         /* Cope with possibility that validator is in different schema */
11014                         if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
11015                                 appendPQExpBuffer(defqry, "%s.",
11016                                                                   fmtId(validatorInfo->dobj.namespace->dobj.name));
11017                         appendPQExpBufferStr(defqry, fmtId(validatorInfo->dobj.name));
11018                 }
11019         }
11020         else
11021         {
11022                 /*
11023                  * If not dumping parameters, then use CREATE OR REPLACE so that the
11024                  * command will not fail if the language is preinstalled in the target
11025                  * database.  We restrict the use of REPLACE to this case so as to
11026                  * eliminate the risk of replacing a language with incompatible
11027                  * parameter settings: this command will only succeed at all if there
11028                  * is a pg_pltemplate entry, and if there is one, the existing entry
11029                  * must match it too.
11030                  */
11031                 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
11032                                                   qlanname);
11033         }
11034         appendPQExpBufferStr(defqry, ";\n");
11035
11036         appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
11037
11038         if (dopt->binary_upgrade)
11039                 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
11040
11041         if (plang->dobj.dump & DUMP_COMPONENT_DEFINITION)
11042                 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
11043                                          plang->dobj.name,
11044                                          lanschema, NULL, plang->lanowner,
11045                                          false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
11046                                          defqry->data, delqry->data, NULL,
11047                                          NULL, 0,
11048                                          NULL, NULL);
11049
11050         /* Dump Proc Lang Comments and Security Labels */
11051         if (plang->dobj.dump & DUMP_COMPONENT_COMMENT)
11052                 dumpComment(fout, labelq->data,
11053                                         lanschema, plang->lanowner,
11054                                         plang->dobj.catId, 0, plang->dobj.dumpId);
11055
11056         if (plang->dobj.dump & DUMP_COMPONENT_SECLABEL)
11057                 dumpSecLabel(fout, labelq->data,
11058                                          lanschema, plang->lanowner,
11059                                          plang->dobj.catId, 0, plang->dobj.dumpId);
11060
11061         if (plang->lanpltrusted && plang->dobj.dump & DUMP_COMPONENT_ACL)
11062                 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
11063                                 qlanname, NULL, plang->dobj.name,
11064                                 lanschema,
11065                                 plang->lanowner, plang->lanacl, plang->rlanacl,
11066                                 plang->initlanacl, plang->initrlanacl);
11067
11068         free(qlanname);
11069
11070         destroyPQExpBuffer(defqry);
11071         destroyPQExpBuffer(delqry);
11072         destroyPQExpBuffer(labelq);
11073 }
11074
11075 /*
11076  * format_function_arguments: generate function name and argument list
11077  *
11078  * This is used when we can rely on pg_get_function_arguments to format
11079  * the argument list.  Note, however, that pg_get_function_arguments
11080  * does not special-case zero-argument aggregates.
11081  */
11082 static char *
11083 format_function_arguments(FuncInfo *finfo, char *funcargs, bool is_agg)
11084 {
11085         PQExpBufferData fn;
11086
11087         initPQExpBuffer(&fn);
11088         appendPQExpBufferStr(&fn, fmtId(finfo->dobj.name));
11089         if (is_agg && finfo->nargs == 0)
11090                 appendPQExpBufferStr(&fn, "(*)");
11091         else
11092                 appendPQExpBuffer(&fn, "(%s)", funcargs);
11093         return fn.data;
11094 }
11095
11096 /*
11097  * format_function_arguments_old: generate function name and argument list
11098  *
11099  * The argument type names are qualified if needed.  The function name
11100  * is never qualified.
11101  *
11102  * This is used only with pre-8.4 servers, so we aren't expecting to see
11103  * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
11104  *
11105  * Any or all of allargtypes, argmodes, argnames may be NULL.
11106  */
11107 static char *
11108 format_function_arguments_old(Archive *fout,
11109                                                           FuncInfo *finfo, int nallargs,
11110                                                           char **allargtypes,
11111                                                           char **argmodes,
11112                                                           char **argnames)
11113 {
11114         PQExpBufferData fn;
11115         int                     j;
11116
11117         initPQExpBuffer(&fn);
11118         appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11119         for (j = 0; j < nallargs; j++)
11120         {
11121                 Oid                     typid;
11122                 char       *typname;
11123                 const char *argmode;
11124                 const char *argname;
11125
11126                 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
11127                 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
11128
11129                 if (argmodes)
11130                 {
11131                         switch (argmodes[j][0])
11132                         {
11133                                 case PROARGMODE_IN:
11134                                         argmode = "";
11135                                         break;
11136                                 case PROARGMODE_OUT:
11137                                         argmode = "OUT ";
11138                                         break;
11139                                 case PROARGMODE_INOUT:
11140                                         argmode = "INOUT ";
11141                                         break;
11142                                 default:
11143                                         write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
11144                                         argmode = "";
11145                                         break;
11146                         }
11147                 }
11148                 else
11149                         argmode = "";
11150
11151                 argname = argnames ? argnames[j] : (char *) NULL;
11152                 if (argname && argname[0] == '\0')
11153                         argname = NULL;
11154
11155                 appendPQExpBuffer(&fn, "%s%s%s%s%s",
11156                                                   (j > 0) ? ", " : "",
11157                                                   argmode,
11158                                                   argname ? fmtId(argname) : "",
11159                                                   argname ? " " : "",
11160                                                   typname);
11161                 free(typname);
11162         }
11163         appendPQExpBufferChar(&fn, ')');
11164         return fn.data;
11165 }
11166
11167 /*
11168  * format_function_signature: generate function name and argument list
11169  *
11170  * This is like format_function_arguments_old except that only a minimal
11171  * list of input argument types is generated; this is sufficient to
11172  * reference the function, but not to define it.
11173  *
11174  * If honor_quotes is false then the function name is never quoted.
11175  * This is appropriate for use in TOC tags, but not in SQL commands.
11176  */
11177 static char *
11178 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
11179 {
11180         PQExpBufferData fn;
11181         int                     j;
11182
11183         initPQExpBuffer(&fn);
11184         if (honor_quotes)
11185                 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
11186         else
11187                 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
11188         for (j = 0; j < finfo->nargs; j++)
11189         {
11190                 char       *typname;
11191
11192                 if (j > 0)
11193                         appendPQExpBufferStr(&fn, ", ");
11194
11195                 typname = getFormattedTypeName(fout, finfo->argtypes[j],
11196                                                                            zeroAsOpaque);
11197                 appendPQExpBufferStr(&fn, typname);
11198                 free(typname);
11199         }
11200         appendPQExpBufferChar(&fn, ')');
11201         return fn.data;
11202 }
11203
11204
11205 /*
11206  * dumpFunc:
11207  *        dump out one function
11208  */
11209 static void
11210 dumpFunc(Archive *fout, FuncInfo *finfo)
11211 {
11212         DumpOptions *dopt = fout->dopt;
11213         PQExpBuffer query;
11214         PQExpBuffer q;
11215         PQExpBuffer delqry;
11216         PQExpBuffer labelq;
11217         PQExpBuffer asPart;
11218         PGresult   *res;
11219         char       *funcsig;            /* identity signature */
11220         char       *funcfullsig = NULL; /* full signature */
11221         char       *funcsig_tag;
11222         char       *proretset;
11223         char       *prosrc;
11224         char       *probin;
11225         char       *funcargs;
11226         char       *funciargs;
11227         char       *funcresult;
11228         char       *proallargtypes;
11229         char       *proargmodes;
11230         char       *proargnames;
11231         char       *protrftypes;
11232         char       *proiswindow;
11233         char       *provolatile;
11234         char       *proisstrict;
11235         char       *prosecdef;
11236         char       *proleakproof;
11237         char       *proconfig;
11238         char       *procost;
11239         char       *prorows;
11240         char       *proparallel;
11241         char       *lanname;
11242         char       *rettypename;
11243         int                     nallargs;
11244         char      **allargtypes = NULL;
11245         char      **argmodes = NULL;
11246         char      **argnames = NULL;
11247         char      **configitems = NULL;
11248         int                     nconfigitems = 0;
11249         int                     i;
11250
11251         /* Skip if not to be dumped */
11252         if (!finfo->dobj.dump || dopt->dataOnly)
11253                 return;
11254
11255         query = createPQExpBuffer();
11256         q = createPQExpBuffer();
11257         delqry = createPQExpBuffer();
11258         labelq = createPQExpBuffer();
11259         asPart = createPQExpBuffer();
11260
11261         /* Set proper schema search path so type references list correctly */
11262         selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
11263
11264         /* Fetch function-specific details */
11265         if (fout->remoteVersion >= 90600)
11266         {
11267                 /*
11268                  * proparallel was added in 9.6
11269                  */
11270                 appendPQExpBuffer(query,
11271                                                   "SELECT proretset, prosrc, probin, "
11272                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11273                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11274                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11275                                                   "array_to_string(protrftypes, ' ') AS protrftypes, "
11276                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
11277                                                   "proleakproof, proconfig, procost, prorows, "
11278                                                   "proparallel, "
11279                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11280                                                   "FROM pg_catalog.pg_proc "
11281                                                   "WHERE oid = '%u'::pg_catalog.oid",
11282                                                   finfo->dobj.catId.oid);
11283         }
11284         else if (fout->remoteVersion >= 90500)
11285         {
11286                 /*
11287                  * protrftypes was added in 9.5
11288                  */
11289                 appendPQExpBuffer(query,
11290                                                   "SELECT proretset, prosrc, probin, "
11291                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11292                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11293                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11294                                                   "array_to_string(protrftypes, ' ') AS protrftypes, "
11295                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
11296                                                   "proleakproof, proconfig, procost, prorows, "
11297                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11298                                                   "FROM pg_catalog.pg_proc "
11299                                                   "WHERE oid = '%u'::pg_catalog.oid",
11300                                                   finfo->dobj.catId.oid);
11301         }
11302         else if (fout->remoteVersion >= 90200)
11303         {
11304                 /*
11305                  * proleakproof was added in 9.2
11306                  */
11307                 appendPQExpBuffer(query,
11308                                                   "SELECT proretset, prosrc, probin, "
11309                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11310                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11311                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11312                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
11313                                                   "proleakproof, proconfig, procost, prorows, "
11314                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11315                                                   "FROM pg_catalog.pg_proc "
11316                                                   "WHERE oid = '%u'::pg_catalog.oid",
11317                                                   finfo->dobj.catId.oid);
11318         }
11319         else if (fout->remoteVersion >= 80400)
11320         {
11321                 /*
11322                  * In 8.4 and up we rely on pg_get_function_arguments and
11323                  * pg_get_function_result instead of examining proallargtypes etc.
11324                  */
11325                 appendPQExpBuffer(query,
11326                                                   "SELECT proretset, prosrc, probin, "
11327                                                   "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
11328                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
11329                                                   "pg_catalog.pg_get_function_result(oid) AS funcresult, "
11330                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
11331                                                   "false AS proleakproof, "
11332                                                   " proconfig, procost, prorows, "
11333                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11334                                                   "FROM pg_catalog.pg_proc "
11335                                                   "WHERE oid = '%u'::pg_catalog.oid",
11336                                                   finfo->dobj.catId.oid);
11337         }
11338         else if (fout->remoteVersion >= 80300)
11339         {
11340                 appendPQExpBuffer(query,
11341                                                   "SELECT proretset, prosrc, probin, "
11342                                                   "proallargtypes, proargmodes, proargnames, "
11343                                                   "false AS proiswindow, "
11344                                                   "provolatile, proisstrict, prosecdef, "
11345                                                   "false AS proleakproof, "
11346                                                   "proconfig, procost, prorows, "
11347                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11348                                                   "FROM pg_catalog.pg_proc "
11349                                                   "WHERE oid = '%u'::pg_catalog.oid",
11350                                                   finfo->dobj.catId.oid);
11351         }
11352         else if (fout->remoteVersion >= 80100)
11353         {
11354                 appendPQExpBuffer(query,
11355                                                   "SELECT proretset, prosrc, probin, "
11356                                                   "proallargtypes, proargmodes, proargnames, "
11357                                                   "false AS proiswindow, "
11358                                                   "provolatile, proisstrict, prosecdef, "
11359                                                   "false AS proleakproof, "
11360                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
11361                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11362                                                   "FROM pg_catalog.pg_proc "
11363                                                   "WHERE oid = '%u'::pg_catalog.oid",
11364                                                   finfo->dobj.catId.oid);
11365         }
11366         else
11367         {
11368                 appendPQExpBuffer(query,
11369                                                   "SELECT proretset, prosrc, probin, "
11370                                                   "null AS proallargtypes, "
11371                                                   "null AS proargmodes, "
11372                                                   "proargnames, "
11373                                                   "false AS proiswindow, "
11374                                                   "provolatile, proisstrict, prosecdef, "
11375                                                   "false AS proleakproof, "
11376                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
11377                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
11378                                                   "FROM pg_catalog.pg_proc "
11379                                                   "WHERE oid = '%u'::pg_catalog.oid",
11380                                                   finfo->dobj.catId.oid);
11381         }
11382
11383         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11384
11385         proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
11386         prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
11387         probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
11388         if (fout->remoteVersion >= 80400)
11389         {
11390                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
11391                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
11392                 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
11393                 proallargtypes = proargmodes = proargnames = NULL;
11394         }
11395         else
11396         {
11397                 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
11398                 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
11399                 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
11400                 funcargs = funciargs = funcresult = NULL;
11401         }
11402         if (PQfnumber(res, "protrftypes") != -1)
11403                 protrftypes = PQgetvalue(res, 0, PQfnumber(res, "protrftypes"));
11404         else
11405                 protrftypes = NULL;
11406         proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
11407         provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
11408         proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
11409         prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
11410         proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
11411         proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
11412         procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
11413         prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
11414
11415         if (PQfnumber(res, "proparallel") != -1)
11416                 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
11417         else
11418                 proparallel = NULL;
11419
11420         lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
11421
11422         /*
11423          * See backend/commands/functioncmds.c for details of how the 'AS' clause
11424          * is used.  In 8.4 and up, an unused probin is NULL (here ""); previous
11425          * versions would set it to "-".  There are no known cases in which prosrc
11426          * is unused, so the tests below for "-" are probably useless.
11427          */
11428         if (probin[0] != '\0' && strcmp(probin, "-") != 0)
11429         {
11430                 appendPQExpBufferStr(asPart, "AS ");
11431                 appendStringLiteralAH(asPart, probin, fout);
11432                 if (strcmp(prosrc, "-") != 0)
11433                 {
11434                         appendPQExpBufferStr(asPart, ", ");
11435
11436                         /*
11437                          * where we have bin, use dollar quoting if allowed and src
11438                          * contains quote or backslash; else use regular quoting.
11439                          */
11440                         if (dopt->disable_dollar_quoting ||
11441                                 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
11442                                 appendStringLiteralAH(asPart, prosrc, fout);
11443                         else
11444                                 appendStringLiteralDQ(asPart, prosrc, NULL);
11445                 }
11446         }
11447         else
11448         {
11449                 if (strcmp(prosrc, "-") != 0)
11450                 {
11451                         appendPQExpBufferStr(asPart, "AS ");
11452                         /* with no bin, dollar quote src unconditionally if allowed */
11453                         if (dopt->disable_dollar_quoting)
11454                                 appendStringLiteralAH(asPart, prosrc, fout);
11455                         else
11456                                 appendStringLiteralDQ(asPart, prosrc, NULL);
11457                 }
11458         }
11459
11460         nallargs = finfo->nargs;        /* unless we learn different from allargs */
11461
11462         if (proallargtypes && *proallargtypes)
11463         {
11464                 int                     nitems = 0;
11465
11466                 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
11467                         nitems < finfo->nargs)
11468                 {
11469                         write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
11470                         if (allargtypes)
11471                                 free(allargtypes);
11472                         allargtypes = NULL;
11473                 }
11474                 else
11475                         nallargs = nitems;
11476         }
11477
11478         if (proargmodes && *proargmodes)
11479         {
11480                 int                     nitems = 0;
11481
11482                 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
11483                         nitems != nallargs)
11484                 {
11485                         write_msg(NULL, "WARNING: could not parse proargmodes array\n");
11486                         if (argmodes)
11487                                 free(argmodes);
11488                         argmodes = NULL;
11489                 }
11490         }
11491
11492         if (proargnames && *proargnames)
11493         {
11494                 int                     nitems = 0;
11495
11496                 if (!parsePGArray(proargnames, &argnames, &nitems) ||
11497                         nitems != nallargs)
11498                 {
11499                         write_msg(NULL, "WARNING: could not parse proargnames array\n");
11500                         if (argnames)
11501                                 free(argnames);
11502                         argnames = NULL;
11503                 }
11504         }
11505
11506         if (proconfig && *proconfig)
11507         {
11508                 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
11509                 {
11510                         write_msg(NULL, "WARNING: could not parse proconfig array\n");
11511                         if (configitems)
11512                                 free(configitems);
11513                         configitems = NULL;
11514                         nconfigitems = 0;
11515                 }
11516         }
11517
11518         if (funcargs)
11519         {
11520                 /* 8.4 or later; we rely on server-side code for most of the work */
11521                 funcfullsig = format_function_arguments(finfo, funcargs, false);
11522                 funcsig = format_function_arguments(finfo, funciargs, false);
11523         }
11524         else
11525                 /* pre-8.4, do it ourselves */
11526                 funcsig = format_function_arguments_old(fout,
11527                                                                                                 finfo, nallargs, allargtypes,
11528                                                                                                 argmodes, argnames);
11529
11530         funcsig_tag = format_function_signature(fout, finfo, false);
11531
11532         /*
11533          * DROP must be fully qualified in case same name appears in pg_catalog
11534          */
11535         appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
11536                                           fmtId(finfo->dobj.namespace->dobj.name),
11537                                           funcsig);
11538
11539         appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig ? funcfullsig :
11540                                           funcsig);
11541         if (funcresult)
11542                 appendPQExpBuffer(q, "RETURNS %s", funcresult);
11543         else
11544         {
11545                 rettypename = getFormattedTypeName(fout, finfo->prorettype,
11546                                                                                    zeroAsOpaque);
11547                 appendPQExpBuffer(q, "RETURNS %s%s",
11548                                                   (proretset[0] == 't') ? "SETOF " : "",
11549                                                   rettypename);
11550                 free(rettypename);
11551         }
11552
11553         appendPQExpBuffer(q, "\n    LANGUAGE %s", fmtId(lanname));
11554
11555         if (protrftypes != NULL && strcmp(protrftypes, "") != 0)
11556         {
11557                 Oid                *typeids = palloc(FUNC_MAX_ARGS * sizeof(Oid));
11558                 int                     i;
11559
11560                 appendPQExpBufferStr(q, " TRANSFORM ");
11561                 parseOidArray(protrftypes, typeids, FUNC_MAX_ARGS);
11562                 for (i = 0; typeids[i]; i++)
11563                 {
11564                         if (i != 0)
11565                                 appendPQExpBufferStr(q, ", ");
11566                         appendPQExpBuffer(q, "FOR TYPE %s",
11567                                                           getFormattedTypeName(fout, typeids[i], zeroAsNone));
11568                 }
11569         }
11570
11571         if (proiswindow[0] == 't')
11572                 appendPQExpBufferStr(q, " WINDOW");
11573
11574         if (provolatile[0] != PROVOLATILE_VOLATILE)
11575         {
11576                 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
11577                         appendPQExpBufferStr(q, " IMMUTABLE");
11578                 else if (provolatile[0] == PROVOLATILE_STABLE)
11579                         appendPQExpBufferStr(q, " STABLE");
11580                 else if (provolatile[0] != PROVOLATILE_VOLATILE)
11581                         exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
11582                                                   finfo->dobj.name);
11583         }
11584
11585         if (proisstrict[0] == 't')
11586                 appendPQExpBufferStr(q, " STRICT");
11587
11588         if (prosecdef[0] == 't')
11589                 appendPQExpBufferStr(q, " SECURITY DEFINER");
11590
11591         if (proleakproof[0] == 't')
11592                 appendPQExpBufferStr(q, " LEAKPROOF");
11593
11594         /*
11595          * COST and ROWS are emitted only if present and not default, so as not to
11596          * break backwards-compatibility of the dump without need.  Keep this code
11597          * in sync with the defaults in functioncmds.c.
11598          */
11599         if (strcmp(procost, "0") != 0)
11600         {
11601                 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
11602                 {
11603                         /* default cost is 1 */
11604                         if (strcmp(procost, "1") != 0)
11605                                 appendPQExpBuffer(q, " COST %s", procost);
11606                 }
11607                 else
11608                 {
11609                         /* default cost is 100 */
11610                         if (strcmp(procost, "100") != 0)
11611                                 appendPQExpBuffer(q, " COST %s", procost);
11612                 }
11613         }
11614         if (proretset[0] == 't' &&
11615                 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
11616                 appendPQExpBuffer(q, " ROWS %s", prorows);
11617
11618         if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
11619         {
11620                 if (proparallel[0] == PROPARALLEL_SAFE)
11621                         appendPQExpBufferStr(q, " PARALLEL SAFE");
11622                 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
11623                         appendPQExpBufferStr(q, " PARALLEL RESTRICTED");
11624                 else if (proparallel[0] != PROPARALLEL_UNSAFE)
11625                         exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
11626                                                   finfo->dobj.name);
11627         }
11628
11629         for (i = 0; i < nconfigitems; i++)
11630         {
11631                 /* we feel free to scribble on configitems[] here */
11632                 char       *configitem = configitems[i];
11633                 char       *pos;
11634
11635                 pos = strchr(configitem, '=');
11636                 if (pos == NULL)
11637                         continue;
11638                 *pos++ = '\0';
11639                 appendPQExpBuffer(q, "\n    SET %s TO ", fmtId(configitem));
11640
11641                 /*
11642                  * Some GUC variable names are 'LIST' type and hence must not be
11643                  * quoted.
11644                  */
11645                 if (pg_strcasecmp(configitem, "DateStyle") == 0
11646                         || pg_strcasecmp(configitem, "search_path") == 0)
11647                         appendPQExpBufferStr(q, pos);
11648                 else
11649                         appendStringLiteralAH(q, pos, fout);
11650         }
11651
11652         appendPQExpBuffer(q, "\n    %s;\n", asPart->data);
11653
11654         appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
11655
11656         if (dopt->binary_upgrade)
11657                 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
11658
11659         if (finfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11660                 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
11661                                          funcsig_tag,
11662                                          finfo->dobj.namespace->dobj.name,
11663                                          NULL,
11664                                          finfo->rolname, false,
11665                                          "FUNCTION", SECTION_PRE_DATA,
11666                                          q->data, delqry->data, NULL,
11667                                          NULL, 0,
11668                                          NULL, NULL);
11669
11670         /* Dump Function Comments and Security Labels */
11671         if (finfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11672                 dumpComment(fout, labelq->data,
11673                                         finfo->dobj.namespace->dobj.name, finfo->rolname,
11674                                         finfo->dobj.catId, 0, finfo->dobj.dumpId);
11675
11676         if (finfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11677                 dumpSecLabel(fout, labelq->data,
11678                                          finfo->dobj.namespace->dobj.name, finfo->rolname,
11679                                          finfo->dobj.catId, 0, finfo->dobj.dumpId);
11680
11681         if (finfo->dobj.dump & DUMP_COMPONENT_ACL)
11682                 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
11683                                 funcsig, NULL, funcsig_tag,
11684                                 finfo->dobj.namespace->dobj.name,
11685                                 finfo->rolname, finfo->proacl, finfo->rproacl,
11686                                 finfo->initproacl, finfo->initrproacl);
11687
11688         PQclear(res);
11689
11690         destroyPQExpBuffer(query);
11691         destroyPQExpBuffer(q);
11692         destroyPQExpBuffer(delqry);
11693         destroyPQExpBuffer(labelq);
11694         destroyPQExpBuffer(asPart);
11695         free(funcsig);
11696         if (funcfullsig)
11697                 free(funcfullsig);
11698         free(funcsig_tag);
11699         if (allargtypes)
11700                 free(allargtypes);
11701         if (argmodes)
11702                 free(argmodes);
11703         if (argnames)
11704                 free(argnames);
11705         if (configitems)
11706                 free(configitems);
11707 }
11708
11709
11710 /*
11711  * Dump a user-defined cast
11712  */
11713 static void
11714 dumpCast(Archive *fout, CastInfo *cast)
11715 {
11716         DumpOptions *dopt = fout->dopt;
11717         PQExpBuffer defqry;
11718         PQExpBuffer delqry;
11719         PQExpBuffer labelq;
11720         FuncInfo   *funcInfo = NULL;
11721         char       *sourceType;
11722         char       *targetType;
11723
11724         /* Skip if not to be dumped */
11725         if (!cast->dobj.dump || dopt->dataOnly)
11726                 return;
11727
11728         /* Cannot dump if we don't have the cast function's info */
11729         if (OidIsValid(cast->castfunc))
11730         {
11731                 funcInfo = findFuncByOid(cast->castfunc);
11732                 if (funcInfo == NULL)
11733                         exit_horribly(NULL, "could not find function definition for function with OID %u\n",
11734                                                   cast->castfunc);
11735         }
11736
11737         /*
11738          * Make sure we are in proper schema (needed for getFormattedTypeName).
11739          * Casts don't have a schema of their own, so use pg_catalog.
11740          */
11741         selectSourceSchema(fout, "pg_catalog");
11742
11743         defqry = createPQExpBuffer();
11744         delqry = createPQExpBuffer();
11745         labelq = createPQExpBuffer();
11746
11747         sourceType = getFormattedTypeName(fout, cast->castsource, zeroAsNone);
11748         targetType = getFormattedTypeName(fout, cast->casttarget, zeroAsNone);
11749         appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
11750                                           sourceType, targetType);
11751
11752         appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
11753                                           sourceType, targetType);
11754
11755         switch (cast->castmethod)
11756         {
11757                 case COERCION_METHOD_BINARY:
11758                         appendPQExpBufferStr(defqry, "WITHOUT FUNCTION");
11759                         break;
11760                 case COERCION_METHOD_INOUT:
11761                         appendPQExpBufferStr(defqry, "WITH INOUT");
11762                         break;
11763                 case COERCION_METHOD_FUNCTION:
11764                         if (funcInfo)
11765                         {
11766                                 char       *fsig = format_function_signature(fout, funcInfo, true);
11767
11768                                 /*
11769                                  * Always qualify the function name, in case it is not in
11770                                  * pg_catalog schema (format_function_signature won't qualify
11771                                  * it).
11772                                  */
11773                                 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
11774                                                                   fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
11775                                 free(fsig);
11776                         }
11777                         else
11778                                 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
11779                         break;
11780                 default:
11781                         write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
11782         }
11783
11784         if (cast->castcontext == 'a')
11785                 appendPQExpBufferStr(defqry, " AS ASSIGNMENT");
11786         else if (cast->castcontext == 'i')
11787                 appendPQExpBufferStr(defqry, " AS IMPLICIT");
11788         appendPQExpBufferStr(defqry, ";\n");
11789
11790         appendPQExpBuffer(labelq, "CAST (%s AS %s)",
11791                                           sourceType, targetType);
11792
11793         if (dopt->binary_upgrade)
11794                 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
11795
11796         if (cast->dobj.dump & DUMP_COMPONENT_DEFINITION)
11797                 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
11798                                          labelq->data,
11799                                          "pg_catalog", NULL, "",
11800                                          false, "CAST", SECTION_PRE_DATA,
11801                                          defqry->data, delqry->data, NULL,
11802                                          NULL, 0,
11803                                          NULL, NULL);
11804
11805         /* Dump Cast Comments */
11806         if (cast->dobj.dump & DUMP_COMPONENT_COMMENT)
11807                 dumpComment(fout, labelq->data,
11808                                         "pg_catalog", "",
11809                                         cast->dobj.catId, 0, cast->dobj.dumpId);
11810
11811         free(sourceType);
11812         free(targetType);
11813
11814         destroyPQExpBuffer(defqry);
11815         destroyPQExpBuffer(delqry);
11816         destroyPQExpBuffer(labelq);
11817 }
11818
11819 /*
11820  * Dump a transform
11821  */
11822 static void
11823 dumpTransform(Archive *fout, TransformInfo *transform)
11824 {
11825         DumpOptions *dopt = fout->dopt;
11826         PQExpBuffer defqry;
11827         PQExpBuffer delqry;
11828         PQExpBuffer labelq;
11829         FuncInfo   *fromsqlFuncInfo = NULL;
11830         FuncInfo   *tosqlFuncInfo = NULL;
11831         char       *lanname;
11832         char       *transformType;
11833
11834         /* Skip if not to be dumped */
11835         if (!transform->dobj.dump || dopt->dataOnly)
11836                 return;
11837
11838         /* Cannot dump if we don't have the transform functions' info */
11839         if (OidIsValid(transform->trffromsql))
11840         {
11841                 fromsqlFuncInfo = findFuncByOid(transform->trffromsql);
11842                 if (fromsqlFuncInfo == NULL)
11843                         exit_horribly(NULL, "could not find function definition for function with OID %u\n",
11844                                                   transform->trffromsql);
11845         }
11846         if (OidIsValid(transform->trftosql))
11847         {
11848                 tosqlFuncInfo = findFuncByOid(transform->trftosql);
11849                 if (tosqlFuncInfo == NULL)
11850                         exit_horribly(NULL, "could not find function definition for function with OID %u\n",
11851                                                   transform->trftosql);
11852         }
11853
11854         /* Make sure we are in proper schema (needed for getFormattedTypeName) */
11855         selectSourceSchema(fout, "pg_catalog");
11856
11857         defqry = createPQExpBuffer();
11858         delqry = createPQExpBuffer();
11859         labelq = createPQExpBuffer();
11860
11861         lanname = get_language_name(fout, transform->trflang);
11862         transformType = getFormattedTypeName(fout, transform->trftype, zeroAsNone);
11863
11864         appendPQExpBuffer(delqry, "DROP TRANSFORM FOR %s LANGUAGE %s;\n",
11865                                           transformType, lanname);
11866
11867         appendPQExpBuffer(defqry, "CREATE TRANSFORM FOR %s LANGUAGE %s (",
11868                                           transformType, lanname);
11869
11870         if (!transform->trffromsql && !transform->trftosql)
11871                 write_msg(NULL, "WARNING: bogus transform definition, at least one of trffromsql and trftosql should be nonzero\n");
11872
11873         if (transform->trffromsql)
11874         {
11875                 if (fromsqlFuncInfo)
11876                 {
11877                         char       *fsig = format_function_signature(fout, fromsqlFuncInfo, true);
11878
11879                         /*
11880                          * Always qualify the function name, in case it is not in
11881                          * pg_catalog schema (format_function_signature won't qualify it).
11882                          */
11883                         appendPQExpBuffer(defqry, "FROM SQL WITH FUNCTION %s.%s",
11884                                                           fmtId(fromsqlFuncInfo->dobj.namespace->dobj.name), fsig);
11885                         free(fsig);
11886                 }
11887                 else
11888                         write_msg(NULL, "WARNING: bogus value in pg_transform.trffromsql field\n");
11889         }
11890
11891         if (transform->trftosql)
11892         {
11893                 if (transform->trffromsql)
11894                         appendPQExpBuffer(defqry, ", ");
11895
11896                 if (tosqlFuncInfo)
11897                 {
11898                         char       *fsig = format_function_signature(fout, tosqlFuncInfo, true);
11899
11900                         /*
11901                          * Always qualify the function name, in case it is not in
11902                          * pg_catalog schema (format_function_signature won't qualify it).
11903                          */
11904                         appendPQExpBuffer(defqry, "TO SQL WITH FUNCTION %s.%s",
11905                                                           fmtId(tosqlFuncInfo->dobj.namespace->dobj.name), fsig);
11906                         free(fsig);
11907                 }
11908                 else
11909                         write_msg(NULL, "WARNING: bogus value in pg_transform.trftosql field\n");
11910         }
11911
11912         appendPQExpBuffer(defqry, ");\n");
11913
11914         appendPQExpBuffer(labelq, "TRANSFORM FOR %s LANGUAGE %s",
11915                                           transformType, lanname);
11916
11917         if (dopt->binary_upgrade)
11918                 binary_upgrade_extension_member(defqry, &transform->dobj, labelq->data);
11919
11920         if (transform->dobj.dump & DUMP_COMPONENT_DEFINITION)
11921                 ArchiveEntry(fout, transform->dobj.catId, transform->dobj.dumpId,
11922                                          labelq->data,
11923                                          "pg_catalog", NULL, "",
11924                                          false, "TRANSFORM", SECTION_PRE_DATA,
11925                                          defqry->data, delqry->data, NULL,
11926                                          transform->dobj.dependencies, transform->dobj.nDeps,
11927                                          NULL, NULL);
11928
11929         /* Dump Transform Comments */
11930         if (transform->dobj.dump & DUMP_COMPONENT_COMMENT)
11931                 dumpComment(fout, labelq->data,
11932                                         "pg_catalog", "",
11933                                         transform->dobj.catId, 0, transform->dobj.dumpId);
11934
11935         free(lanname);
11936         free(transformType);
11937         destroyPQExpBuffer(defqry);
11938         destroyPQExpBuffer(delqry);
11939         destroyPQExpBuffer(labelq);
11940 }
11941
11942
11943 /*
11944  * dumpOpr
11945  *        write out a single operator definition
11946  */
11947 static void
11948 dumpOpr(Archive *fout, OprInfo *oprinfo)
11949 {
11950         DumpOptions *dopt = fout->dopt;
11951         PQExpBuffer query;
11952         PQExpBuffer q;
11953         PQExpBuffer delq;
11954         PQExpBuffer labelq;
11955         PQExpBuffer oprid;
11956         PQExpBuffer details;
11957         PGresult   *res;
11958         int                     i_oprkind;
11959         int                     i_oprcode;
11960         int                     i_oprleft;
11961         int                     i_oprright;
11962         int                     i_oprcom;
11963         int                     i_oprnegate;
11964         int                     i_oprrest;
11965         int                     i_oprjoin;
11966         int                     i_oprcanmerge;
11967         int                     i_oprcanhash;
11968         char       *oprkind;
11969         char       *oprcode;
11970         char       *oprleft;
11971         char       *oprright;
11972         char       *oprcom;
11973         char       *oprnegate;
11974         char       *oprrest;
11975         char       *oprjoin;
11976         char       *oprcanmerge;
11977         char       *oprcanhash;
11978         char       *oprregproc;
11979         char       *oprref;
11980
11981         /* Skip if not to be dumped */
11982         if (!oprinfo->dobj.dump || dopt->dataOnly)
11983                 return;
11984
11985         /*
11986          * some operators are invalid because they were the result of user
11987          * defining operators before commutators exist
11988          */
11989         if (!OidIsValid(oprinfo->oprcode))
11990                 return;
11991
11992         query = createPQExpBuffer();
11993         q = createPQExpBuffer();
11994         delq = createPQExpBuffer();
11995         labelq = createPQExpBuffer();
11996         oprid = createPQExpBuffer();
11997         details = createPQExpBuffer();
11998
11999         /* Make sure we are in proper schema so regoperator works correctly */
12000         selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
12001
12002         if (fout->remoteVersion >= 80300)
12003         {
12004                 appendPQExpBuffer(query, "SELECT oprkind, "
12005                                                   "oprcode::pg_catalog.regprocedure, "
12006                                                   "oprleft::pg_catalog.regtype, "
12007                                                   "oprright::pg_catalog.regtype, "
12008                                                   "oprcom::pg_catalog.regoperator, "
12009                                                   "oprnegate::pg_catalog.regoperator, "
12010                                                   "oprrest::pg_catalog.regprocedure, "
12011                                                   "oprjoin::pg_catalog.regprocedure, "
12012                                                   "oprcanmerge, oprcanhash "
12013                                                   "FROM pg_catalog.pg_operator "
12014                                                   "WHERE oid = '%u'::pg_catalog.oid",
12015                                                   oprinfo->dobj.catId.oid);
12016         }
12017         else
12018         {
12019                 appendPQExpBuffer(query, "SELECT oprkind, "
12020                                                   "oprcode::pg_catalog.regprocedure, "
12021                                                   "oprleft::pg_catalog.regtype, "
12022                                                   "oprright::pg_catalog.regtype, "
12023                                                   "oprcom::pg_catalog.regoperator, "
12024                                                   "oprnegate::pg_catalog.regoperator, "
12025                                                   "oprrest::pg_catalog.regprocedure, "
12026                                                   "oprjoin::pg_catalog.regprocedure, "
12027                                                   "(oprlsortop != 0) AS oprcanmerge, "
12028                                                   "oprcanhash "
12029                                                   "FROM pg_catalog.pg_operator "
12030                                                   "WHERE oid = '%u'::pg_catalog.oid",
12031                                                   oprinfo->dobj.catId.oid);
12032         }
12033
12034         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12035
12036         i_oprkind = PQfnumber(res, "oprkind");
12037         i_oprcode = PQfnumber(res, "oprcode");
12038         i_oprleft = PQfnumber(res, "oprleft");
12039         i_oprright = PQfnumber(res, "oprright");
12040         i_oprcom = PQfnumber(res, "oprcom");
12041         i_oprnegate = PQfnumber(res, "oprnegate");
12042         i_oprrest = PQfnumber(res, "oprrest");
12043         i_oprjoin = PQfnumber(res, "oprjoin");
12044         i_oprcanmerge = PQfnumber(res, "oprcanmerge");
12045         i_oprcanhash = PQfnumber(res, "oprcanhash");
12046
12047         oprkind = PQgetvalue(res, 0, i_oprkind);
12048         oprcode = PQgetvalue(res, 0, i_oprcode);
12049         oprleft = PQgetvalue(res, 0, i_oprleft);
12050         oprright = PQgetvalue(res, 0, i_oprright);
12051         oprcom = PQgetvalue(res, 0, i_oprcom);
12052         oprnegate = PQgetvalue(res, 0, i_oprnegate);
12053         oprrest = PQgetvalue(res, 0, i_oprrest);
12054         oprjoin = PQgetvalue(res, 0, i_oprjoin);
12055         oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
12056         oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
12057
12058         oprregproc = convertRegProcReference(fout, oprcode);
12059         if (oprregproc)
12060         {
12061                 appendPQExpBuffer(details, "    PROCEDURE = %s", oprregproc);
12062                 free(oprregproc);
12063         }
12064
12065         appendPQExpBuffer(oprid, "%s (",
12066                                           oprinfo->dobj.name);
12067
12068         /*
12069          * right unary means there's a left arg and left unary means there's a
12070          * right arg
12071          */
12072         if (strcmp(oprkind, "r") == 0 ||
12073                 strcmp(oprkind, "b") == 0)
12074         {
12075                 appendPQExpBuffer(details, ",\n    LEFTARG = %s", oprleft);
12076                 appendPQExpBufferStr(oprid, oprleft);
12077         }
12078         else
12079                 appendPQExpBufferStr(oprid, "NONE");
12080
12081         if (strcmp(oprkind, "l") == 0 ||
12082                 strcmp(oprkind, "b") == 0)
12083         {
12084                 appendPQExpBuffer(details, ",\n    RIGHTARG = %s", oprright);
12085                 appendPQExpBuffer(oprid, ", %s)", oprright);
12086         }
12087         else
12088                 appendPQExpBufferStr(oprid, ", NONE)");
12089
12090         oprref = convertOperatorReference(fout, oprcom);
12091         if (oprref)
12092         {
12093                 appendPQExpBuffer(details, ",\n    COMMUTATOR = %s", oprref);
12094                 free(oprref);
12095         }
12096
12097         oprref = convertOperatorReference(fout, oprnegate);
12098         if (oprref)
12099         {
12100                 appendPQExpBuffer(details, ",\n    NEGATOR = %s", oprref);
12101                 free(oprref);
12102         }
12103
12104         if (strcmp(oprcanmerge, "t") == 0)
12105                 appendPQExpBufferStr(details, ",\n    MERGES");
12106
12107         if (strcmp(oprcanhash, "t") == 0)
12108                 appendPQExpBufferStr(details, ",\n    HASHES");
12109
12110         oprregproc = convertRegProcReference(fout, oprrest);
12111         if (oprregproc)
12112         {
12113                 appendPQExpBuffer(details, ",\n    RESTRICT = %s", oprregproc);
12114                 free(oprregproc);
12115         }
12116
12117         oprregproc = convertRegProcReference(fout, oprjoin);
12118         if (oprregproc)
12119         {
12120                 appendPQExpBuffer(details, ",\n    JOIN = %s", oprregproc);
12121                 free(oprregproc);
12122         }
12123
12124         /*
12125          * DROP must be fully qualified in case same name appears in pg_catalog
12126          */
12127         appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
12128                                           fmtId(oprinfo->dobj.namespace->dobj.name),
12129                                           oprid->data);
12130
12131         appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
12132                                           oprinfo->dobj.name, details->data);
12133
12134         appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
12135
12136         if (dopt->binary_upgrade)
12137                 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
12138
12139         if (oprinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12140                 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
12141                                          oprinfo->dobj.name,
12142                                          oprinfo->dobj.namespace->dobj.name,
12143                                          NULL,
12144                                          oprinfo->rolname,
12145                                          false, "OPERATOR", SECTION_PRE_DATA,
12146                                          q->data, delq->data, NULL,
12147                                          NULL, 0,
12148                                          NULL, NULL);
12149
12150         /* Dump Operator Comments */
12151         if (oprinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12152                 dumpComment(fout, labelq->data,
12153                                         oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
12154                                         oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
12155
12156         PQclear(res);
12157
12158         destroyPQExpBuffer(query);
12159         destroyPQExpBuffer(q);
12160         destroyPQExpBuffer(delq);
12161         destroyPQExpBuffer(labelq);
12162         destroyPQExpBuffer(oprid);
12163         destroyPQExpBuffer(details);
12164 }
12165
12166 /*
12167  * Convert a function reference obtained from pg_operator
12168  *
12169  * Returns allocated string of what to print, or NULL if function references
12170  * is InvalidOid. Returned string is expected to be free'd by the caller.
12171  *
12172  * The input is a REGPROCEDURE display; we have to strip the argument-types
12173  * part.
12174  */
12175 static char *
12176 convertRegProcReference(Archive *fout, const char *proc)
12177 {
12178         char       *name;
12179         char       *paren;
12180         bool            inquote;
12181
12182         /* In all cases "-" means a null reference */
12183         if (strcmp(proc, "-") == 0)
12184                 return NULL;
12185
12186         name = pg_strdup(proc);
12187         /* find non-double-quoted left paren */
12188         inquote = false;
12189         for (paren = name; *paren; paren++)
12190         {
12191                 if (*paren == '(' && !inquote)
12192                 {
12193                         *paren = '\0';
12194                         break;
12195                 }
12196                 if (*paren == '"')
12197                         inquote = !inquote;
12198         }
12199         return name;
12200 }
12201
12202 /*
12203  * Convert an operator cross-reference obtained from pg_operator
12204  *
12205  * Returns an allocated string of what to print, or NULL to print nothing.
12206  * Caller is responsible for free'ing result string.
12207  *
12208  * The input is a REGOPERATOR display; we have to strip the argument-types
12209  * part, and add OPERATOR() decoration if the name is schema-qualified.
12210  */
12211 static char *
12212 convertOperatorReference(Archive *fout, const char *opr)
12213 {
12214         char       *name;
12215         char       *oname;
12216         char       *ptr;
12217         bool            inquote;
12218         bool            sawdot;
12219
12220         /* In all cases "0" means a null reference */
12221         if (strcmp(opr, "0") == 0)
12222                 return NULL;
12223
12224         name = pg_strdup(opr);
12225         /* find non-double-quoted left paren, and check for non-quoted dot */
12226         inquote = false;
12227         sawdot = false;
12228         for (ptr = name; *ptr; ptr++)
12229         {
12230                 if (*ptr == '"')
12231                         inquote = !inquote;
12232                 else if (*ptr == '.' && !inquote)
12233                         sawdot = true;
12234                 else if (*ptr == '(' && !inquote)
12235                 {
12236                         *ptr = '\0';
12237                         break;
12238                 }
12239         }
12240         /* If not schema-qualified, don't need to add OPERATOR() */
12241         if (!sawdot)
12242                 return name;
12243         oname = psprintf("OPERATOR(%s)", name);
12244         free(name);
12245         return oname;
12246 }
12247
12248 /*
12249  * Convert a function OID obtained from pg_ts_parser or pg_ts_template
12250  *
12251  * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
12252  * argument lists of these functions are predetermined.  Note that the
12253  * caller should ensure we are in the proper schema, because the results
12254  * are search path dependent!
12255  */
12256 static char *
12257 convertTSFunction(Archive *fout, Oid funcOid)
12258 {
12259         char       *result;
12260         char            query[128];
12261         PGresult   *res;
12262
12263         snprintf(query, sizeof(query),
12264                          "SELECT '%u'::pg_catalog.regproc", funcOid);
12265         res = ExecuteSqlQueryForSingleRow(fout, query);
12266
12267         result = pg_strdup(PQgetvalue(res, 0, 0));
12268
12269         PQclear(res);
12270
12271         return result;
12272 }
12273
12274 /*
12275  * dumpAccessMethod
12276  *        write out a single access method definition
12277  */
12278 static void
12279 dumpAccessMethod(Archive *fout, AccessMethodInfo *aminfo)
12280 {
12281         DumpOptions *dopt = fout->dopt;
12282         PQExpBuffer q;
12283         PQExpBuffer delq;
12284         PQExpBuffer labelq;
12285         char       *qamname;
12286
12287         /* Skip if not to be dumped */
12288         if (!aminfo->dobj.dump || dopt->dataOnly)
12289                 return;
12290
12291         q = createPQExpBuffer();
12292         delq = createPQExpBuffer();
12293         labelq = createPQExpBuffer();
12294
12295         qamname = pg_strdup(fmtId(aminfo->dobj.name));
12296
12297         appendPQExpBuffer(q, "CREATE ACCESS METHOD %s ", qamname);
12298
12299         switch (aminfo->amtype)
12300         {
12301                 case AMTYPE_INDEX:
12302                         appendPQExpBuffer(q, "TYPE INDEX ");
12303                         break;
12304                 default:
12305                         write_msg(NULL, "WARNING: invalid type \"%c\" of access method \"%s\"\n",
12306                                           aminfo->amtype, qamname);
12307                         pg_free(qamname);
12308                         destroyPQExpBuffer(q);
12309                         destroyPQExpBuffer(delq);
12310                         destroyPQExpBuffer(labelq);
12311                         return;
12312         }
12313
12314         appendPQExpBuffer(q, "HANDLER %s;\n", aminfo->amhandler);
12315
12316         appendPQExpBuffer(delq, "DROP ACCESS METHOD %s;\n",
12317                                           qamname);
12318
12319         appendPQExpBuffer(labelq, "ACCESS METHOD %s",
12320                                           qamname);
12321
12322         if (dopt->binary_upgrade)
12323                 binary_upgrade_extension_member(q, &aminfo->dobj, labelq->data);
12324
12325         if (aminfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12326                 ArchiveEntry(fout, aminfo->dobj.catId, aminfo->dobj.dumpId,
12327                                          aminfo->dobj.name,
12328                                          NULL,
12329                                          NULL,
12330                                          "",
12331                                          false, "ACCESS METHOD", SECTION_PRE_DATA,
12332                                          q->data, delq->data, NULL,
12333                                          NULL, 0,
12334                                          NULL, NULL);
12335
12336         /* Dump Access Method Comments */
12337         if (aminfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12338                 dumpComment(fout, labelq->data,
12339                                         NULL, "",
12340                                         aminfo->dobj.catId, 0, aminfo->dobj.dumpId);
12341
12342         pg_free(qamname);
12343
12344         destroyPQExpBuffer(q);
12345         destroyPQExpBuffer(delq);
12346         destroyPQExpBuffer(labelq);
12347 }
12348
12349 /*
12350  * dumpOpclass
12351  *        write out a single operator class definition
12352  */
12353 static void
12354 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
12355 {
12356         DumpOptions *dopt = fout->dopt;
12357         PQExpBuffer query;
12358         PQExpBuffer q;
12359         PQExpBuffer delq;
12360         PQExpBuffer labelq;
12361         PGresult   *res;
12362         int                     ntups;
12363         int                     i_opcintype;
12364         int                     i_opckeytype;
12365         int                     i_opcdefault;
12366         int                     i_opcfamily;
12367         int                     i_opcfamilyname;
12368         int                     i_opcfamilynsp;
12369         int                     i_amname;
12370         int                     i_amopstrategy;
12371         int                     i_amopreqcheck;
12372         int                     i_amopopr;
12373         int                     i_sortfamily;
12374         int                     i_sortfamilynsp;
12375         int                     i_amprocnum;
12376         int                     i_amproc;
12377         int                     i_amproclefttype;
12378         int                     i_amprocrighttype;
12379         char       *opcintype;
12380         char       *opckeytype;
12381         char       *opcdefault;
12382         char       *opcfamily;
12383         char       *opcfamilyname;
12384         char       *opcfamilynsp;
12385         char       *amname;
12386         char       *amopstrategy;
12387         char       *amopreqcheck;
12388         char       *amopopr;
12389         char       *sortfamily;
12390         char       *sortfamilynsp;
12391         char       *amprocnum;
12392         char       *amproc;
12393         char       *amproclefttype;
12394         char       *amprocrighttype;
12395         bool            needComma;
12396         int                     i;
12397
12398         /* Skip if not to be dumped */
12399         if (!opcinfo->dobj.dump || dopt->dataOnly)
12400                 return;
12401
12402         query = createPQExpBuffer();
12403         q = createPQExpBuffer();
12404         delq = createPQExpBuffer();
12405         labelq = createPQExpBuffer();
12406
12407         /* Make sure we are in proper schema so regoperator works correctly */
12408         selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
12409
12410         /* Get additional fields from the pg_opclass row */
12411         if (fout->remoteVersion >= 80300)
12412         {
12413                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12414                                                   "opckeytype::pg_catalog.regtype, "
12415                                                   "opcdefault, opcfamily, "
12416                                                   "opfname AS opcfamilyname, "
12417                                                   "nspname AS opcfamilynsp, "
12418                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
12419                                                   "FROM pg_catalog.pg_opclass c "
12420                                                   "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
12421                                                   "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12422                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
12423                                                   opcinfo->dobj.catId.oid);
12424         }
12425         else
12426         {
12427                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
12428                                                   "opckeytype::pg_catalog.regtype, "
12429                                                   "opcdefault, NULL AS opcfamily, "
12430                                                   "NULL AS opcfamilyname, "
12431                                                   "NULL AS opcfamilynsp, "
12432                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
12433                                                   "FROM pg_catalog.pg_opclass "
12434                                                   "WHERE oid = '%u'::pg_catalog.oid",
12435                                                   opcinfo->dobj.catId.oid);
12436         }
12437
12438         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12439
12440         i_opcintype = PQfnumber(res, "opcintype");
12441         i_opckeytype = PQfnumber(res, "opckeytype");
12442         i_opcdefault = PQfnumber(res, "opcdefault");
12443         i_opcfamily = PQfnumber(res, "opcfamily");
12444         i_opcfamilyname = PQfnumber(res, "opcfamilyname");
12445         i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
12446         i_amname = PQfnumber(res, "amname");
12447
12448         /* opcintype may still be needed after we PQclear res */
12449         opcintype = pg_strdup(PQgetvalue(res, 0, i_opcintype));
12450         opckeytype = PQgetvalue(res, 0, i_opckeytype);
12451         opcdefault = PQgetvalue(res, 0, i_opcdefault);
12452         /* opcfamily will still be needed after we PQclear res */
12453         opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
12454         opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
12455         opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
12456         /* amname will still be needed after we PQclear res */
12457         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
12458
12459         /*
12460          * DROP must be fully qualified in case same name appears in pg_catalog
12461          */
12462         appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
12463                                           fmtId(opcinfo->dobj.namespace->dobj.name));
12464         appendPQExpBuffer(delq, ".%s",
12465                                           fmtId(opcinfo->dobj.name));
12466         appendPQExpBuffer(delq, " USING %s;\n",
12467                                           fmtId(amname));
12468
12469         /* Build the fixed portion of the CREATE command */
12470         appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n    ",
12471                                           fmtId(opcinfo->dobj.name));
12472         if (strcmp(opcdefault, "t") == 0)
12473                 appendPQExpBufferStr(q, "DEFAULT ");
12474         appendPQExpBuffer(q, "FOR TYPE %s USING %s",
12475                                           opcintype,
12476                                           fmtId(amname));
12477         if (strlen(opcfamilyname) > 0)
12478         {
12479                 appendPQExpBufferStr(q, " FAMILY ");
12480                 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
12481                         appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
12482                 appendPQExpBufferStr(q, fmtId(opcfamilyname));
12483         }
12484         appendPQExpBufferStr(q, " AS\n    ");
12485
12486         needComma = false;
12487
12488         if (strcmp(opckeytype, "-") != 0)
12489         {
12490                 appendPQExpBuffer(q, "STORAGE %s",
12491                                                   opckeytype);
12492                 needComma = true;
12493         }
12494
12495         PQclear(res);
12496
12497         /*
12498          * Now fetch and print the OPERATOR entries (pg_amop rows).
12499          *
12500          * Print only those opfamily members that are tied to the opclass by
12501          * pg_depend entries.
12502          *
12503          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
12504          * older server's opclass in which it is used.  This is to avoid
12505          * hard-to-detect breakage if a newer pg_dump is used to dump from an
12506          * older server and then reload into that old version.  This can go away
12507          * once 8.3 is so old as to not be of interest to anyone.
12508          */
12509         resetPQExpBuffer(query);
12510
12511         if (fout->remoteVersion >= 90100)
12512         {
12513                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12514                                                   "amopopr::pg_catalog.regoperator, "
12515                                                   "opfname AS sortfamily, "
12516                                                   "nspname AS sortfamilynsp "
12517                                                   "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
12518                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
12519                                                   "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
12520                                                   "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12521                                                   "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12522                                                   "AND refobjid = '%u'::pg_catalog.oid "
12523                                                   "AND amopfamily = '%s'::pg_catalog.oid "
12524                                                   "ORDER BY amopstrategy",
12525                                                   opcinfo->dobj.catId.oid,
12526                                                   opcfamily);
12527         }
12528         else if (fout->remoteVersion >= 80400)
12529         {
12530                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12531                                                   "amopopr::pg_catalog.regoperator, "
12532                                                   "NULL AS sortfamily, "
12533                                                   "NULL AS sortfamilynsp "
12534                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12535                                                   "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12536                                                   "AND refobjid = '%u'::pg_catalog.oid "
12537                                                   "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12538                                                   "AND objid = ao.oid "
12539                                                   "ORDER BY amopstrategy",
12540                                                   opcinfo->dobj.catId.oid);
12541         }
12542         else if (fout->remoteVersion >= 80300)
12543         {
12544                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12545                                                   "amopopr::pg_catalog.regoperator, "
12546                                                   "NULL AS sortfamily, "
12547                                                   "NULL AS sortfamilynsp "
12548                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12549                                                   "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12550                                                   "AND refobjid = '%u'::pg_catalog.oid "
12551                                                   "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12552                                                   "AND objid = ao.oid "
12553                                                   "ORDER BY amopstrategy",
12554                                                   opcinfo->dobj.catId.oid);
12555         }
12556         else
12557         {
12558                 /*
12559                  * Here, we print all entries since there are no opfamilies and hence
12560                  * no loose operators to worry about.
12561                  */
12562                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12563                                                   "amopopr::pg_catalog.regoperator, "
12564                                                   "NULL AS sortfamily, "
12565                                                   "NULL AS sortfamilynsp "
12566                                                   "FROM pg_catalog.pg_amop "
12567                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
12568                                                   "ORDER BY amopstrategy",
12569                                                   opcinfo->dobj.catId.oid);
12570         }
12571
12572         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12573
12574         ntups = PQntuples(res);
12575
12576         i_amopstrategy = PQfnumber(res, "amopstrategy");
12577         i_amopreqcheck = PQfnumber(res, "amopreqcheck");
12578         i_amopopr = PQfnumber(res, "amopopr");
12579         i_sortfamily = PQfnumber(res, "sortfamily");
12580         i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
12581
12582         for (i = 0; i < ntups; i++)
12583         {
12584                 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
12585                 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
12586                 amopopr = PQgetvalue(res, i, i_amopopr);
12587                 sortfamily = PQgetvalue(res, i, i_sortfamily);
12588                 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
12589
12590                 if (needComma)
12591                         appendPQExpBufferStr(q, " ,\n    ");
12592
12593                 appendPQExpBuffer(q, "OPERATOR %s %s",
12594                                                   amopstrategy, amopopr);
12595
12596                 if (strlen(sortfamily) > 0)
12597                 {
12598                         appendPQExpBufferStr(q, " FOR ORDER BY ");
12599                         if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
12600                                 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
12601                         appendPQExpBufferStr(q, fmtId(sortfamily));
12602                 }
12603
12604                 if (strcmp(amopreqcheck, "t") == 0)
12605                         appendPQExpBufferStr(q, " RECHECK");
12606
12607                 needComma = true;
12608         }
12609
12610         PQclear(res);
12611
12612         /*
12613          * Now fetch and print the FUNCTION entries (pg_amproc rows).
12614          *
12615          * Print only those opfamily members that are tied to the opclass by
12616          * pg_depend entries.
12617          *
12618          * We print the amproclefttype/amprocrighttype even though in most cases
12619          * the backend could deduce the right values, because of the corner case
12620          * of a btree sort support function for a cross-type comparison.  That's
12621          * only allowed in 9.2 and later, but for simplicity print them in all
12622          * versions that have the columns.
12623          */
12624         resetPQExpBuffer(query);
12625
12626         if (fout->remoteVersion >= 80300)
12627         {
12628                 appendPQExpBuffer(query, "SELECT amprocnum, "
12629                                                   "amproc::pg_catalog.regprocedure, "
12630                                                   "amproclefttype::pg_catalog.regtype, "
12631                                                   "amprocrighttype::pg_catalog.regtype "
12632                                                   "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
12633                                                   "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
12634                                                   "AND refobjid = '%u'::pg_catalog.oid "
12635                                                   "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
12636                                                   "AND objid = ap.oid "
12637                                                   "ORDER BY amprocnum",
12638                                                   opcinfo->dobj.catId.oid);
12639         }
12640         else
12641         {
12642                 appendPQExpBuffer(query, "SELECT amprocnum, "
12643                                                   "amproc::pg_catalog.regprocedure, "
12644                                                   "'' AS amproclefttype, "
12645                                                   "'' AS amprocrighttype "
12646                                                   "FROM pg_catalog.pg_amproc "
12647                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
12648                                                   "ORDER BY amprocnum",
12649                                                   opcinfo->dobj.catId.oid);
12650         }
12651
12652         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12653
12654         ntups = PQntuples(res);
12655
12656         i_amprocnum = PQfnumber(res, "amprocnum");
12657         i_amproc = PQfnumber(res, "amproc");
12658         i_amproclefttype = PQfnumber(res, "amproclefttype");
12659         i_amprocrighttype = PQfnumber(res, "amprocrighttype");
12660
12661         for (i = 0; i < ntups; i++)
12662         {
12663                 amprocnum = PQgetvalue(res, i, i_amprocnum);
12664                 amproc = PQgetvalue(res, i, i_amproc);
12665                 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
12666                 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
12667
12668                 if (needComma)
12669                         appendPQExpBufferStr(q, " ,\n    ");
12670
12671                 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
12672
12673                 if (*amproclefttype && *amprocrighttype)
12674                         appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
12675
12676                 appendPQExpBuffer(q, " %s", amproc);
12677
12678                 needComma = true;
12679         }
12680
12681         PQclear(res);
12682
12683         /*
12684          * If needComma is still false it means we haven't added anything after
12685          * the AS keyword.  To avoid printing broken SQL, append a dummy STORAGE
12686          * clause with the same datatype.  This isn't sanctioned by the
12687          * documentation, but actually DefineOpClass will treat it as a no-op.
12688          */
12689         if (!needComma)
12690                 appendPQExpBuffer(q, "STORAGE %s", opcintype);
12691
12692         appendPQExpBufferStr(q, ";\n");
12693
12694         appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
12695                                           fmtId(opcinfo->dobj.name));
12696         appendPQExpBuffer(labelq, " USING %s",
12697                                           fmtId(amname));
12698
12699         if (dopt->binary_upgrade)
12700                 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
12701
12702         if (opcinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12703                 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
12704                                          opcinfo->dobj.name,
12705                                          opcinfo->dobj.namespace->dobj.name,
12706                                          NULL,
12707                                          opcinfo->rolname,
12708                                          false, "OPERATOR CLASS", SECTION_PRE_DATA,
12709                                          q->data, delq->data, NULL,
12710                                          NULL, 0,
12711                                          NULL, NULL);
12712
12713         /* Dump Operator Class Comments */
12714         if (opcinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12715                 dumpComment(fout, labelq->data,
12716                                         opcinfo->dobj.namespace->dobj.name, opcinfo->rolname,
12717                                         opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
12718
12719         free(opcintype);
12720         free(opcfamily);
12721         free(amname);
12722         destroyPQExpBuffer(query);
12723         destroyPQExpBuffer(q);
12724         destroyPQExpBuffer(delq);
12725         destroyPQExpBuffer(labelq);
12726 }
12727
12728 /*
12729  * dumpOpfamily
12730  *        write out a single operator family definition
12731  *
12732  * Note: this also dumps any "loose" operator members that aren't bound to a
12733  * specific opclass within the opfamily.
12734  */
12735 static void
12736 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
12737 {
12738         DumpOptions *dopt = fout->dopt;
12739         PQExpBuffer query;
12740         PQExpBuffer q;
12741         PQExpBuffer delq;
12742         PQExpBuffer labelq;
12743         PGresult   *res;
12744         PGresult   *res_ops;
12745         PGresult   *res_procs;
12746         int                     ntups;
12747         int                     i_amname;
12748         int                     i_amopstrategy;
12749         int                     i_amopreqcheck;
12750         int                     i_amopopr;
12751         int                     i_sortfamily;
12752         int                     i_sortfamilynsp;
12753         int                     i_amprocnum;
12754         int                     i_amproc;
12755         int                     i_amproclefttype;
12756         int                     i_amprocrighttype;
12757         char       *amname;
12758         char       *amopstrategy;
12759         char       *amopreqcheck;
12760         char       *amopopr;
12761         char       *sortfamily;
12762         char       *sortfamilynsp;
12763         char       *amprocnum;
12764         char       *amproc;
12765         char       *amproclefttype;
12766         char       *amprocrighttype;
12767         bool            needComma;
12768         int                     i;
12769
12770         /* Skip if not to be dumped */
12771         if (!opfinfo->dobj.dump || dopt->dataOnly)
12772                 return;
12773
12774         query = createPQExpBuffer();
12775         q = createPQExpBuffer();
12776         delq = createPQExpBuffer();
12777         labelq = createPQExpBuffer();
12778
12779         /* Make sure we are in proper schema so regoperator works correctly */
12780         selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
12781
12782         /*
12783          * Fetch only those opfamily members that are tied directly to the
12784          * opfamily by pg_depend entries.
12785          *
12786          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
12787          * older server's opclass in which it is used.  This is to avoid
12788          * hard-to-detect breakage if a newer pg_dump is used to dump from an
12789          * older server and then reload into that old version.  This can go away
12790          * once 8.3 is so old as to not be of interest to anyone.
12791          */
12792         if (fout->remoteVersion >= 90100)
12793         {
12794                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12795                                                   "amopopr::pg_catalog.regoperator, "
12796                                                   "opfname AS sortfamily, "
12797                                                   "nspname AS sortfamilynsp "
12798                                                   "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
12799                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
12800                                                   "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
12801                                                   "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
12802                                                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
12803                                                   "AND refobjid = '%u'::pg_catalog.oid "
12804                                                   "AND amopfamily = '%u'::pg_catalog.oid "
12805                                                   "ORDER BY amopstrategy",
12806                                                   opfinfo->dobj.catId.oid,
12807                                                   opfinfo->dobj.catId.oid);
12808         }
12809         else if (fout->remoteVersion >= 80400)
12810         {
12811                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
12812                                                   "amopopr::pg_catalog.regoperator, "
12813                                                   "NULL AS sortfamily, "
12814                                                   "NULL AS sortfamilynsp "
12815                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12816                                                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
12817                                                   "AND refobjid = '%u'::pg_catalog.oid "
12818                                                   "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12819                                                   "AND objid = ao.oid "
12820                                                   "ORDER BY amopstrategy",
12821                                                   opfinfo->dobj.catId.oid);
12822         }
12823         else
12824         {
12825                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
12826                                                   "amopopr::pg_catalog.regoperator, "
12827                                                   "NULL AS sortfamily, "
12828                                                   "NULL AS sortfamilynsp "
12829                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
12830                                                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
12831                                                   "AND refobjid = '%u'::pg_catalog.oid "
12832                                                   "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
12833                                                   "AND objid = ao.oid "
12834                                                   "ORDER BY amopstrategy",
12835                                                   opfinfo->dobj.catId.oid);
12836         }
12837
12838         res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12839
12840         resetPQExpBuffer(query);
12841
12842         appendPQExpBuffer(query, "SELECT amprocnum, "
12843                                           "amproc::pg_catalog.regprocedure, "
12844                                           "amproclefttype::pg_catalog.regtype, "
12845                                           "amprocrighttype::pg_catalog.regtype "
12846                                           "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
12847                                           "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
12848                                           "AND refobjid = '%u'::pg_catalog.oid "
12849                                           "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
12850                                           "AND objid = ap.oid "
12851                                           "ORDER BY amprocnum",
12852                                           opfinfo->dobj.catId.oid);
12853
12854         res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12855
12856         /* Get additional fields from the pg_opfamily row */
12857         resetPQExpBuffer(query);
12858
12859         appendPQExpBuffer(query, "SELECT "
12860                                           "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
12861                                           "FROM pg_catalog.pg_opfamily "
12862                                           "WHERE oid = '%u'::pg_catalog.oid",
12863                                           opfinfo->dobj.catId.oid);
12864
12865         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12866
12867         i_amname = PQfnumber(res, "amname");
12868
12869         /* amname will still be needed after we PQclear res */
12870         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
12871
12872         /*
12873          * DROP must be fully qualified in case same name appears in pg_catalog
12874          */
12875         appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
12876                                           fmtId(opfinfo->dobj.namespace->dobj.name));
12877         appendPQExpBuffer(delq, ".%s",
12878                                           fmtId(opfinfo->dobj.name));
12879         appendPQExpBuffer(delq, " USING %s;\n",
12880                                           fmtId(amname));
12881
12882         /* Build the fixed portion of the CREATE command */
12883         appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
12884                                           fmtId(opfinfo->dobj.name));
12885         appendPQExpBuffer(q, " USING %s;\n",
12886                                           fmtId(amname));
12887
12888         PQclear(res);
12889
12890         /* Do we need an ALTER to add loose members? */
12891         if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
12892         {
12893                 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
12894                                                   fmtId(opfinfo->dobj.name));
12895                 appendPQExpBuffer(q, " USING %s ADD\n    ",
12896                                                   fmtId(amname));
12897
12898                 needComma = false;
12899
12900                 /*
12901                  * Now fetch and print the OPERATOR entries (pg_amop rows).
12902                  */
12903                 ntups = PQntuples(res_ops);
12904
12905                 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
12906                 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
12907                 i_amopopr = PQfnumber(res_ops, "amopopr");
12908                 i_sortfamily = PQfnumber(res_ops, "sortfamily");
12909                 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
12910
12911                 for (i = 0; i < ntups; i++)
12912                 {
12913                         amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
12914                         amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
12915                         amopopr = PQgetvalue(res_ops, i, i_amopopr);
12916                         sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
12917                         sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
12918
12919                         if (needComma)
12920                                 appendPQExpBufferStr(q, " ,\n    ");
12921
12922                         appendPQExpBuffer(q, "OPERATOR %s %s",
12923                                                           amopstrategy, amopopr);
12924
12925                         if (strlen(sortfamily) > 0)
12926                         {
12927                                 appendPQExpBufferStr(q, " FOR ORDER BY ");
12928                                 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
12929                                         appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
12930                                 appendPQExpBufferStr(q, fmtId(sortfamily));
12931                         }
12932
12933                         if (strcmp(amopreqcheck, "t") == 0)
12934                                 appendPQExpBufferStr(q, " RECHECK");
12935
12936                         needComma = true;
12937                 }
12938
12939                 /*
12940                  * Now fetch and print the FUNCTION entries (pg_amproc rows).
12941                  */
12942                 ntups = PQntuples(res_procs);
12943
12944                 i_amprocnum = PQfnumber(res_procs, "amprocnum");
12945                 i_amproc = PQfnumber(res_procs, "amproc");
12946                 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
12947                 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
12948
12949                 for (i = 0; i < ntups; i++)
12950                 {
12951                         amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
12952                         amproc = PQgetvalue(res_procs, i, i_amproc);
12953                         amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
12954                         amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
12955
12956                         if (needComma)
12957                                 appendPQExpBufferStr(q, " ,\n    ");
12958
12959                         appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
12960                                                           amprocnum, amproclefttype, amprocrighttype,
12961                                                           amproc);
12962
12963                         needComma = true;
12964                 }
12965
12966                 appendPQExpBufferStr(q, ";\n");
12967         }
12968
12969         appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
12970                                           fmtId(opfinfo->dobj.name));
12971         appendPQExpBuffer(labelq, " USING %s",
12972                                           fmtId(amname));
12973
12974         if (dopt->binary_upgrade)
12975                 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
12976
12977         if (opfinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12978                 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
12979                                          opfinfo->dobj.name,
12980                                          opfinfo->dobj.namespace->dobj.name,
12981                                          NULL,
12982                                          opfinfo->rolname,
12983                                          false, "OPERATOR FAMILY", SECTION_PRE_DATA,
12984                                          q->data, delq->data, NULL,
12985                                          NULL, 0,
12986                                          NULL, NULL);
12987
12988         /* Dump Operator Family Comments */
12989         if (opfinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12990                 dumpComment(fout, labelq->data,
12991                                         opfinfo->dobj.namespace->dobj.name, opfinfo->rolname,
12992                                         opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
12993
12994         free(amname);
12995         PQclear(res_ops);
12996         PQclear(res_procs);
12997         destroyPQExpBuffer(query);
12998         destroyPQExpBuffer(q);
12999         destroyPQExpBuffer(delq);
13000         destroyPQExpBuffer(labelq);
13001 }
13002
13003 /*
13004  * dumpCollation
13005  *        write out a single collation definition
13006  */
13007 static void
13008 dumpCollation(Archive *fout, CollInfo *collinfo)
13009 {
13010         DumpOptions *dopt = fout->dopt;
13011         PQExpBuffer query;
13012         PQExpBuffer q;
13013         PQExpBuffer delq;
13014         PQExpBuffer labelq;
13015         PGresult   *res;
13016         int                     i_collprovider;
13017         int                     i_collcollate;
13018         int                     i_collctype;
13019         const char *collprovider;
13020         const char *collcollate;
13021         const char *collctype;
13022
13023         /* Skip if not to be dumped */
13024         if (!collinfo->dobj.dump || dopt->dataOnly)
13025                 return;
13026
13027         query = createPQExpBuffer();
13028         q = createPQExpBuffer();
13029         delq = createPQExpBuffer();
13030         labelq = createPQExpBuffer();
13031
13032         /* Make sure we are in proper schema */
13033         selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
13034
13035         /* Get collation-specific details */
13036         if (fout->remoteVersion >= 100000)
13037                 appendPQExpBuffer(query, "SELECT "
13038                                                   "collprovider, "
13039                                                   "collcollate, "
13040                                                   "collctype, "
13041                                                   "collversion "
13042                                                   "FROM pg_catalog.pg_collation c "
13043                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
13044                                                   collinfo->dobj.catId.oid);
13045         else
13046                 appendPQExpBuffer(query, "SELECT "
13047                                                   "'c'::char AS collprovider, "
13048                                                   "collcollate, "
13049                                                   "collctype, "
13050                                                   "NULL AS collversion "
13051                                                   "FROM pg_catalog.pg_collation c "
13052                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
13053                                                   collinfo->dobj.catId.oid);
13054
13055         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13056
13057         i_collprovider = PQfnumber(res, "collprovider");
13058         i_collcollate = PQfnumber(res, "collcollate");
13059         i_collctype = PQfnumber(res, "collctype");
13060
13061         collprovider = PQgetvalue(res, 0, i_collprovider);
13062         collcollate = PQgetvalue(res, 0, i_collcollate);
13063         collctype = PQgetvalue(res, 0, i_collctype);
13064
13065         /*
13066          * DROP must be fully qualified in case same name appears in pg_catalog
13067          */
13068         appendPQExpBuffer(delq, "DROP COLLATION %s",
13069                                           fmtId(collinfo->dobj.namespace->dobj.name));
13070         appendPQExpBuffer(delq, ".%s;\n",
13071                                           fmtId(collinfo->dobj.name));
13072
13073         appendPQExpBuffer(q, "CREATE COLLATION %s (",
13074                                           fmtId(collinfo->dobj.name));
13075
13076         appendPQExpBufferStr(q, "provider = ");
13077         if (collprovider[0] == 'c')
13078                 appendPQExpBufferStr(q, "libc");
13079         else if (collprovider[0] == 'i')
13080                 appendPQExpBufferStr(q, "icu");
13081         else if (collprovider[0] == 'd')
13082                 /* to allow dumping pg_catalog; not accepted on input */
13083                 appendPQExpBufferStr(q, "default");
13084         else
13085                 exit_horribly(NULL,
13086                                           "unrecognized collation provider: %s\n",
13087                                           collprovider);
13088
13089         if (strcmp(collcollate, collctype) == 0)
13090         {
13091                 appendPQExpBufferStr(q, ", locale = ");
13092                 appendStringLiteralAH(q, collcollate, fout);
13093         }
13094         else
13095         {
13096                 appendPQExpBufferStr(q, ", lc_collate = ");
13097                 appendStringLiteralAH(q, collcollate, fout);
13098                 appendPQExpBufferStr(q, ", lc_ctype = ");
13099                 appendStringLiteralAH(q, collctype, fout);
13100         }
13101
13102         /*
13103          * For binary upgrade, carry over the collation version.  For normal
13104          * dump/restore, omit the version, so that it is computed upon restore.
13105          */
13106         if (dopt->binary_upgrade)
13107         {
13108                 int                     i_collversion;
13109
13110                 i_collversion = PQfnumber(res, "collversion");
13111                 if (!PQgetisnull(res, 0, i_collversion))
13112                 {
13113                         appendPQExpBufferStr(q, ", version = ");
13114                         appendStringLiteralAH(q,
13115                                                                   PQgetvalue(res, 0, i_collversion),
13116                                                                   fout);
13117                 }
13118         }
13119
13120         appendPQExpBufferStr(q, ");\n");
13121
13122         appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
13123
13124         if (dopt->binary_upgrade)
13125                 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
13126
13127         if (collinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13128                 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
13129                                          collinfo->dobj.name,
13130                                          collinfo->dobj.namespace->dobj.name,
13131                                          NULL,
13132                                          collinfo->rolname,
13133                                          false, "COLLATION", SECTION_PRE_DATA,
13134                                          q->data, delq->data, NULL,
13135                                          NULL, 0,
13136                                          NULL, NULL);
13137
13138         /* Dump Collation Comments */
13139         if (collinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13140                 dumpComment(fout, labelq->data,
13141                                         collinfo->dobj.namespace->dobj.name, collinfo->rolname,
13142                                         collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
13143
13144         PQclear(res);
13145
13146         destroyPQExpBuffer(query);
13147         destroyPQExpBuffer(q);
13148         destroyPQExpBuffer(delq);
13149         destroyPQExpBuffer(labelq);
13150 }
13151
13152 /*
13153  * dumpConversion
13154  *        write out a single conversion definition
13155  */
13156 static void
13157 dumpConversion(Archive *fout, ConvInfo *convinfo)
13158 {
13159         DumpOptions *dopt = fout->dopt;
13160         PQExpBuffer query;
13161         PQExpBuffer q;
13162         PQExpBuffer delq;
13163         PQExpBuffer labelq;
13164         PGresult   *res;
13165         int                     i_conforencoding;
13166         int                     i_contoencoding;
13167         int                     i_conproc;
13168         int                     i_condefault;
13169         const char *conforencoding;
13170         const char *contoencoding;
13171         const char *conproc;
13172         bool            condefault;
13173
13174         /* Skip if not to be dumped */
13175         if (!convinfo->dobj.dump || dopt->dataOnly)
13176                 return;
13177
13178         query = createPQExpBuffer();
13179         q = createPQExpBuffer();
13180         delq = createPQExpBuffer();
13181         labelq = createPQExpBuffer();
13182
13183         /* Make sure we are in proper schema */
13184         selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
13185
13186         /* Get conversion-specific details */
13187         appendPQExpBuffer(query, "SELECT "
13188                                           "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
13189                                           "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
13190                                           "conproc, condefault "
13191                                           "FROM pg_catalog.pg_conversion c "
13192                                           "WHERE c.oid = '%u'::pg_catalog.oid",
13193                                           convinfo->dobj.catId.oid);
13194
13195         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13196
13197         i_conforencoding = PQfnumber(res, "conforencoding");
13198         i_contoencoding = PQfnumber(res, "contoencoding");
13199         i_conproc = PQfnumber(res, "conproc");
13200         i_condefault = PQfnumber(res, "condefault");
13201
13202         conforencoding = PQgetvalue(res, 0, i_conforencoding);
13203         contoencoding = PQgetvalue(res, 0, i_contoencoding);
13204         conproc = PQgetvalue(res, 0, i_conproc);
13205         condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
13206
13207         /*
13208          * DROP must be fully qualified in case same name appears in pg_catalog
13209          */
13210         appendPQExpBuffer(delq, "DROP CONVERSION %s",
13211                                           fmtId(convinfo->dobj.namespace->dobj.name));
13212         appendPQExpBuffer(delq, ".%s;\n",
13213                                           fmtId(convinfo->dobj.name));
13214
13215         appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
13216                                           (condefault) ? "DEFAULT " : "",
13217                                           fmtId(convinfo->dobj.name));
13218         appendStringLiteralAH(q, conforencoding, fout);
13219         appendPQExpBufferStr(q, " TO ");
13220         appendStringLiteralAH(q, contoencoding, fout);
13221         /* regproc output is already sufficiently quoted */
13222         appendPQExpBuffer(q, " FROM %s;\n", conproc);
13223
13224         appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
13225
13226         if (dopt->binary_upgrade)
13227                 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
13228
13229         if (convinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13230                 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
13231                                          convinfo->dobj.name,
13232                                          convinfo->dobj.namespace->dobj.name,
13233                                          NULL,
13234                                          convinfo->rolname,
13235                                          false, "CONVERSION", SECTION_PRE_DATA,
13236                                          q->data, delq->data, NULL,
13237                                          NULL, 0,
13238                                          NULL, NULL);
13239
13240         /* Dump Conversion Comments */
13241         if (convinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13242                 dumpComment(fout, labelq->data,
13243                                         convinfo->dobj.namespace->dobj.name, convinfo->rolname,
13244                                         convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
13245
13246         PQclear(res);
13247
13248         destroyPQExpBuffer(query);
13249         destroyPQExpBuffer(q);
13250         destroyPQExpBuffer(delq);
13251         destroyPQExpBuffer(labelq);
13252 }
13253
13254 /*
13255  * format_aggregate_signature: generate aggregate name and argument list
13256  *
13257  * The argument type names are qualified if needed.  The aggregate name
13258  * is never qualified.
13259  */
13260 static char *
13261 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
13262 {
13263         PQExpBufferData buf;
13264         int                     j;
13265
13266         initPQExpBuffer(&buf);
13267         if (honor_quotes)
13268                 appendPQExpBufferStr(&buf, fmtId(agginfo->aggfn.dobj.name));
13269         else
13270                 appendPQExpBufferStr(&buf, agginfo->aggfn.dobj.name);
13271
13272         if (agginfo->aggfn.nargs == 0)
13273                 appendPQExpBuffer(&buf, "(*)");
13274         else
13275         {
13276                 appendPQExpBufferChar(&buf, '(');
13277                 for (j = 0; j < agginfo->aggfn.nargs; j++)
13278                 {
13279                         char       *typname;
13280
13281                         typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
13282                                                                                    zeroAsOpaque);
13283
13284                         appendPQExpBuffer(&buf, "%s%s",
13285                                                           (j > 0) ? ", " : "",
13286                                                           typname);
13287                         free(typname);
13288                 }
13289                 appendPQExpBufferChar(&buf, ')');
13290         }
13291         return buf.data;
13292 }
13293
13294 /*
13295  * dumpAgg
13296  *        write out a single aggregate definition
13297  */
13298 static void
13299 dumpAgg(Archive *fout, AggInfo *agginfo)
13300 {
13301         DumpOptions *dopt = fout->dopt;
13302         PQExpBuffer query;
13303         PQExpBuffer q;
13304         PQExpBuffer delq;
13305         PQExpBuffer labelq;
13306         PQExpBuffer details;
13307         char       *aggsig;                     /* identity signature */
13308         char       *aggfullsig = NULL;  /* full signature */
13309         char       *aggsig_tag;
13310         PGresult   *res;
13311         int                     i_aggtransfn;
13312         int                     i_aggfinalfn;
13313         int                     i_aggcombinefn;
13314         int                     i_aggserialfn;
13315         int                     i_aggdeserialfn;
13316         int                     i_aggmtransfn;
13317         int                     i_aggminvtransfn;
13318         int                     i_aggmfinalfn;
13319         int                     i_aggfinalextra;
13320         int                     i_aggmfinalextra;
13321         int                     i_aggsortop;
13322         int                     i_hypothetical;
13323         int                     i_aggtranstype;
13324         int                     i_aggtransspace;
13325         int                     i_aggmtranstype;
13326         int                     i_aggmtransspace;
13327         int                     i_agginitval;
13328         int                     i_aggminitval;
13329         int                     i_convertok;
13330         int                     i_proparallel;
13331         const char *aggtransfn;
13332         const char *aggfinalfn;
13333         const char *aggcombinefn;
13334         const char *aggserialfn;
13335         const char *aggdeserialfn;
13336         const char *aggmtransfn;
13337         const char *aggminvtransfn;
13338         const char *aggmfinalfn;
13339         bool            aggfinalextra;
13340         bool            aggmfinalextra;
13341         const char *aggsortop;
13342         char       *aggsortconvop;
13343         bool            hypothetical;
13344         const char *aggtranstype;
13345         const char *aggtransspace;
13346         const char *aggmtranstype;
13347         const char *aggmtransspace;
13348         const char *agginitval;
13349         const char *aggminitval;
13350         bool            convertok;
13351         const char *proparallel;
13352
13353         /* Skip if not to be dumped */
13354         if (!agginfo->aggfn.dobj.dump || dopt->dataOnly)
13355                 return;
13356
13357         query = createPQExpBuffer();
13358         q = createPQExpBuffer();
13359         delq = createPQExpBuffer();
13360         labelq = createPQExpBuffer();
13361         details = createPQExpBuffer();
13362
13363         /* Make sure we are in proper schema */
13364         selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
13365
13366         /* Get aggregate-specific details */
13367         if (fout->remoteVersion >= 90600)
13368         {
13369                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13370                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13371                                                   "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
13372                                                   "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13373                                                   "aggfinalextra, aggmfinalextra, "
13374                                                   "aggsortop::pg_catalog.regoperator, "
13375                                                   "(aggkind = 'h') AS hypothetical, "
13376                                                   "aggtransspace, agginitval, "
13377                                                   "aggmtransspace, aggminitval, "
13378                                                   "true AS convertok, "
13379                                                   "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13380                                                   "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
13381                                                   "p.proparallel "
13382                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13383                                                   "WHERE a.aggfnoid = p.oid "
13384                                                   "AND p.oid = '%u'::pg_catalog.oid",
13385                                                   agginfo->aggfn.dobj.catId.oid);
13386         }
13387         else if (fout->remoteVersion >= 90400)
13388         {
13389                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13390                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13391                                                   "'-' AS aggcombinefn, '-' AS aggserialfn, "
13392                                                   "'-' AS aggdeserialfn, aggmtransfn, aggminvtransfn, "
13393                                                   "aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
13394                                                   "aggfinalextra, aggmfinalextra, "
13395                                                   "aggsortop::pg_catalog.regoperator, "
13396                                                   "(aggkind = 'h') AS hypothetical, "
13397                                                   "aggtransspace, agginitval, "
13398                                                   "aggmtransspace, aggminitval, "
13399                                                   "true AS convertok, "
13400                                                   "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13401                                                   "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13402                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13403                                                   "WHERE a.aggfnoid = p.oid "
13404                                                   "AND p.oid = '%u'::pg_catalog.oid",
13405                                                   agginfo->aggfn.dobj.catId.oid);
13406         }
13407         else if (fout->remoteVersion >= 80400)
13408         {
13409                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13410                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13411                                                   "'-' AS aggcombinefn, '-' AS aggserialfn, "
13412                                                   "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13413                                                   "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13414                                                   "0 AS aggmtranstype, false AS aggfinalextra, "
13415                                                   "false AS aggmfinalextra, "
13416                                                   "aggsortop::pg_catalog.regoperator, "
13417                                                   "false AS hypothetical, "
13418                                                   "0 AS aggtransspace, agginitval, "
13419                                                   "0 AS aggmtransspace, NULL AS aggminitval, "
13420                                                   "true AS convertok, "
13421                                                   "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
13422                                                   "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
13423                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13424                                                   "WHERE a.aggfnoid = p.oid "
13425                                                   "AND p.oid = '%u'::pg_catalog.oid",
13426                                                   agginfo->aggfn.dobj.catId.oid);
13427         }
13428         else if (fout->remoteVersion >= 80100)
13429         {
13430                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13431                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13432                                                   "'-' AS aggcombinefn, '-' AS aggserialfn, "
13433                                                   "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13434                                                   "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13435                                                   "0 AS aggmtranstype, false AS aggfinalextra, "
13436                                                   "false AS aggmfinalextra, "
13437                                                   "aggsortop::pg_catalog.regoperator, "
13438                                                   "false AS hypothetical, "
13439                                                   "0 AS aggtransspace, agginitval, "
13440                                                   "0 AS aggmtransspace, NULL AS aggminitval, "
13441                                                   "true AS convertok "
13442                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13443                                                   "WHERE a.aggfnoid = p.oid "
13444                                                   "AND p.oid = '%u'::pg_catalog.oid",
13445                                                   agginfo->aggfn.dobj.catId.oid);
13446         }
13447         else
13448         {
13449                 appendPQExpBuffer(query, "SELECT aggtransfn, "
13450                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
13451                                                   "'-' AS aggcombinefn, '-' AS aggserialfn, "
13452                                                   "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
13453                                                   "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
13454                                                   "0 AS aggmtranstype, false AS aggfinalextra, "
13455                                                   "false AS aggmfinalextra, 0 AS aggsortop, "
13456                                                   "false AS hypothetical, "
13457                                                   "0 AS aggtransspace, agginitval, "
13458                                                   "0 AS aggmtransspace, NULL AS aggminitval, "
13459                                                   "true AS convertok "
13460                                                   "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
13461                                                   "WHERE a.aggfnoid = p.oid "
13462                                                   "AND p.oid = '%u'::pg_catalog.oid",
13463                                                   agginfo->aggfn.dobj.catId.oid);
13464         }
13465
13466         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13467
13468         i_aggtransfn = PQfnumber(res, "aggtransfn");
13469         i_aggfinalfn = PQfnumber(res, "aggfinalfn");
13470         i_aggcombinefn = PQfnumber(res, "aggcombinefn");
13471         i_aggserialfn = PQfnumber(res, "aggserialfn");
13472         i_aggdeserialfn = PQfnumber(res, "aggdeserialfn");
13473         i_aggmtransfn = PQfnumber(res, "aggmtransfn");
13474         i_aggminvtransfn = PQfnumber(res, "aggminvtransfn");
13475         i_aggmfinalfn = PQfnumber(res, "aggmfinalfn");
13476         i_aggfinalextra = PQfnumber(res, "aggfinalextra");
13477         i_aggmfinalextra = PQfnumber(res, "aggmfinalextra");
13478         i_aggsortop = PQfnumber(res, "aggsortop");
13479         i_hypothetical = PQfnumber(res, "hypothetical");
13480         i_aggtranstype = PQfnumber(res, "aggtranstype");
13481         i_aggtransspace = PQfnumber(res, "aggtransspace");
13482         i_aggmtranstype = PQfnumber(res, "aggmtranstype");
13483         i_aggmtransspace = PQfnumber(res, "aggmtransspace");
13484         i_agginitval = PQfnumber(res, "agginitval");
13485         i_aggminitval = PQfnumber(res, "aggminitval");
13486         i_convertok = PQfnumber(res, "convertok");
13487         i_proparallel = PQfnumber(res, "proparallel");
13488
13489         aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
13490         aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
13491         aggcombinefn = PQgetvalue(res, 0, i_aggcombinefn);
13492         aggserialfn = PQgetvalue(res, 0, i_aggserialfn);
13493         aggdeserialfn = PQgetvalue(res, 0, i_aggdeserialfn);
13494         aggmtransfn = PQgetvalue(res, 0, i_aggmtransfn);
13495         aggminvtransfn = PQgetvalue(res, 0, i_aggminvtransfn);
13496         aggmfinalfn = PQgetvalue(res, 0, i_aggmfinalfn);
13497         aggfinalextra = (PQgetvalue(res, 0, i_aggfinalextra)[0] == 't');
13498         aggmfinalextra = (PQgetvalue(res, 0, i_aggmfinalextra)[0] == 't');
13499         aggsortop = PQgetvalue(res, 0, i_aggsortop);
13500         hypothetical = (PQgetvalue(res, 0, i_hypothetical)[0] == 't');
13501         aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
13502         aggtransspace = PQgetvalue(res, 0, i_aggtransspace);
13503         aggmtranstype = PQgetvalue(res, 0, i_aggmtranstype);
13504         aggmtransspace = PQgetvalue(res, 0, i_aggmtransspace);
13505         agginitval = PQgetvalue(res, 0, i_agginitval);
13506         aggminitval = PQgetvalue(res, 0, i_aggminitval);
13507         convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
13508
13509         if (fout->remoteVersion >= 80400)
13510         {
13511                 /* 8.4 or later; we rely on server-side code for most of the work */
13512                 char       *funcargs;
13513                 char       *funciargs;
13514
13515                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
13516                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
13517                 aggfullsig = format_function_arguments(&agginfo->aggfn, funcargs, true);
13518                 aggsig = format_function_arguments(&agginfo->aggfn, funciargs, true);
13519         }
13520         else
13521                 /* pre-8.4, do it ourselves */
13522                 aggsig = format_aggregate_signature(agginfo, fout, true);
13523
13524         aggsig_tag = format_aggregate_signature(agginfo, fout, false);
13525
13526         if (i_proparallel != -1)
13527                 proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
13528         else
13529                 proparallel = NULL;
13530
13531         if (!convertok)
13532         {
13533                 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
13534                                   aggsig);
13535
13536                 if (aggfullsig)
13537                         free(aggfullsig);
13538
13539                 free(aggsig);
13540
13541                 return;
13542         }
13543
13544         /* regproc and regtype output is already sufficiently quoted */
13545         appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
13546                                           aggtransfn, aggtranstype);
13547
13548         if (strcmp(aggtransspace, "0") != 0)
13549         {
13550                 appendPQExpBuffer(details, ",\n    SSPACE = %s",
13551                                                   aggtransspace);
13552         }
13553
13554         if (!PQgetisnull(res, 0, i_agginitval))
13555         {
13556                 appendPQExpBufferStr(details, ",\n    INITCOND = ");
13557                 appendStringLiteralAH(details, agginitval, fout);
13558         }
13559
13560         if (strcmp(aggfinalfn, "-") != 0)
13561         {
13562                 appendPQExpBuffer(details, ",\n    FINALFUNC = %s",
13563                                                   aggfinalfn);
13564                 if (aggfinalextra)
13565                         appendPQExpBufferStr(details, ",\n    FINALFUNC_EXTRA");
13566         }
13567
13568         if (strcmp(aggcombinefn, "-") != 0)
13569                 appendPQExpBuffer(details, ",\n    COMBINEFUNC = %s", aggcombinefn);
13570
13571         if (strcmp(aggserialfn, "-") != 0)
13572                 appendPQExpBuffer(details, ",\n    SERIALFUNC = %s", aggserialfn);
13573
13574         if (strcmp(aggdeserialfn, "-") != 0)
13575                 appendPQExpBuffer(details, ",\n    DESERIALFUNC = %s", aggdeserialfn);
13576
13577         if (strcmp(aggmtransfn, "-") != 0)
13578         {
13579                 appendPQExpBuffer(details, ",\n    MSFUNC = %s,\n    MINVFUNC = %s,\n    MSTYPE = %s",
13580                                                   aggmtransfn,
13581                                                   aggminvtransfn,
13582                                                   aggmtranstype);
13583         }
13584
13585         if (strcmp(aggmtransspace, "0") != 0)
13586         {
13587                 appendPQExpBuffer(details, ",\n    MSSPACE = %s",
13588                                                   aggmtransspace);
13589         }
13590
13591         if (!PQgetisnull(res, 0, i_aggminitval))
13592         {
13593                 appendPQExpBufferStr(details, ",\n    MINITCOND = ");
13594                 appendStringLiteralAH(details, aggminitval, fout);
13595         }
13596
13597         if (strcmp(aggmfinalfn, "-") != 0)
13598         {
13599                 appendPQExpBuffer(details, ",\n    MFINALFUNC = %s",
13600                                                   aggmfinalfn);
13601                 if (aggmfinalextra)
13602                         appendPQExpBufferStr(details, ",\n    MFINALFUNC_EXTRA");
13603         }
13604
13605         aggsortconvop = convertOperatorReference(fout, aggsortop);
13606         if (aggsortconvop)
13607         {
13608                 appendPQExpBuffer(details, ",\n    SORTOP = %s",
13609                                                   aggsortconvop);
13610                 free(aggsortconvop);
13611         }
13612
13613         if (hypothetical)
13614                 appendPQExpBufferStr(details, ",\n    HYPOTHETICAL");
13615
13616         if (proparallel != NULL && proparallel[0] != PROPARALLEL_UNSAFE)
13617         {
13618                 if (proparallel[0] == PROPARALLEL_SAFE)
13619                         appendPQExpBufferStr(details, ",\n    PARALLEL = safe");
13620                 else if (proparallel[0] == PROPARALLEL_RESTRICTED)
13621                         appendPQExpBufferStr(details, ",\n    PARALLEL = restricted");
13622                 else if (proparallel[0] != PROPARALLEL_UNSAFE)
13623                         exit_horribly(NULL, "unrecognized proparallel value for function \"%s\"\n",
13624                                                   agginfo->aggfn.dobj.name);
13625         }
13626
13627         /*
13628          * DROP must be fully qualified in case same name appears in pg_catalog
13629          */
13630         appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
13631                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
13632                                           aggsig);
13633
13634         appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
13635                                           aggfullsig ? aggfullsig : aggsig, details->data);
13636
13637         appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
13638
13639         if (dopt->binary_upgrade)
13640                 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
13641
13642         if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_DEFINITION)
13643                 ArchiveEntry(fout, agginfo->aggfn.dobj.catId,
13644                                          agginfo->aggfn.dobj.dumpId,
13645                                          aggsig_tag,
13646                                          agginfo->aggfn.dobj.namespace->dobj.name,
13647                                          NULL,
13648                                          agginfo->aggfn.rolname,
13649                                          false, "AGGREGATE", SECTION_PRE_DATA,
13650                                          q->data, delq->data, NULL,
13651                                          NULL, 0,
13652                                          NULL, NULL);
13653
13654         /* Dump Aggregate Comments */
13655         if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_COMMENT)
13656                 dumpComment(fout, labelq->data,
13657                                         agginfo->aggfn.dobj.namespace->dobj.name,
13658                                         agginfo->aggfn.rolname,
13659                                         agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
13660
13661         if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_SECLABEL)
13662                 dumpSecLabel(fout, labelq->data,
13663                                          agginfo->aggfn.dobj.namespace->dobj.name,
13664                                          agginfo->aggfn.rolname,
13665                                          agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
13666
13667         /*
13668          * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
13669          * command look like a function's GRANT; in particular this affects the
13670          * syntax for zero-argument aggregates and ordered-set aggregates.
13671          */
13672         free(aggsig);
13673         free(aggsig_tag);
13674
13675         aggsig = format_function_signature(fout, &agginfo->aggfn, true);
13676         aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
13677
13678         if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_ACL)
13679                 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
13680                                 "FUNCTION",
13681                                 aggsig, NULL, aggsig_tag,
13682                                 agginfo->aggfn.dobj.namespace->dobj.name,
13683                                 agginfo->aggfn.rolname, agginfo->aggfn.proacl,
13684                                 agginfo->aggfn.rproacl,
13685                                 agginfo->aggfn.initproacl, agginfo->aggfn.initrproacl);
13686
13687         free(aggsig);
13688         if (aggfullsig)
13689                 free(aggfullsig);
13690         free(aggsig_tag);
13691
13692         PQclear(res);
13693
13694         destroyPQExpBuffer(query);
13695         destroyPQExpBuffer(q);
13696         destroyPQExpBuffer(delq);
13697         destroyPQExpBuffer(labelq);
13698         destroyPQExpBuffer(details);
13699 }
13700
13701 /*
13702  * dumpTSParser
13703  *        write out a single text search parser
13704  */
13705 static void
13706 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
13707 {
13708         DumpOptions *dopt = fout->dopt;
13709         PQExpBuffer q;
13710         PQExpBuffer delq;
13711         PQExpBuffer labelq;
13712
13713         /* Skip if not to be dumped */
13714         if (!prsinfo->dobj.dump || dopt->dataOnly)
13715                 return;
13716
13717         q = createPQExpBuffer();
13718         delq = createPQExpBuffer();
13719         labelq = createPQExpBuffer();
13720
13721         /* Make sure we are in proper schema */
13722         selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
13723
13724         appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
13725                                           fmtId(prsinfo->dobj.name));
13726
13727         appendPQExpBuffer(q, "    START = %s,\n",
13728                                           convertTSFunction(fout, prsinfo->prsstart));
13729         appendPQExpBuffer(q, "    GETTOKEN = %s,\n",
13730                                           convertTSFunction(fout, prsinfo->prstoken));
13731         appendPQExpBuffer(q, "    END = %s,\n",
13732                                           convertTSFunction(fout, prsinfo->prsend));
13733         if (prsinfo->prsheadline != InvalidOid)
13734                 appendPQExpBuffer(q, "    HEADLINE = %s,\n",
13735                                                   convertTSFunction(fout, prsinfo->prsheadline));
13736         appendPQExpBuffer(q, "    LEXTYPES = %s );\n",
13737                                           convertTSFunction(fout, prsinfo->prslextype));
13738
13739         /*
13740          * DROP must be fully qualified in case same name appears in pg_catalog
13741          */
13742         appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
13743                                           fmtId(prsinfo->dobj.namespace->dobj.name));
13744         appendPQExpBuffer(delq, ".%s;\n",
13745                                           fmtId(prsinfo->dobj.name));
13746
13747         appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
13748                                           fmtId(prsinfo->dobj.name));
13749
13750         if (dopt->binary_upgrade)
13751                 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
13752
13753         if (prsinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13754                 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
13755                                          prsinfo->dobj.name,
13756                                          prsinfo->dobj.namespace->dobj.name,
13757                                          NULL,
13758                                          "",
13759                                          false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
13760                                          q->data, delq->data, NULL,
13761                                          NULL, 0,
13762                                          NULL, NULL);
13763
13764         /* Dump Parser Comments */
13765         if (prsinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13766                 dumpComment(fout, labelq->data,
13767                                         prsinfo->dobj.namespace->dobj.name, "",
13768                                         prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
13769
13770         destroyPQExpBuffer(q);
13771         destroyPQExpBuffer(delq);
13772         destroyPQExpBuffer(labelq);
13773 }
13774
13775 /*
13776  * dumpTSDictionary
13777  *        write out a single text search dictionary
13778  */
13779 static void
13780 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
13781 {
13782         DumpOptions *dopt = fout->dopt;
13783         PQExpBuffer q;
13784         PQExpBuffer delq;
13785         PQExpBuffer labelq;
13786         PQExpBuffer query;
13787         PGresult   *res;
13788         char       *nspname;
13789         char       *tmplname;
13790
13791         /* Skip if not to be dumped */
13792         if (!dictinfo->dobj.dump || dopt->dataOnly)
13793                 return;
13794
13795         q = createPQExpBuffer();
13796         delq = createPQExpBuffer();
13797         labelq = createPQExpBuffer();
13798         query = createPQExpBuffer();
13799
13800         /* Fetch name and namespace of the dictionary's template */
13801         selectSourceSchema(fout, "pg_catalog");
13802         appendPQExpBuffer(query, "SELECT nspname, tmplname "
13803                                           "FROM pg_ts_template p, pg_namespace n "
13804                                           "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
13805                                           dictinfo->dicttemplate);
13806         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13807         nspname = PQgetvalue(res, 0, 0);
13808         tmplname = PQgetvalue(res, 0, 1);
13809
13810         /* Make sure we are in proper schema */
13811         selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
13812
13813         appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
13814                                           fmtId(dictinfo->dobj.name));
13815
13816         appendPQExpBufferStr(q, "    TEMPLATE = ");
13817         if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
13818                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
13819         appendPQExpBufferStr(q, fmtId(tmplname));
13820
13821         PQclear(res);
13822
13823         /* the dictinitoption can be dumped straight into the command */
13824         if (dictinfo->dictinitoption)
13825                 appendPQExpBuffer(q, ",\n    %s", dictinfo->dictinitoption);
13826
13827         appendPQExpBufferStr(q, " );\n");
13828
13829         /*
13830          * DROP must be fully qualified in case same name appears in pg_catalog
13831          */
13832         appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
13833                                           fmtId(dictinfo->dobj.namespace->dobj.name));
13834         appendPQExpBuffer(delq, ".%s;\n",
13835                                           fmtId(dictinfo->dobj.name));
13836
13837         appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
13838                                           fmtId(dictinfo->dobj.name));
13839
13840         if (dopt->binary_upgrade)
13841                 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
13842
13843         if (dictinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13844                 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
13845                                          dictinfo->dobj.name,
13846                                          dictinfo->dobj.namespace->dobj.name,
13847                                          NULL,
13848                                          dictinfo->rolname,
13849                                          false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
13850                                          q->data, delq->data, NULL,
13851                                          NULL, 0,
13852                                          NULL, NULL);
13853
13854         /* Dump Dictionary Comments */
13855         if (dictinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13856                 dumpComment(fout, labelq->data,
13857                                         dictinfo->dobj.namespace->dobj.name, dictinfo->rolname,
13858                                         dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
13859
13860         destroyPQExpBuffer(q);
13861         destroyPQExpBuffer(delq);
13862         destroyPQExpBuffer(labelq);
13863         destroyPQExpBuffer(query);
13864 }
13865
13866 /*
13867  * dumpTSTemplate
13868  *        write out a single text search template
13869  */
13870 static void
13871 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
13872 {
13873         DumpOptions *dopt = fout->dopt;
13874         PQExpBuffer q;
13875         PQExpBuffer delq;
13876         PQExpBuffer labelq;
13877
13878         /* Skip if not to be dumped */
13879         if (!tmplinfo->dobj.dump || dopt->dataOnly)
13880                 return;
13881
13882         q = createPQExpBuffer();
13883         delq = createPQExpBuffer();
13884         labelq = createPQExpBuffer();
13885
13886         /* Make sure we are in proper schema */
13887         selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
13888
13889         appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
13890                                           fmtId(tmplinfo->dobj.name));
13891
13892         if (tmplinfo->tmplinit != InvalidOid)
13893                 appendPQExpBuffer(q, "    INIT = %s,\n",
13894                                                   convertTSFunction(fout, tmplinfo->tmplinit));
13895         appendPQExpBuffer(q, "    LEXIZE = %s );\n",
13896                                           convertTSFunction(fout, tmplinfo->tmpllexize));
13897
13898         /*
13899          * DROP must be fully qualified in case same name appears in pg_catalog
13900          */
13901         appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
13902                                           fmtId(tmplinfo->dobj.namespace->dobj.name));
13903         appendPQExpBuffer(delq, ".%s;\n",
13904                                           fmtId(tmplinfo->dobj.name));
13905
13906         appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
13907                                           fmtId(tmplinfo->dobj.name));
13908
13909         if (dopt->binary_upgrade)
13910                 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
13911
13912         if (tmplinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13913                 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
13914                                          tmplinfo->dobj.name,
13915                                          tmplinfo->dobj.namespace->dobj.name,
13916                                          NULL,
13917                                          "",
13918                                          false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
13919                                          q->data, delq->data, NULL,
13920                                          NULL, 0,
13921                                          NULL, NULL);
13922
13923         /* Dump Template Comments */
13924         if (tmplinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13925                 dumpComment(fout, labelq->data,
13926                                         tmplinfo->dobj.namespace->dobj.name, "",
13927                                         tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
13928
13929         destroyPQExpBuffer(q);
13930         destroyPQExpBuffer(delq);
13931         destroyPQExpBuffer(labelq);
13932 }
13933
13934 /*
13935  * dumpTSConfig
13936  *        write out a single text search configuration
13937  */
13938 static void
13939 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
13940 {
13941         DumpOptions *dopt = fout->dopt;
13942         PQExpBuffer q;
13943         PQExpBuffer delq;
13944         PQExpBuffer labelq;
13945         PQExpBuffer query;
13946         PGresult   *res;
13947         char       *nspname;
13948         char       *prsname;
13949         int                     ntups,
13950                                 i;
13951         int                     i_tokenname;
13952         int                     i_dictname;
13953
13954         /* Skip if not to be dumped */
13955         if (!cfginfo->dobj.dump || dopt->dataOnly)
13956                 return;
13957
13958         q = createPQExpBuffer();
13959         delq = createPQExpBuffer();
13960         labelq = createPQExpBuffer();
13961         query = createPQExpBuffer();
13962
13963         /* Fetch name and namespace of the config's parser */
13964         selectSourceSchema(fout, "pg_catalog");
13965         appendPQExpBuffer(query, "SELECT nspname, prsname "
13966                                           "FROM pg_ts_parser p, pg_namespace n "
13967                                           "WHERE p.oid = '%u' AND n.oid = prsnamespace",
13968                                           cfginfo->cfgparser);
13969         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13970         nspname = PQgetvalue(res, 0, 0);
13971         prsname = PQgetvalue(res, 0, 1);
13972
13973         /* Make sure we are in proper schema */
13974         selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
13975
13976         appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
13977                                           fmtId(cfginfo->dobj.name));
13978
13979         appendPQExpBufferStr(q, "    PARSER = ");
13980         if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
13981                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
13982         appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
13983
13984         PQclear(res);
13985
13986         resetPQExpBuffer(query);
13987         appendPQExpBuffer(query,
13988                                           "SELECT\n"
13989                                           "  ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t\n"
13990                                           "    WHERE t.tokid = m.maptokentype ) AS tokenname,\n"
13991                                           "  m.mapdict::pg_catalog.regdictionary AS dictname\n"
13992                                           "FROM pg_catalog.pg_ts_config_map AS m\n"
13993                                           "WHERE m.mapcfg = '%u'\n"
13994                                           "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
13995                                           cfginfo->cfgparser, cfginfo->dobj.catId.oid);
13996
13997         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13998         ntups = PQntuples(res);
13999
14000         i_tokenname = PQfnumber(res, "tokenname");
14001         i_dictname = PQfnumber(res, "dictname");
14002
14003         for (i = 0; i < ntups; i++)
14004         {
14005                 char       *tokenname = PQgetvalue(res, i, i_tokenname);
14006                 char       *dictname = PQgetvalue(res, i, i_dictname);
14007
14008                 if (i == 0 ||
14009                         strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
14010                 {
14011                         /* starting a new token type, so start a new command */
14012                         if (i > 0)
14013                                 appendPQExpBufferStr(q, ";\n");
14014                         appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
14015                                                           fmtId(cfginfo->dobj.name));
14016                         /* tokenname needs quoting, dictname does NOT */
14017                         appendPQExpBuffer(q, "    ADD MAPPING FOR %s WITH %s",
14018                                                           fmtId(tokenname), dictname);
14019                 }
14020                 else
14021                         appendPQExpBuffer(q, ", %s", dictname);
14022         }
14023
14024         if (ntups > 0)
14025                 appendPQExpBufferStr(q, ";\n");
14026
14027         PQclear(res);
14028
14029         /*
14030          * DROP must be fully qualified in case same name appears in pg_catalog
14031          */
14032         appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
14033                                           fmtId(cfginfo->dobj.namespace->dobj.name));
14034         appendPQExpBuffer(delq, ".%s;\n",
14035                                           fmtId(cfginfo->dobj.name));
14036
14037         appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
14038                                           fmtId(cfginfo->dobj.name));
14039
14040         if (dopt->binary_upgrade)
14041                 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
14042
14043         if (cfginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14044                 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
14045                                          cfginfo->dobj.name,
14046                                          cfginfo->dobj.namespace->dobj.name,
14047                                          NULL,
14048                                          cfginfo->rolname,
14049                                          false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
14050                                          q->data, delq->data, NULL,
14051                                          NULL, 0,
14052                                          NULL, NULL);
14053
14054         /* Dump Configuration Comments */
14055         if (cfginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14056                 dumpComment(fout, labelq->data,
14057                                         cfginfo->dobj.namespace->dobj.name, cfginfo->rolname,
14058                                         cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
14059
14060         destroyPQExpBuffer(q);
14061         destroyPQExpBuffer(delq);
14062         destroyPQExpBuffer(labelq);
14063         destroyPQExpBuffer(query);
14064 }
14065
14066 /*
14067  * dumpForeignDataWrapper
14068  *        write out a single foreign-data wrapper definition
14069  */
14070 static void
14071 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
14072 {
14073         DumpOptions *dopt = fout->dopt;
14074         PQExpBuffer q;
14075         PQExpBuffer delq;
14076         PQExpBuffer labelq;
14077         char       *qfdwname;
14078
14079         /* Skip if not to be dumped */
14080         if (!fdwinfo->dobj.dump || dopt->dataOnly)
14081                 return;
14082
14083         q = createPQExpBuffer();
14084         delq = createPQExpBuffer();
14085         labelq = createPQExpBuffer();
14086
14087         qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
14088
14089         appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
14090                                           qfdwname);
14091
14092         if (strcmp(fdwinfo->fdwhandler, "-") != 0)
14093                 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
14094
14095         if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
14096                 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
14097
14098         if (strlen(fdwinfo->fdwoptions) > 0)
14099                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", fdwinfo->fdwoptions);
14100
14101         appendPQExpBufferStr(q, ";\n");
14102
14103         appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
14104                                           qfdwname);
14105
14106         appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
14107                                           qfdwname);
14108
14109         if (dopt->binary_upgrade)
14110                 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
14111
14112         if (fdwinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14113                 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14114                                          fdwinfo->dobj.name,
14115                                          NULL,
14116                                          NULL,
14117                                          fdwinfo->rolname,
14118                                          false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
14119                                          q->data, delq->data, NULL,
14120                                          NULL, 0,
14121                                          NULL, NULL);
14122
14123         /* Handle the ACL */
14124         if (fdwinfo->dobj.dump & DUMP_COMPONENT_ACL)
14125                 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14126                                 "FOREIGN DATA WRAPPER",
14127                                 qfdwname, NULL, fdwinfo->dobj.name,
14128                                 NULL, fdwinfo->rolname,
14129                                 fdwinfo->fdwacl, fdwinfo->rfdwacl,
14130                                 fdwinfo->initfdwacl, fdwinfo->initrfdwacl);
14131
14132         /* Dump Foreign Data Wrapper Comments */
14133         if (fdwinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14134                 dumpComment(fout, labelq->data,
14135                                         NULL, fdwinfo->rolname,
14136                                         fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
14137
14138         free(qfdwname);
14139
14140         destroyPQExpBuffer(q);
14141         destroyPQExpBuffer(delq);
14142         destroyPQExpBuffer(labelq);
14143 }
14144
14145 /*
14146  * dumpForeignServer
14147  *        write out a foreign server definition
14148  */
14149 static void
14150 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
14151 {
14152         DumpOptions *dopt = fout->dopt;
14153         PQExpBuffer q;
14154         PQExpBuffer delq;
14155         PQExpBuffer labelq;
14156         PQExpBuffer query;
14157         PGresult   *res;
14158         char       *qsrvname;
14159         char       *fdwname;
14160
14161         /* Skip if not to be dumped */
14162         if (!srvinfo->dobj.dump || dopt->dataOnly)
14163                 return;
14164
14165         q = createPQExpBuffer();
14166         delq = createPQExpBuffer();
14167         labelq = createPQExpBuffer();
14168         query = createPQExpBuffer();
14169
14170         qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
14171
14172         /* look up the foreign-data wrapper */
14173         selectSourceSchema(fout, "pg_catalog");
14174         appendPQExpBuffer(query, "SELECT fdwname "
14175                                           "FROM pg_foreign_data_wrapper w "
14176                                           "WHERE w.oid = '%u'",
14177                                           srvinfo->srvfdw);
14178         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14179         fdwname = PQgetvalue(res, 0, 0);
14180
14181         appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
14182         if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
14183         {
14184                 appendPQExpBufferStr(q, " TYPE ");
14185                 appendStringLiteralAH(q, srvinfo->srvtype, fout);
14186         }
14187         if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
14188         {
14189                 appendPQExpBufferStr(q, " VERSION ");
14190                 appendStringLiteralAH(q, srvinfo->srvversion, fout);
14191         }
14192
14193         appendPQExpBufferStr(q, " FOREIGN DATA WRAPPER ");
14194         appendPQExpBufferStr(q, fmtId(fdwname));
14195
14196         if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
14197                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", srvinfo->srvoptions);
14198
14199         appendPQExpBufferStr(q, ";\n");
14200
14201         appendPQExpBuffer(delq, "DROP SERVER %s;\n",
14202                                           qsrvname);
14203
14204         appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
14205
14206         if (dopt->binary_upgrade)
14207                 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
14208
14209         if (srvinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14210                 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14211                                          srvinfo->dobj.name,
14212                                          NULL,
14213                                          NULL,
14214                                          srvinfo->rolname,
14215                                          false, "SERVER", SECTION_PRE_DATA,
14216                                          q->data, delq->data, NULL,
14217                                          NULL, 0,
14218                                          NULL, NULL);
14219
14220         /* Handle the ACL */
14221         if (srvinfo->dobj.dump & DUMP_COMPONENT_ACL)
14222                 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
14223                                 "FOREIGN SERVER",
14224                                 qsrvname, NULL, srvinfo->dobj.name,
14225                                 NULL, srvinfo->rolname,
14226                                 srvinfo->srvacl, srvinfo->rsrvacl,
14227                                 srvinfo->initsrvacl, srvinfo->initrsrvacl);
14228
14229         /* Dump user mappings */
14230         if (srvinfo->dobj.dump & DUMP_COMPONENT_USERMAP)
14231                 dumpUserMappings(fout,
14232                                                  srvinfo->dobj.name, NULL,
14233                                                  srvinfo->rolname,
14234                                                  srvinfo->dobj.catId, srvinfo->dobj.dumpId);
14235
14236         /* Dump Foreign Server Comments */
14237         if (srvinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14238                 dumpComment(fout, labelq->data,
14239                                         NULL, srvinfo->rolname,
14240                                         srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
14241
14242         free(qsrvname);
14243
14244         destroyPQExpBuffer(q);
14245         destroyPQExpBuffer(delq);
14246         destroyPQExpBuffer(labelq);
14247         destroyPQExpBuffer(query);
14248 }
14249
14250 /*
14251  * dumpUserMappings
14252  *
14253  * This routine is used to dump any user mappings associated with the
14254  * server handed to this routine. Should be called after ArchiveEntry()
14255  * for the server.
14256  */
14257 static void
14258 dumpUserMappings(Archive *fout,
14259                                  const char *servername, const char *namespace,
14260                                  const char *owner,
14261                                  CatalogId catalogId, DumpId dumpId)
14262 {
14263         PQExpBuffer q;
14264         PQExpBuffer delq;
14265         PQExpBuffer query;
14266         PQExpBuffer tag;
14267         PGresult   *res;
14268         int                     ntups;
14269         int                     i_usename;
14270         int                     i_umoptions;
14271         int                     i;
14272
14273         q = createPQExpBuffer();
14274         tag = createPQExpBuffer();
14275         delq = createPQExpBuffer();
14276         query = createPQExpBuffer();
14277
14278         /*
14279          * We read from the publicly accessible view pg_user_mappings, so as not
14280          * to fail if run by a non-superuser.  Note that the view will show
14281          * umoptions as null if the user hasn't got privileges for the associated
14282          * server; this means that pg_dump will dump such a mapping, but with no
14283          * OPTIONS clause.  A possible alternative is to skip such mappings
14284          * altogether, but it's not clear that that's an improvement.
14285          */
14286         selectSourceSchema(fout, "pg_catalog");
14287
14288         appendPQExpBuffer(query,
14289                                           "SELECT usename, "
14290                                           "array_to_string(ARRAY("
14291                                           "SELECT quote_ident(option_name) || ' ' || "
14292                                           "quote_literal(option_value) "
14293                                           "FROM pg_options_to_table(umoptions) "
14294                                           "ORDER BY option_name"
14295                                           "), E',\n    ') AS umoptions "
14296                                           "FROM pg_user_mappings "
14297                                           "WHERE srvid = '%u' "
14298                                           "ORDER BY usename",
14299                                           catalogId.oid);
14300
14301         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14302
14303         ntups = PQntuples(res);
14304         i_usename = PQfnumber(res, "usename");
14305         i_umoptions = PQfnumber(res, "umoptions");
14306
14307         for (i = 0; i < ntups; i++)
14308         {
14309                 char       *usename;
14310                 char       *umoptions;
14311
14312                 usename = PQgetvalue(res, i, i_usename);
14313                 umoptions = PQgetvalue(res, i, i_umoptions);
14314
14315                 resetPQExpBuffer(q);
14316                 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
14317                 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
14318
14319                 if (umoptions && strlen(umoptions) > 0)
14320                         appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", umoptions);
14321
14322                 appendPQExpBufferStr(q, ";\n");
14323
14324                 resetPQExpBuffer(delq);
14325                 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
14326                 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
14327
14328                 resetPQExpBuffer(tag);
14329                 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
14330                                                   usename, servername);
14331
14332                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14333                                          tag->data,
14334                                          namespace,
14335                                          NULL,
14336                                          owner, false,
14337                                          "USER MAPPING", SECTION_PRE_DATA,
14338                                          q->data, delq->data, NULL,
14339                                          &dumpId, 1,
14340                                          NULL, NULL);
14341         }
14342
14343         PQclear(res);
14344
14345         destroyPQExpBuffer(query);
14346         destroyPQExpBuffer(delq);
14347         destroyPQExpBuffer(tag);
14348         destroyPQExpBuffer(q);
14349 }
14350
14351 /*
14352  * Write out default privileges information
14353  */
14354 static void
14355 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
14356 {
14357         DumpOptions *dopt = fout->dopt;
14358         PQExpBuffer q;
14359         PQExpBuffer tag;
14360         const char *type;
14361
14362         /* Skip if not to be dumped */
14363         if (!daclinfo->dobj.dump || dopt->dataOnly || dopt->aclsSkip)
14364                 return;
14365
14366         q = createPQExpBuffer();
14367         tag = createPQExpBuffer();
14368
14369         switch (daclinfo->defaclobjtype)
14370         {
14371                 case DEFACLOBJ_RELATION:
14372                         type = "TABLES";
14373                         break;
14374                 case DEFACLOBJ_SEQUENCE:
14375                         type = "SEQUENCES";
14376                         break;
14377                 case DEFACLOBJ_FUNCTION:
14378                         type = "FUNCTIONS";
14379                         break;
14380                 case DEFACLOBJ_TYPE:
14381                         type = "TYPES";
14382                         break;
14383                 case DEFACLOBJ_NAMESPACE:
14384                         type = "SCHEMAS";
14385                         break;
14386                 default:
14387                         /* shouldn't get here */
14388                         exit_horribly(NULL,
14389                                                   "unrecognized object type in default privileges: %d\n",
14390                                                   (int) daclinfo->defaclobjtype);
14391                         type = "";                      /* keep compiler quiet */
14392         }
14393
14394         appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
14395
14396         /* build the actual command(s) for this tuple */
14397         if (!buildDefaultACLCommands(type,
14398                                                                  daclinfo->dobj.namespace != NULL ?
14399                                                                  daclinfo->dobj.namespace->dobj.name : NULL,
14400                                                                  daclinfo->defaclacl,
14401                                                                  daclinfo->rdefaclacl,
14402                                                                  daclinfo->initdefaclacl,
14403                                                                  daclinfo->initrdefaclacl,
14404                                                                  daclinfo->defaclrole,
14405                                                                  fout->remoteVersion,
14406                                                                  q))
14407                 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
14408                                           daclinfo->defaclacl);
14409
14410         if (daclinfo->dobj.dump & DUMP_COMPONENT_ACL)
14411                 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
14412                                          tag->data,
14413                                          daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
14414                                          NULL,
14415                                          daclinfo->defaclrole,
14416                                          false, "DEFAULT ACL", SECTION_POST_DATA,
14417                                          q->data, "", NULL,
14418                                          NULL, 0,
14419                                          NULL, NULL);
14420
14421         destroyPQExpBuffer(tag);
14422         destroyPQExpBuffer(q);
14423 }
14424
14425 /*----------
14426  * Write out grant/revoke information
14427  *
14428  * 'objCatId' is the catalog ID of the underlying object.
14429  * 'objDumpId' is the dump ID of the underlying object.
14430  * 'type' must be one of
14431  *              TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
14432  *              FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
14433  * 'name' is the formatted name of the object.  Must be quoted etc. already.
14434  * 'subname' is the formatted name of the sub-object, if any.  Must be quoted.
14435  * 'tag' is the tag for the archive entry (typ. unquoted name of object).
14436  * 'nspname' is the namespace the object is in (NULL if none).
14437  * 'owner' is the owner, NULL if there is no owner (for languages).
14438  * 'acls' contains the ACL string of the object from the appropriate system
14439  *              catalog field; it will be passed to buildACLCommands for building the
14440  *              appropriate GRANT commands.
14441  * 'racls' contains the ACL string of any initial-but-now-revoked ACLs of the
14442  *              object; it will be passed to buildACLCommands for building the
14443  *              appropriate REVOKE commands.
14444  * 'initacls' In binary-upgrade mode, ACL string of the object's initial
14445  *              privileges, to be recorded into pg_init_privs
14446  * 'initracls' In binary-upgrade mode, ACL string of the object's
14447  *              revoked-from-default privileges, to be recorded into pg_init_privs
14448  *
14449  * NB: initacls/initracls are needed because extensions can set privileges on
14450  * an object during the extension's script file and we record those into
14451  * pg_init_privs as that object's initial privileges.
14452  *----------
14453  */
14454 static void
14455 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
14456                 const char *type, const char *name, const char *subname,
14457                 const char *tag, const char *nspname, const char *owner,
14458                 const char *acls, const char *racls,
14459                 const char *initacls, const char *initracls)
14460 {
14461         DumpOptions *dopt = fout->dopt;
14462         PQExpBuffer sql;
14463
14464         /* Do nothing if ACL dump is not enabled */
14465         if (dopt->aclsSkip)
14466                 return;
14467
14468         /* --data-only skips ACLs *except* BLOB ACLs */
14469         if (dopt->dataOnly && strcmp(type, "LARGE OBJECT") != 0)
14470                 return;
14471
14472         sql = createPQExpBuffer();
14473
14474         /*
14475          * Check to see if this object has had any initial ACLs included for it.
14476          * If so, we are in binary upgrade mode and these are the ACLs to turn
14477          * into GRANT and REVOKE statements to set and record the initial
14478          * privileges for an extension object.  Let the backend know that these
14479          * are to be recorded by calling binary_upgrade_set_record_init_privs()
14480          * before and after.
14481          */
14482         if (strlen(initacls) != 0 || strlen(initracls) != 0)
14483         {
14484                 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(true);\n");
14485                 if (!buildACLCommands(name, subname, type, initacls, initracls, owner,
14486                                                           "", fout->remoteVersion, sql))
14487                         exit_horribly(NULL,
14488                                                   "could not parse initial GRANT ACL list (%s) or initial REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14489                                                   initacls, initracls, name, type);
14490                 appendPQExpBuffer(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(false);\n");
14491         }
14492
14493         if (!buildACLCommands(name, subname, type, acls, racls, owner,
14494                                                   "", fout->remoteVersion, sql))
14495                 exit_horribly(NULL,
14496                                           "could not parse GRANT ACL list (%s) or REVOKE ACL list (%s) for object \"%s\" (%s)\n",
14497                                           acls, racls, name, type);
14498
14499         if (sql->len > 0)
14500                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14501                                          tag, nspname,
14502                                          NULL,
14503                                          owner ? owner : "",
14504                                          false, "ACL", SECTION_NONE,
14505                                          sql->data, "", NULL,
14506                                          &(objDumpId), 1,
14507                                          NULL, NULL);
14508
14509         destroyPQExpBuffer(sql);
14510 }
14511
14512 /*
14513  * dumpSecLabel
14514  *
14515  * This routine is used to dump any security labels associated with the
14516  * object handed to this routine. The routine takes a constant character
14517  * string for the target part of the security-label command, plus
14518  * the namespace and owner of the object (for labeling the ArchiveEntry),
14519  * plus catalog ID and subid which are the lookup key for pg_seclabel,
14520  * plus the dump ID for the object (for setting a dependency).
14521  * If a matching pg_seclabel entry is found, it is dumped.
14522  *
14523  * Note: although this routine takes a dumpId for dependency purposes,
14524  * that purpose is just to mark the dependency in the emitted dump file
14525  * for possible future use by pg_restore.  We do NOT use it for determining
14526  * ordering of the label in the dump file, because this routine is called
14527  * after dependency sorting occurs.  This routine should be called just after
14528  * calling ArchiveEntry() for the specified object.
14529  */
14530 static void
14531 dumpSecLabel(Archive *fout, const char *target,
14532                          const char *namespace, const char *owner,
14533                          CatalogId catalogId, int subid, DumpId dumpId)
14534 {
14535         DumpOptions *dopt = fout->dopt;
14536         SecLabelItem *labels;
14537         int                     nlabels;
14538         int                     i;
14539         PQExpBuffer query;
14540
14541         /* do nothing, if --no-security-labels is supplied */
14542         if (dopt->no_security_labels)
14543                 return;
14544
14545         /* Comments are schema not data ... except blob comments are data */
14546         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
14547         {
14548                 if (dopt->dataOnly)
14549                         return;
14550         }
14551         else
14552         {
14553                 /* We do dump blob security labels in binary-upgrade mode */
14554                 if (dopt->schemaOnly && !dopt->binary_upgrade)
14555                         return;
14556         }
14557
14558         /* Search for security labels associated with catalogId, using table */
14559         nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
14560
14561         query = createPQExpBuffer();
14562
14563         for (i = 0; i < nlabels; i++)
14564         {
14565                 /*
14566                  * Ignore label entries for which the subid doesn't match.
14567                  */
14568                 if (labels[i].objsubid != subid)
14569                         continue;
14570
14571                 appendPQExpBuffer(query,
14572                                                   "SECURITY LABEL FOR %s ON %s IS ",
14573                                                   fmtId(labels[i].provider), target);
14574                 appendStringLiteralAH(query, labels[i].label, fout);
14575                 appendPQExpBufferStr(query, ";\n");
14576         }
14577
14578         if (query->len > 0)
14579         {
14580                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14581                                          target, namespace, NULL, owner,
14582                                          false, "SECURITY LABEL", SECTION_NONE,
14583                                          query->data, "", NULL,
14584                                          &(dumpId), 1,
14585                                          NULL, NULL);
14586         }
14587         destroyPQExpBuffer(query);
14588 }
14589
14590 /*
14591  * dumpTableSecLabel
14592  *
14593  * As above, but dump security label for both the specified table (or view)
14594  * and its columns.
14595  */
14596 static void
14597 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
14598 {
14599         DumpOptions *dopt = fout->dopt;
14600         SecLabelItem *labels;
14601         int                     nlabels;
14602         int                     i;
14603         PQExpBuffer query;
14604         PQExpBuffer target;
14605
14606         /* do nothing, if --no-security-labels is supplied */
14607         if (dopt->no_security_labels)
14608                 return;
14609
14610         /* SecLabel are SCHEMA not data */
14611         if (dopt->dataOnly)
14612                 return;
14613
14614         /* Search for comments associated with relation, using table */
14615         nlabels = findSecLabels(fout,
14616                                                         tbinfo->dobj.catId.tableoid,
14617                                                         tbinfo->dobj.catId.oid,
14618                                                         &labels);
14619
14620         /* If security labels exist, build SECURITY LABEL statements */
14621         if (nlabels <= 0)
14622                 return;
14623
14624         query = createPQExpBuffer();
14625         target = createPQExpBuffer();
14626
14627         for (i = 0; i < nlabels; i++)
14628         {
14629                 const char *colname;
14630                 const char *provider = labels[i].provider;
14631                 const char *label = labels[i].label;
14632                 int                     objsubid = labels[i].objsubid;
14633
14634                 resetPQExpBuffer(target);
14635                 if (objsubid == 0)
14636                 {
14637                         appendPQExpBuffer(target, "%s %s", reltypename,
14638                                                           fmtId(tbinfo->dobj.name));
14639                 }
14640                 else
14641                 {
14642                         colname = getAttrName(objsubid, tbinfo);
14643                         /* first fmtId result must be consumed before calling it again */
14644                         appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
14645                         appendPQExpBuffer(target, ".%s", fmtId(colname));
14646                 }
14647                 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
14648                                                   fmtId(provider), target->data);
14649                 appendStringLiteralAH(query, label, fout);
14650                 appendPQExpBufferStr(query, ";\n");
14651         }
14652         if (query->len > 0)
14653         {
14654                 resetPQExpBuffer(target);
14655                 appendPQExpBuffer(target, "%s %s", reltypename,
14656                                                   fmtId(tbinfo->dobj.name));
14657                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14658                                          target->data,
14659                                          tbinfo->dobj.namespace->dobj.name,
14660                                          NULL, tbinfo->rolname,
14661                                          false, "SECURITY LABEL", SECTION_NONE,
14662                                          query->data, "", NULL,
14663                                          &(tbinfo->dobj.dumpId), 1,
14664                                          NULL, NULL);
14665         }
14666         destroyPQExpBuffer(query);
14667         destroyPQExpBuffer(target);
14668 }
14669
14670 /*
14671  * findSecLabels
14672  *
14673  * Find the security label(s), if any, associated with the given object.
14674  * All the objsubid values associated with the given classoid/objoid are
14675  * found with one search.
14676  */
14677 static int
14678 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
14679 {
14680         /* static storage for table of security labels */
14681         static SecLabelItem *labels = NULL;
14682         static int      nlabels = -1;
14683
14684         SecLabelItem *middle = NULL;
14685         SecLabelItem *low;
14686         SecLabelItem *high;
14687         int                     nmatch;
14688
14689         /* Get security labels if we didn't already */
14690         if (nlabels < 0)
14691                 nlabels = collectSecLabels(fout, &labels);
14692
14693         if (nlabels <= 0)                       /* no labels, so no match is possible */
14694         {
14695                 *items = NULL;
14696                 return 0;
14697         }
14698
14699         /*
14700          * Do binary search to find some item matching the object.
14701          */
14702         low = &labels[0];
14703         high = &labels[nlabels - 1];
14704         while (low <= high)
14705         {
14706                 middle = low + (high - low) / 2;
14707
14708                 if (classoid < middle->classoid)
14709                         high = middle - 1;
14710                 else if (classoid > middle->classoid)
14711                         low = middle + 1;
14712                 else if (objoid < middle->objoid)
14713                         high = middle - 1;
14714                 else if (objoid > middle->objoid)
14715                         low = middle + 1;
14716                 else
14717                         break;                          /* found a match */
14718         }
14719
14720         if (low > high)                         /* no matches */
14721         {
14722                 *items = NULL;
14723                 return 0;
14724         }
14725
14726         /*
14727          * Now determine how many items match the object.  The search loop
14728          * invariant still holds: only items between low and high inclusive could
14729          * match.
14730          */
14731         nmatch = 1;
14732         while (middle > low)
14733         {
14734                 if (classoid != middle[-1].classoid ||
14735                         objoid != middle[-1].objoid)
14736                         break;
14737                 middle--;
14738                 nmatch++;
14739         }
14740
14741         *items = middle;
14742
14743         middle += nmatch;
14744         while (middle <= high)
14745         {
14746                 if (classoid != middle->classoid ||
14747                         objoid != middle->objoid)
14748                         break;
14749                 middle++;
14750                 nmatch++;
14751         }
14752
14753         return nmatch;
14754 }
14755
14756 /*
14757  * collectSecLabels
14758  *
14759  * Construct a table of all security labels available for database objects.
14760  * It's much faster to pull them all at once.
14761  *
14762  * The table is sorted by classoid/objid/objsubid for speed in lookup.
14763  */
14764 static int
14765 collectSecLabels(Archive *fout, SecLabelItem **items)
14766 {
14767         PGresult   *res;
14768         PQExpBuffer query;
14769         int                     i_label;
14770         int                     i_provider;
14771         int                     i_classoid;
14772         int                     i_objoid;
14773         int                     i_objsubid;
14774         int                     ntups;
14775         int                     i;
14776         SecLabelItem *labels;
14777
14778         query = createPQExpBuffer();
14779
14780         appendPQExpBufferStr(query,
14781                                                  "SELECT label, provider, classoid, objoid, objsubid "
14782                                                  "FROM pg_catalog.pg_seclabel "
14783                                                  "ORDER BY classoid, objoid, objsubid");
14784
14785         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14786
14787         /* Construct lookup table containing OIDs in numeric form */
14788         i_label = PQfnumber(res, "label");
14789         i_provider = PQfnumber(res, "provider");
14790         i_classoid = PQfnumber(res, "classoid");
14791         i_objoid = PQfnumber(res, "objoid");
14792         i_objsubid = PQfnumber(res, "objsubid");
14793
14794         ntups = PQntuples(res);
14795
14796         labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
14797
14798         for (i = 0; i < ntups; i++)
14799         {
14800                 labels[i].label = PQgetvalue(res, i, i_label);
14801                 labels[i].provider = PQgetvalue(res, i, i_provider);
14802                 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
14803                 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
14804                 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
14805         }
14806
14807         /* Do NOT free the PGresult since we are keeping pointers into it */
14808         destroyPQExpBuffer(query);
14809
14810         *items = labels;
14811         return ntups;
14812 }
14813
14814 /*
14815  * dumpTable
14816  *        write out to fout the declarations (not data) of a user-defined table
14817  */
14818 static void
14819 dumpTable(Archive *fout, TableInfo *tbinfo)
14820 {
14821         DumpOptions *dopt = fout->dopt;
14822         char       *namecopy;
14823
14824         /*
14825          * noop if we are not dumping anything about this table, or if we are
14826          * doing a data-only dump
14827          */
14828         if (!tbinfo->dobj.dump || dopt->dataOnly)
14829                 return;
14830
14831         if (tbinfo->relkind == RELKIND_SEQUENCE)
14832                 dumpSequence(fout, tbinfo);
14833         else
14834                 dumpTableSchema(fout, tbinfo);
14835
14836         /* Handle the ACL here */
14837         namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
14838         if (tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
14839                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
14840                                 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
14841                                 "TABLE",
14842                                 namecopy, NULL, tbinfo->dobj.name,
14843                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
14844                                 tbinfo->relacl, tbinfo->rrelacl,
14845                                 tbinfo->initrelacl, tbinfo->initrrelacl);
14846
14847         /*
14848          * Handle column ACLs, if any.  Note: we pull these with a separate query
14849          * rather than trying to fetch them during getTableAttrs, so that we won't
14850          * miss ACLs on system columns.
14851          */
14852         if (fout->remoteVersion >= 80400 && tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
14853         {
14854                 PQExpBuffer query = createPQExpBuffer();
14855                 PGresult   *res;
14856                 int                     i;
14857
14858                 if (fout->remoteVersion >= 90600)
14859                 {
14860                         PQExpBuffer acl_subquery = createPQExpBuffer();
14861                         PQExpBuffer racl_subquery = createPQExpBuffer();
14862                         PQExpBuffer initacl_subquery = createPQExpBuffer();
14863                         PQExpBuffer initracl_subquery = createPQExpBuffer();
14864
14865                         buildACLQueries(acl_subquery, racl_subquery, initacl_subquery,
14866                                                         initracl_subquery, "at.attacl", "c.relowner", "'c'",
14867                                                         dopt->binary_upgrade);
14868
14869                         appendPQExpBuffer(query,
14870                                                           "SELECT at.attname, "
14871                                                           "%s AS attacl, "
14872                                                           "%s AS rattacl, "
14873                                                           "%s AS initattacl, "
14874                                                           "%s AS initrattacl "
14875                                                           "FROM pg_catalog.pg_attribute at "
14876                                                           "JOIN pg_catalog.pg_class c ON (at.attrelid = c.oid) "
14877                                                           "LEFT JOIN pg_catalog.pg_init_privs pip ON "
14878                                                           "(at.attrelid = pip.objoid "
14879                                                           "AND pip.classoid = 'pg_catalog.pg_class'::pg_catalog.regclass "
14880                                                           "AND at.attnum = pip.objsubid) "
14881                                                           "WHERE at.attrelid = '%u'::pg_catalog.oid AND "
14882                                                           "NOT at.attisdropped "
14883                                                           "AND ("
14884                                                           "%s IS NOT NULL OR "
14885                                                           "%s IS NOT NULL OR "
14886                                                           "%s IS NOT NULL OR "
14887                                                           "%s IS NOT NULL)"
14888                                                           "ORDER BY at.attnum",
14889                                                           acl_subquery->data,
14890                                                           racl_subquery->data,
14891                                                           initacl_subquery->data,
14892                                                           initracl_subquery->data,
14893                                                           tbinfo->dobj.catId.oid,
14894                                                           acl_subquery->data,
14895                                                           racl_subquery->data,
14896                                                           initacl_subquery->data,
14897                                                           initracl_subquery->data);
14898
14899                         destroyPQExpBuffer(acl_subquery);
14900                         destroyPQExpBuffer(racl_subquery);
14901                         destroyPQExpBuffer(initacl_subquery);
14902                         destroyPQExpBuffer(initracl_subquery);
14903                 }
14904                 else
14905                 {
14906                         appendPQExpBuffer(query,
14907                                                           "SELECT attname, attacl, NULL as rattacl, "
14908                                                           "NULL AS initattacl, NULL AS initrattacl "
14909                                                           "FROM pg_catalog.pg_attribute "
14910                                                           "WHERE attrelid = '%u'::pg_catalog.oid AND NOT attisdropped "
14911                                                           "AND attacl IS NOT NULL "
14912                                                           "ORDER BY attnum",
14913                                                           tbinfo->dobj.catId.oid);
14914                 }
14915
14916                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14917
14918                 for (i = 0; i < PQntuples(res); i++)
14919                 {
14920                         char       *attname = PQgetvalue(res, i, 0);
14921                         char       *attacl = PQgetvalue(res, i, 1);
14922                         char       *rattacl = PQgetvalue(res, i, 2);
14923                         char       *initattacl = PQgetvalue(res, i, 3);
14924                         char       *initrattacl = PQgetvalue(res, i, 4);
14925                         char       *attnamecopy;
14926                         char       *acltag;
14927
14928                         attnamecopy = pg_strdup(fmtId(attname));
14929                         acltag = psprintf("%s.%s", tbinfo->dobj.name, attname);
14930                         /* Column's GRANT type is always TABLE */
14931                         dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
14932                                         namecopy, attnamecopy, acltag,
14933                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
14934                                         attacl, rattacl, initattacl, initrattacl);
14935                         free(attnamecopy);
14936                         free(acltag);
14937                 }
14938                 PQclear(res);
14939                 destroyPQExpBuffer(query);
14940         }
14941
14942         free(namecopy);
14943
14944         return;
14945 }
14946
14947 /*
14948  * Create the AS clause for a view or materialized view. The semicolon is
14949  * stripped because a materialized view must add a WITH NO DATA clause.
14950  *
14951  * This returns a new buffer which must be freed by the caller.
14952  */
14953 static PQExpBuffer
14954 createViewAsClause(Archive *fout, TableInfo *tbinfo)
14955 {
14956         PQExpBuffer query = createPQExpBuffer();
14957         PQExpBuffer result = createPQExpBuffer();
14958         PGresult   *res;
14959         int                     len;
14960
14961         /* Fetch the view definition */
14962         appendPQExpBuffer(query,
14963                                           "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
14964                                           tbinfo->dobj.catId.oid);
14965
14966         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14967
14968         if (PQntuples(res) != 1)
14969         {
14970                 if (PQntuples(res) < 1)
14971                         exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
14972                                                   tbinfo->dobj.name);
14973                 else
14974                         exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
14975                                                   tbinfo->dobj.name);
14976         }
14977
14978         len = PQgetlength(res, 0, 0);
14979
14980         if (len == 0)
14981                 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
14982                                           tbinfo->dobj.name);
14983
14984         /* Strip off the trailing semicolon so that other things may follow. */
14985         Assert(PQgetvalue(res, 0, 0)[len - 1] == ';');
14986         appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
14987
14988         PQclear(res);
14989         destroyPQExpBuffer(query);
14990
14991         return result;
14992 }
14993
14994 /*
14995  * Create a dummy AS clause for a view.  This is used when the real view
14996  * definition has to be postponed because of circular dependencies.
14997  * We must duplicate the view's external properties -- column names and types
14998  * (including collation) -- so that it works for subsequent references.
14999  *
15000  * This returns a new buffer which must be freed by the caller.
15001  */
15002 static PQExpBuffer
15003 createDummyViewAsClause(Archive *fout, TableInfo *tbinfo)
15004 {
15005         PQExpBuffer result = createPQExpBuffer();
15006         int                     j;
15007
15008         appendPQExpBufferStr(result, "SELECT");
15009
15010         for (j = 0; j < tbinfo->numatts; j++)
15011         {
15012                 if (j > 0)
15013                         appendPQExpBufferChar(result, ',');
15014                 appendPQExpBufferStr(result, "\n    ");
15015
15016                 appendPQExpBuffer(result, "NULL::%s", tbinfo->atttypnames[j]);
15017
15018                 /*
15019                  * Must add collation if not default for the type, because CREATE OR
15020                  * REPLACE VIEW won't change it
15021                  */
15022                 if (OidIsValid(tbinfo->attcollation[j]))
15023                 {
15024                         CollInfo   *coll;
15025
15026                         coll = findCollationByOid(tbinfo->attcollation[j]);
15027                         if (coll)
15028                         {
15029                                 /* always schema-qualify, don't try to be smart */
15030                                 appendPQExpBuffer(result, " COLLATE %s.",
15031                                                                   fmtId(coll->dobj.namespace->dobj.name));
15032                                 appendPQExpBufferStr(result, fmtId(coll->dobj.name));
15033                         }
15034                 }
15035
15036                 appendPQExpBuffer(result, " AS %s", fmtId(tbinfo->attnames[j]));
15037         }
15038
15039         return result;
15040 }
15041
15042 /*
15043  * dumpTableSchema
15044  *        write the declaration (not data) of one user-defined table or view
15045  */
15046 static void
15047 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
15048 {
15049         DumpOptions *dopt = fout->dopt;
15050         PQExpBuffer q = createPQExpBuffer();
15051         PQExpBuffer delq = createPQExpBuffer();
15052         PQExpBuffer labelq = createPQExpBuffer();
15053         int                     numParents;
15054         TableInfo **parents;
15055         int                     actual_atts;    /* number of attrs in this CREATE statement */
15056         const char *reltypename;
15057         char       *storage;
15058         char       *srvname;
15059         char       *ftoptions;
15060         int                     j,
15061                                 k;
15062
15063         /* Make sure we are in proper schema */
15064         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
15065
15066         if (dopt->binary_upgrade)
15067                 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
15068                                                                                                 tbinfo->dobj.catId.oid);
15069
15070         /* Is it a table or a view? */
15071         if (tbinfo->relkind == RELKIND_VIEW)
15072         {
15073                 PQExpBuffer result;
15074
15075                 /*
15076                  * Note: keep this code in sync with the is_view case in dumpRule()
15077                  */
15078
15079                 reltypename = "VIEW";
15080
15081                 /*
15082                  * DROP must be fully qualified in case same name appears in
15083                  * pg_catalog
15084                  */
15085                 appendPQExpBuffer(delq, "DROP VIEW %s.",
15086                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
15087                 appendPQExpBuffer(delq, "%s;\n",
15088                                                   fmtId(tbinfo->dobj.name));
15089
15090                 if (dopt->binary_upgrade)
15091                         binary_upgrade_set_pg_class_oids(fout, q,
15092                                                                                          tbinfo->dobj.catId.oid, false);
15093
15094                 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
15095                 if (tbinfo->dummy_view)
15096                         result = createDummyViewAsClause(fout, tbinfo);
15097                 else
15098                 {
15099                         if (nonemptyReloptions(tbinfo->reloptions))
15100                         {
15101                                 appendPQExpBufferStr(q, " WITH (");
15102                                 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15103                                 appendPQExpBufferChar(q, ')');
15104                         }
15105                         result = createViewAsClause(fout, tbinfo);
15106                 }
15107                 appendPQExpBuffer(q, " AS\n%s", result->data);
15108                 destroyPQExpBuffer(result);
15109
15110                 if (tbinfo->checkoption != NULL && !tbinfo->dummy_view)
15111                         appendPQExpBuffer(q, "\n  WITH %s CHECK OPTION", tbinfo->checkoption);
15112                 appendPQExpBufferStr(q, ";\n");
15113
15114                 appendPQExpBuffer(labelq, "VIEW %s",
15115                                                   fmtId(tbinfo->dobj.name));
15116         }
15117         else
15118         {
15119                 switch (tbinfo->relkind)
15120                 {
15121                         case RELKIND_FOREIGN_TABLE:
15122                                 {
15123                                         PQExpBuffer query = createPQExpBuffer();
15124                                         PGresult   *res;
15125                                         int                     i_srvname;
15126                                         int                     i_ftoptions;
15127
15128                                         reltypename = "FOREIGN TABLE";
15129
15130                                         /* retrieve name of foreign server and generic options */
15131                                         appendPQExpBuffer(query,
15132                                                                           "SELECT fs.srvname, "
15133                                                                           "pg_catalog.array_to_string(ARRAY("
15134                                                                           "SELECT pg_catalog.quote_ident(option_name) || "
15135                                                                           "' ' || pg_catalog.quote_literal(option_value) "
15136                                                                           "FROM pg_catalog.pg_options_to_table(ftoptions) "
15137                                                                           "ORDER BY option_name"
15138                                                                           "), E',\n    ') AS ftoptions "
15139                                                                           "FROM pg_catalog.pg_foreign_table ft "
15140                                                                           "JOIN pg_catalog.pg_foreign_server fs "
15141                                                                           "ON (fs.oid = ft.ftserver) "
15142                                                                           "WHERE ft.ftrelid = '%u'",
15143                                                                           tbinfo->dobj.catId.oid);
15144                                         res = ExecuteSqlQueryForSingleRow(fout, query->data);
15145                                         i_srvname = PQfnumber(res, "srvname");
15146                                         i_ftoptions = PQfnumber(res, "ftoptions");
15147                                         srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
15148                                         ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
15149                                         PQclear(res);
15150                                         destroyPQExpBuffer(query);
15151                                         break;
15152                                 }
15153                         case RELKIND_MATVIEW:
15154                                 reltypename = "MATERIALIZED VIEW";
15155                                 srvname = NULL;
15156                                 ftoptions = NULL;
15157                                 break;
15158                         default:
15159                                 reltypename = "TABLE";
15160                                 srvname = NULL;
15161                                 ftoptions = NULL;
15162                 }
15163
15164                 numParents = tbinfo->numParents;
15165                 parents = tbinfo->parents;
15166
15167                 /*
15168                  * DROP must be fully qualified in case same name appears in
15169                  * pg_catalog
15170                  */
15171                 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
15172                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
15173                 appendPQExpBuffer(delq, "%s;\n",
15174                                                   fmtId(tbinfo->dobj.name));
15175
15176                 appendPQExpBuffer(labelq, "%s %s", reltypename,
15177                                                   fmtId(tbinfo->dobj.name));
15178
15179                 if (dopt->binary_upgrade)
15180                         binary_upgrade_set_pg_class_oids(fout, q,
15181                                                                                          tbinfo->dobj.catId.oid, false);
15182
15183                 appendPQExpBuffer(q, "CREATE %s%s %s",
15184                                                   tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
15185                                                   "UNLOGGED " : "",
15186                                                   reltypename,
15187                                                   fmtId(tbinfo->dobj.name));
15188
15189                 /*
15190                  * Attach to type, if reloftype; except in case of a binary upgrade,
15191                  * we dump the table normally and attach it to the type afterward.
15192                  */
15193                 if (tbinfo->reloftype && !dopt->binary_upgrade)
15194                         appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
15195
15196                 /*
15197                  * If the table is a partition, dump it as such; except in the case of
15198                  * a binary upgrade, we dump the table normally and attach it to the
15199                  * parent afterward.
15200                  */
15201                 if (tbinfo->ispartition && !dopt->binary_upgrade)
15202                 {
15203                         TableInfo  *parentRel = tbinfo->parents[0];
15204
15205                         /*
15206                          * With partitions, unlike inheritance, there can only be one
15207                          * parent.
15208                          */
15209                         if (tbinfo->numParents != 1)
15210                                 exit_horribly(NULL, "invalid number of parents %d for table \"%s\"\n",
15211                                                           tbinfo->numParents, tbinfo->dobj.name);
15212
15213                         appendPQExpBuffer(q, " PARTITION OF ");
15214                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
15215                                 appendPQExpBuffer(q, "%s.",
15216                                                                   fmtId(parentRel->dobj.namespace->dobj.name));
15217                         appendPQExpBufferStr(q, fmtId(parentRel->dobj.name));
15218                 }
15219
15220                 if (tbinfo->relkind != RELKIND_MATVIEW)
15221                 {
15222                         /* Dump the attributes */
15223                         actual_atts = 0;
15224                         for (j = 0; j < tbinfo->numatts; j++)
15225                         {
15226                                 /*
15227                                  * Normally, dump if it's locally defined in this table, and
15228                                  * not dropped.  But for binary upgrade, we'll dump all the
15229                                  * columns, and then fix up the dropped and nonlocal cases
15230                                  * below.
15231                                  */
15232                                 if (shouldPrintColumn(dopt, tbinfo, j))
15233                                 {
15234                                         /*
15235                                          * Default value --- suppress if to be printed separately.
15236                                          */
15237                                         bool            has_default = (tbinfo->attrdefs[j] != NULL &&
15238                                                                                            !tbinfo->attrdefs[j]->separate);
15239
15240                                         /*
15241                                          * Not Null constraint --- suppress if inherited, except
15242                                          * in binary-upgrade case where that won't work.
15243                                          */
15244                                         bool            has_notnull = (tbinfo->notnull[j] &&
15245                                                                                            (!tbinfo->inhNotNull[j] ||
15246                                                                                                 dopt->binary_upgrade));
15247
15248                                         /*
15249                                          * Skip column if fully defined by reloftype or the
15250                                          * partition parent.
15251                                          */
15252                                         if ((tbinfo->reloftype || tbinfo->ispartition) &&
15253                                                 !has_default && !has_notnull && !dopt->binary_upgrade)
15254                                                 continue;
15255
15256                                         /* Format properly if not first attr */
15257                                         if (actual_atts == 0)
15258                                                 appendPQExpBufferStr(q, " (");
15259                                         else
15260                                                 appendPQExpBufferChar(q, ',');
15261                                         appendPQExpBufferStr(q, "\n    ");
15262                                         actual_atts++;
15263
15264                                         /* Attribute name */
15265                                         appendPQExpBufferStr(q, fmtId(tbinfo->attnames[j]));
15266
15267                                         if (tbinfo->attisdropped[j])
15268                                         {
15269                                                 /*
15270                                                  * ALTER TABLE DROP COLUMN clears
15271                                                  * pg_attribute.atttypid, so we will not have gotten a
15272                                                  * valid type name; insert INTEGER as a stopgap. We'll
15273                                                  * clean things up later.
15274                                                  */
15275                                                 appendPQExpBufferStr(q, " INTEGER /* dummy */");
15276                                                 /* Skip all the rest, too */
15277                                                 continue;
15278                                         }
15279
15280                                         /*
15281                                          * Attribute type
15282                                          *
15283                                          * In binary-upgrade mode, we always include the type. If
15284                                          * we aren't in binary-upgrade mode, then we skip the type
15285                                          * when creating a typed table ('OF type_name') or a
15286                                          * partition ('PARTITION OF'), since the type comes from
15287                                          * the parent/partitioned table.
15288                                          */
15289                                         if (dopt->binary_upgrade || (!tbinfo->reloftype && !tbinfo->ispartition))
15290                                         {
15291                                                 appendPQExpBuffer(q, " %s",
15292                                                                                   tbinfo->atttypnames[j]);
15293                                         }
15294
15295                                         /* Add collation if not default for the type */
15296                                         if (OidIsValid(tbinfo->attcollation[j]))
15297                                         {
15298                                                 CollInfo   *coll;
15299
15300                                                 coll = findCollationByOid(tbinfo->attcollation[j]);
15301                                                 if (coll)
15302                                                 {
15303                                                         /* always schema-qualify, don't try to be smart */
15304                                                         appendPQExpBuffer(q, " COLLATE %s.",
15305                                                                                           fmtId(coll->dobj.namespace->dobj.name));
15306                                                         appendPQExpBufferStr(q, fmtId(coll->dobj.name));
15307                                                 }
15308                                         }
15309
15310                                         if (has_default)
15311                                                 appendPQExpBuffer(q, " DEFAULT %s",
15312                                                                                   tbinfo->attrdefs[j]->adef_expr);
15313
15314                                         if (has_notnull)
15315                                                 appendPQExpBufferStr(q, " NOT NULL");
15316                                 }
15317                         }
15318
15319                         /*
15320                          * Add non-inherited CHECK constraints, if any.
15321                          */
15322                         for (j = 0; j < tbinfo->ncheck; j++)
15323                         {
15324                                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
15325
15326                                 if (constr->separate || !constr->conislocal)
15327                                         continue;
15328
15329                                 if (actual_atts == 0)
15330                                         appendPQExpBufferStr(q, " (\n    ");
15331                                 else
15332                                         appendPQExpBufferStr(q, ",\n    ");
15333
15334                                 appendPQExpBuffer(q, "CONSTRAINT %s ",
15335                                                                   fmtId(constr->dobj.name));
15336                                 appendPQExpBufferStr(q, constr->condef);
15337
15338                                 actual_atts++;
15339                         }
15340
15341                         if (actual_atts)
15342                                 appendPQExpBufferStr(q, "\n)");
15343                         else if (!((tbinfo->reloftype || tbinfo->ispartition) &&
15344                                            !dopt->binary_upgrade))
15345                         {
15346                                 /*
15347                                  * We must have a parenthesized attribute list, even though
15348                                  * empty, when not using the OF TYPE or PARTITION OF syntax.
15349                                  */
15350                                 appendPQExpBufferStr(q, " (\n)");
15351                         }
15352
15353                         if (tbinfo->ispartition && !dopt->binary_upgrade)
15354                         {
15355                                 appendPQExpBufferStr(q, "\n");
15356                                 appendPQExpBufferStr(q, tbinfo->partbound);
15357                         }
15358
15359                         /* Emit the INHERITS clause, except if this is a partition. */
15360                         if (numParents > 0 &&
15361                                 !tbinfo->ispartition &&
15362                                 !dopt->binary_upgrade)
15363                         {
15364                                 appendPQExpBufferStr(q, "\nINHERITS (");
15365                                 for (k = 0; k < numParents; k++)
15366                                 {
15367                                         TableInfo  *parentRel = parents[k];
15368
15369                                         if (k > 0)
15370                                                 appendPQExpBufferStr(q, ", ");
15371                                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
15372                                                 appendPQExpBuffer(q, "%s.",
15373                                                                                   fmtId(parentRel->dobj.namespace->dobj.name));
15374                                         appendPQExpBufferStr(q, fmtId(parentRel->dobj.name));
15375                                 }
15376                                 appendPQExpBufferChar(q, ')');
15377                         }
15378
15379                         if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15380                                 appendPQExpBuffer(q, "\nPARTITION BY %s", tbinfo->partkeydef);
15381
15382                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
15383                                 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
15384                 }
15385
15386                 if (nonemptyReloptions(tbinfo->reloptions) ||
15387                         nonemptyReloptions(tbinfo->toast_reloptions))
15388                 {
15389                         bool            addcomma = false;
15390
15391                         appendPQExpBufferStr(q, "\nWITH (");
15392                         if (nonemptyReloptions(tbinfo->reloptions))
15393                         {
15394                                 addcomma = true;
15395                                 appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15396                         }
15397                         if (nonemptyReloptions(tbinfo->toast_reloptions))
15398                         {
15399                                 if (addcomma)
15400                                         appendPQExpBufferStr(q, ", ");
15401                                 appendReloptionsArrayAH(q, tbinfo->toast_reloptions, "toast.",
15402                                                                                 fout);
15403                         }
15404                         appendPQExpBufferChar(q, ')');
15405                 }
15406
15407                 /* Dump generic options if any */
15408                 if (ftoptions && ftoptions[0])
15409                         appendPQExpBuffer(q, "\nOPTIONS (\n    %s\n)", ftoptions);
15410
15411                 /*
15412                  * For materialized views, create the AS clause just like a view. At
15413                  * this point, we always mark the view as not populated.
15414                  */
15415                 if (tbinfo->relkind == RELKIND_MATVIEW)
15416                 {
15417                         PQExpBuffer result;
15418
15419                         result = createViewAsClause(fout, tbinfo);
15420                         appendPQExpBuffer(q, " AS\n%s\n  WITH NO DATA;\n",
15421                                                           result->data);
15422                         destroyPQExpBuffer(result);
15423                 }
15424                 else
15425                         appendPQExpBufferStr(q, ";\n");
15426
15427                 /*
15428                  * To create binary-compatible heap files, we have to ensure the same
15429                  * physical column order, including dropped columns, as in the
15430                  * original.  Therefore, we create dropped columns above and drop them
15431                  * here, also updating their attlen/attalign values so that the
15432                  * dropped column can be skipped properly.  (We do not bother with
15433                  * restoring the original attbyval setting.)  Also, inheritance
15434                  * relationships are set up by doing ALTER TABLE INHERIT rather than
15435                  * using an INHERITS clause --- the latter would possibly mess up the
15436                  * column order.  That also means we have to take care about setting
15437                  * attislocal correctly, plus fix up any inherited CHECK constraints.
15438                  * Analogously, we set up typed tables using ALTER TABLE / OF here.
15439                  */
15440                 if (dopt->binary_upgrade &&
15441                         (tbinfo->relkind == RELKIND_RELATION ||
15442                          tbinfo->relkind == RELKIND_FOREIGN_TABLE ||
15443                          tbinfo->relkind == RELKIND_PARTITIONED_TABLE))
15444                 {
15445                         for (j = 0; j < tbinfo->numatts; j++)
15446                         {
15447                                 if (tbinfo->attisdropped[j])
15448                                 {
15449                                         appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate dropped column.\n");
15450                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
15451                                                                           "SET attlen = %d, "
15452                                                                           "attalign = '%c', attbyval = false\n"
15453                                                                           "WHERE attname = ",
15454                                                                           tbinfo->attlen[j],
15455                                                                           tbinfo->attalign[j]);
15456                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15457                                         appendPQExpBufferStr(q, "\n  AND attrelid = ");
15458                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
15459                                         appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15460
15461                                         if (tbinfo->relkind == RELKIND_RELATION ||
15462                                                 tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
15463                                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15464                                                                                   fmtId(tbinfo->dobj.name));
15465                                         else
15466                                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE ONLY %s ",
15467                                                                                   fmtId(tbinfo->dobj.name));
15468                                         appendPQExpBuffer(q, "DROP COLUMN %s;\n",
15469                                                                           fmtId(tbinfo->attnames[j]));
15470                                 }
15471                                 else if (!tbinfo->attislocal[j])
15472                                 {
15473                                         appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate inherited column.\n");
15474                                         appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_attribute\n"
15475                                                                                  "SET attislocal = false\n"
15476                                                                                  "WHERE attname = ");
15477                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
15478                                         appendPQExpBufferStr(q, "\n  AND attrelid = ");
15479                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
15480                                         appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15481                                 }
15482                         }
15483
15484                         for (k = 0; k < tbinfo->ncheck; k++)
15485                         {
15486                                 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
15487
15488                                 if (constr->separate || constr->conislocal)
15489                                         continue;
15490
15491                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inherited constraint.\n");
15492                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15493                                                                   fmtId(tbinfo->dobj.name));
15494                                 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
15495                                                                   fmtId(constr->dobj.name));
15496                                 appendPQExpBuffer(q, "%s;\n", constr->condef);
15497                                 appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_constraint\n"
15498                                                                          "SET conislocal = false\n"
15499                                                                          "WHERE contype = 'c' AND conname = ");
15500                                 appendStringLiteralAH(q, constr->dobj.name, fout);
15501                                 appendPQExpBufferStr(q, "\n  AND conrelid = ");
15502                                 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
15503                                 appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15504                         }
15505
15506                         if (numParents > 0)
15507                         {
15508                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inheritance and partitioning this way.\n");
15509                                 for (k = 0; k < numParents; k++)
15510                                 {
15511                                         TableInfo  *parentRel = parents[k];
15512                                         PQExpBuffer parentname = createPQExpBuffer();
15513
15514                                         /* Schema-qualify the parent table, if necessary */
15515                                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
15516                                                 appendPQExpBuffer(parentname, "%s.",
15517                                                                                   fmtId(parentRel->dobj.namespace->dobj.name));
15518
15519                                         appendPQExpBuffer(parentname, "%s",
15520                                                                           fmtId(parentRel->dobj.name));
15521
15522                                         /* In the partitioning case, we alter the parent */
15523                                         if (tbinfo->ispartition)
15524                                                 appendPQExpBuffer(q,
15525                                                                                   "ALTER TABLE ONLY %s ATTACH PARTITION ",
15526                                                                                   parentname->data);
15527                                         else
15528                                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
15529                                                                                   fmtId(tbinfo->dobj.name));
15530
15531                                         /* Partition needs specifying the bounds */
15532                                         if (tbinfo->ispartition)
15533                                                 appendPQExpBuffer(q, "%s %s;\n",
15534                                                                                   fmtId(tbinfo->dobj.name),
15535                                                                                   tbinfo->partbound);
15536                                         else
15537                                                 appendPQExpBuffer(q, "%s;\n", parentname->data);
15538
15539                                         destroyPQExpBuffer(parentname);
15540                                 }
15541                         }
15542
15543                         if (tbinfo->reloftype)
15544                         {
15545                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, set up typed tables this way.\n");
15546                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
15547                                                                   fmtId(tbinfo->dobj.name),
15548                                                                   tbinfo->reloftype);
15549                         }
15550
15551                         appendPQExpBufferStr(q, "\n-- For binary upgrade, set heap's relfrozenxid and relminmxid\n");
15552                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
15553                                                           "SET relfrozenxid = '%u', relminmxid = '%u'\n"
15554                                                           "WHERE oid = ",
15555                                                           tbinfo->frozenxid, tbinfo->minmxid);
15556                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
15557                         appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15558
15559                         if (tbinfo->toast_oid)
15560                         {
15561                                 /* We preserve the toast oids, so we can use it during restore */
15562                                 appendPQExpBufferStr(q, "\n-- For binary upgrade, set toast's relfrozenxid and relminmxid\n");
15563                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
15564                                                                   "SET relfrozenxid = '%u', relminmxid = '%u'\n"
15565                                                                   "WHERE oid = '%u';\n",
15566                                                                   tbinfo->toast_frozenxid,
15567                                                                   tbinfo->toast_minmxid, tbinfo->toast_oid);
15568                         }
15569                 }
15570
15571                 /*
15572                  * In binary_upgrade mode, restore matviews' populated status by
15573                  * poking pg_class directly.  This is pretty ugly, but we can't use
15574                  * REFRESH MATERIALIZED VIEW since it's possible that some underlying
15575                  * matview is not populated even though this matview is.
15576                  */
15577                 if (dopt->binary_upgrade && tbinfo->relkind == RELKIND_MATVIEW &&
15578                         tbinfo->relispopulated)
15579                 {
15580                         appendPQExpBufferStr(q, "\n-- For binary upgrade, mark materialized view as populated\n");
15581                         appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_class\n"
15582                                                                  "SET relispopulated = 't'\n"
15583                                                                  "WHERE oid = ");
15584                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
15585                         appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
15586                 }
15587
15588                 /*
15589                  * Dump additional per-column properties that we can't handle in the
15590                  * main CREATE TABLE command.
15591                  */
15592                 for (j = 0; j < tbinfo->numatts; j++)
15593                 {
15594                         /* None of this applies to dropped columns */
15595                         if (tbinfo->attisdropped[j])
15596                                 continue;
15597
15598                         /*
15599                          * If we didn't dump the column definition explicitly above, and
15600                          * it is NOT NULL and did not inherit that property from a parent,
15601                          * we have to mark it separately.
15602                          */
15603                         if (!shouldPrintColumn(dopt, tbinfo, j) &&
15604                                 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
15605                         {
15606                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15607                                                                   fmtId(tbinfo->dobj.name));
15608                                 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
15609                                                                   fmtId(tbinfo->attnames[j]));
15610                         }
15611
15612                         /*
15613                          * Dump per-column statistics information. We only issue an ALTER
15614                          * TABLE statement if the attstattarget entry for this column is
15615                          * non-negative (i.e. it's not the default value)
15616                          */
15617                         if (tbinfo->attstattarget[j] >= 0)
15618                         {
15619                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15620                                                                   fmtId(tbinfo->dobj.name));
15621                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15622                                                                   fmtId(tbinfo->attnames[j]));
15623                                 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
15624                                                                   tbinfo->attstattarget[j]);
15625                         }
15626
15627                         /*
15628                          * Dump per-column storage information.  The statement is only
15629                          * dumped if the storage has been changed from the type's default.
15630                          */
15631                         if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
15632                         {
15633                                 switch (tbinfo->attstorage[j])
15634                                 {
15635                                         case 'p':
15636                                                 storage = "PLAIN";
15637                                                 break;
15638                                         case 'e':
15639                                                 storage = "EXTERNAL";
15640                                                 break;
15641                                         case 'm':
15642                                                 storage = "MAIN";
15643                                                 break;
15644                                         case 'x':
15645                                                 storage = "EXTENDED";
15646                                                 break;
15647                                         default:
15648                                                 storage = NULL;
15649                                 }
15650
15651                                 /*
15652                                  * Only dump the statement if it's a storage type we recognize
15653                                  */
15654                                 if (storage != NULL)
15655                                 {
15656                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15657                                                                           fmtId(tbinfo->dobj.name));
15658                                         appendPQExpBuffer(q, "ALTER COLUMN %s ",
15659                                                                           fmtId(tbinfo->attnames[j]));
15660                                         appendPQExpBuffer(q, "SET STORAGE %s;\n",
15661                                                                           storage);
15662                                 }
15663                         }
15664
15665                         /*
15666                          * Dump per-column attributes.
15667                          */
15668                         if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
15669                         {
15670                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15671                                                                   fmtId(tbinfo->dobj.name));
15672                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15673                                                                   fmtId(tbinfo->attnames[j]));
15674                                 appendPQExpBuffer(q, "SET (%s);\n",
15675                                                                   tbinfo->attoptions[j]);
15676                         }
15677
15678                         /*
15679                          * Dump per-column fdw options.
15680                          */
15681                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
15682                                 tbinfo->attfdwoptions[j] &&
15683                                 tbinfo->attfdwoptions[j][0] != '\0')
15684                         {
15685                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
15686                                                                   fmtId(tbinfo->dobj.name));
15687                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
15688                                                                   fmtId(tbinfo->attnames[j]));
15689                                 appendPQExpBuffer(q, "OPTIONS (\n    %s\n);\n",
15690                                                                   tbinfo->attfdwoptions[j]);
15691                         }
15692                 }
15693         }
15694
15695         /*
15696          * dump properties we only have ALTER TABLE syntax for
15697          */
15698         if ((tbinfo->relkind == RELKIND_RELATION ||
15699                  tbinfo->relkind == RELKIND_PARTITIONED_TABLE ||
15700                  tbinfo->relkind == RELKIND_MATVIEW) &&
15701                 tbinfo->relreplident != REPLICA_IDENTITY_DEFAULT)
15702         {
15703                 if (tbinfo->relreplident == REPLICA_IDENTITY_INDEX)
15704                 {
15705                         /* nothing to do, will be set when the index is dumped */
15706                 }
15707                 else if (tbinfo->relreplident == REPLICA_IDENTITY_NOTHING)
15708                 {
15709                         appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY NOTHING;\n",
15710                                                           fmtId(tbinfo->dobj.name));
15711                 }
15712                 else if (tbinfo->relreplident == REPLICA_IDENTITY_FULL)
15713                 {
15714                         appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY FULL;\n",
15715                                                           fmtId(tbinfo->dobj.name));
15716                 }
15717         }
15718
15719         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE && tbinfo->hasoids)
15720                 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s SET WITH OIDS;\n",
15721                                                   fmtId(tbinfo->dobj.name));
15722
15723         if (tbinfo->forcerowsec)
15724                 appendPQExpBuffer(q, "\nALTER TABLE ONLY %s FORCE ROW LEVEL SECURITY;\n",
15725                                                   fmtId(tbinfo->dobj.name));
15726
15727         if (dopt->binary_upgrade)
15728                 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
15729
15730         if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
15731                 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
15732                                          tbinfo->dobj.name,
15733                                          tbinfo->dobj.namespace->dobj.name,
15734                                          (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
15735                                          tbinfo->rolname,
15736                                          (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
15737                                          reltypename,
15738                                          tbinfo->postponed_def ?
15739                                          SECTION_POST_DATA : SECTION_PRE_DATA,
15740                                          q->data, delq->data, NULL,
15741                                          NULL, 0,
15742                                          NULL, NULL);
15743
15744
15745         /* Dump Table Comments */
15746         if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
15747                 dumpTableComment(fout, tbinfo, reltypename);
15748
15749         /* Dump Table Security Labels */
15750         if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
15751                 dumpTableSecLabel(fout, tbinfo, reltypename);
15752
15753         /* Dump comments on inlined table constraints */
15754         for (j = 0; j < tbinfo->ncheck; j++)
15755         {
15756                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
15757
15758                 if (constr->separate || !constr->conislocal)
15759                         continue;
15760
15761                 if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
15762                         dumpTableConstraintComment(fout, constr);
15763         }
15764
15765         destroyPQExpBuffer(q);
15766         destroyPQExpBuffer(delq);
15767         destroyPQExpBuffer(labelq);
15768 }
15769
15770 /*
15771  * dumpAttrDef --- dump an attribute's default-value declaration
15772  */
15773 static void
15774 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
15775 {
15776         DumpOptions *dopt = fout->dopt;
15777         TableInfo  *tbinfo = adinfo->adtable;
15778         int                     adnum = adinfo->adnum;
15779         PQExpBuffer q;
15780         PQExpBuffer delq;
15781         char       *tag;
15782
15783         /* Skip if table definition not to be dumped */
15784         if (!tbinfo->dobj.dump || dopt->dataOnly)
15785                 return;
15786
15787         /* Skip if not "separate"; it was dumped in the table's definition */
15788         if (!adinfo->separate)
15789                 return;
15790
15791         q = createPQExpBuffer();
15792         delq = createPQExpBuffer();
15793
15794         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
15795                                           fmtId(tbinfo->dobj.name));
15796         appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
15797                                           fmtId(tbinfo->attnames[adnum - 1]),
15798                                           adinfo->adef_expr);
15799
15800         /*
15801          * DROP must be fully qualified in case same name appears in pg_catalog
15802          */
15803         appendPQExpBuffer(delq, "ALTER TABLE %s.",
15804                                           fmtId(tbinfo->dobj.namespace->dobj.name));
15805         appendPQExpBuffer(delq, "%s ",
15806                                           fmtId(tbinfo->dobj.name));
15807         appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
15808                                           fmtId(tbinfo->attnames[adnum - 1]));
15809
15810         tag = psprintf("%s %s", tbinfo->dobj.name, tbinfo->attnames[adnum - 1]);
15811
15812         if (adinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
15813                 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
15814                                          tag,
15815                                          tbinfo->dobj.namespace->dobj.name,
15816                                          NULL,
15817                                          tbinfo->rolname,
15818                                          false, "DEFAULT", SECTION_PRE_DATA,
15819                                          q->data, delq->data, NULL,
15820                                          NULL, 0,
15821                                          NULL, NULL);
15822
15823         free(tag);
15824         destroyPQExpBuffer(q);
15825         destroyPQExpBuffer(delq);
15826 }
15827
15828 /*
15829  * getAttrName: extract the correct name for an attribute
15830  *
15831  * The array tblInfo->attnames[] only provides names of user attributes;
15832  * if a system attribute number is supplied, we have to fake it.
15833  * We also do a little bit of bounds checking for safety's sake.
15834  */
15835 static const char *
15836 getAttrName(int attrnum, TableInfo *tblInfo)
15837 {
15838         if (attrnum > 0 && attrnum <= tblInfo->numatts)
15839                 return tblInfo->attnames[attrnum - 1];
15840         switch (attrnum)
15841         {
15842                 case SelfItemPointerAttributeNumber:
15843                         return "ctid";
15844                 case ObjectIdAttributeNumber:
15845                         return "oid";
15846                 case MinTransactionIdAttributeNumber:
15847                         return "xmin";
15848                 case MinCommandIdAttributeNumber:
15849                         return "cmin";
15850                 case MaxTransactionIdAttributeNumber:
15851                         return "xmax";
15852                 case MaxCommandIdAttributeNumber:
15853                         return "cmax";
15854                 case TableOidAttributeNumber:
15855                         return "tableoid";
15856         }
15857         exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
15858                                   attrnum, tblInfo->dobj.name);
15859         return NULL;                            /* keep compiler quiet */
15860 }
15861
15862 /*
15863  * dumpIndex
15864  *        write out to fout a user-defined index
15865  */
15866 static void
15867 dumpIndex(Archive *fout, IndxInfo *indxinfo)
15868 {
15869         DumpOptions *dopt = fout->dopt;
15870         TableInfo  *tbinfo = indxinfo->indextable;
15871         bool            is_constraint = (indxinfo->indexconstraint != 0);
15872         PQExpBuffer q;
15873         PQExpBuffer delq;
15874         PQExpBuffer labelq;
15875
15876         if (dopt->dataOnly)
15877                 return;
15878
15879         q = createPQExpBuffer();
15880         delq = createPQExpBuffer();
15881         labelq = createPQExpBuffer();
15882
15883         appendPQExpBuffer(labelq, "INDEX %s",
15884                                           fmtId(indxinfo->dobj.name));
15885
15886         /*
15887          * If there's an associated constraint, don't dump the index per se, but
15888          * do dump any comment for it.  (This is safe because dependency ordering
15889          * will have ensured the constraint is emitted first.)  Note that the
15890          * emitted comment has to be shown as depending on the constraint, not the
15891          * index, in such cases.
15892          */
15893         if (!is_constraint)
15894         {
15895                 if (dopt->binary_upgrade)
15896                         binary_upgrade_set_pg_class_oids(fout, q,
15897                                                                                          indxinfo->dobj.catId.oid, true);
15898
15899                 /* Plain secondary index */
15900                 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
15901
15902                 /* If the index is clustered, we need to record that. */
15903                 if (indxinfo->indisclustered)
15904                 {
15905                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
15906                                                           fmtId(tbinfo->dobj.name));
15907                         appendPQExpBuffer(q, " ON %s;\n",
15908                                                           fmtId(indxinfo->dobj.name));
15909                 }
15910
15911                 /* If the index defines identity, we need to record that. */
15912                 if (indxinfo->indisreplident)
15913                 {
15914                         appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
15915                                                           fmtId(tbinfo->dobj.name));
15916                         appendPQExpBuffer(q, " INDEX %s;\n",
15917                                                           fmtId(indxinfo->dobj.name));
15918                 }
15919
15920                 /*
15921                  * DROP must be fully qualified in case same name appears in
15922                  * pg_catalog
15923                  */
15924                 appendPQExpBuffer(delq, "DROP INDEX %s.",
15925                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
15926                 appendPQExpBuffer(delq, "%s;\n",
15927                                                   fmtId(indxinfo->dobj.name));
15928
15929                 if (indxinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
15930                         ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
15931                                                  indxinfo->dobj.name,
15932                                                  tbinfo->dobj.namespace->dobj.name,
15933                                                  indxinfo->tablespace,
15934                                                  tbinfo->rolname, false,
15935                                                  "INDEX", SECTION_POST_DATA,
15936                                                  q->data, delq->data, NULL,
15937                                                  NULL, 0,
15938                                                  NULL, NULL);
15939         }
15940
15941         /* Dump Index Comments */
15942         if (indxinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
15943                 dumpComment(fout, labelq->data,
15944                                         tbinfo->dobj.namespace->dobj.name,
15945                                         tbinfo->rolname,
15946                                         indxinfo->dobj.catId, 0,
15947                                         is_constraint ? indxinfo->indexconstraint :
15948                                         indxinfo->dobj.dumpId);
15949
15950         destroyPQExpBuffer(q);
15951         destroyPQExpBuffer(delq);
15952         destroyPQExpBuffer(labelq);
15953 }
15954
15955 /*
15956  * dumpStatisticsExt
15957  *        write out to fout an extended statistics object
15958  */
15959 static void
15960 dumpStatisticsExt(Archive *fout, StatsExtInfo *statsextinfo)
15961 {
15962         DumpOptions *dopt = fout->dopt;
15963         TableInfo  *tbinfo = statsextinfo->statsexttable;
15964         PQExpBuffer q;
15965         PQExpBuffer delq;
15966         PQExpBuffer labelq;
15967
15968         if (dopt->dataOnly)
15969                 return;
15970
15971         q = createPQExpBuffer();
15972         delq = createPQExpBuffer();
15973         labelq = createPQExpBuffer();
15974
15975         appendPQExpBuffer(labelq, "STATISTICS %s",
15976                                           fmtId(statsextinfo->dobj.name));
15977
15978         appendPQExpBuffer(q, "%s;\n", statsextinfo->statsextdef);
15979
15980         appendPQExpBuffer(delq, "DROP STATISTICS %s.",
15981                                           fmtId(tbinfo->dobj.namespace->dobj.name));
15982         appendPQExpBuffer(delq, "%s;\n",
15983                                           fmtId(statsextinfo->dobj.name));
15984
15985         if (statsextinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
15986                 ArchiveEntry(fout, statsextinfo->dobj.catId,
15987                                          statsextinfo->dobj.dumpId,
15988                                          statsextinfo->dobj.name,
15989                                          tbinfo->dobj.namespace->dobj.name,
15990                                          NULL,
15991                                          tbinfo->rolname, false,
15992                                          "STATISTICS", SECTION_POST_DATA,
15993                                          q->data, delq->data, NULL,
15994                                          NULL, 0,
15995                                          NULL, NULL);
15996
15997         /* Dump Statistics Comments */
15998         if (statsextinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
15999                 dumpComment(fout, labelq->data,
16000                                         tbinfo->dobj.namespace->dobj.name,
16001                                         tbinfo->rolname,
16002                                         statsextinfo->dobj.catId, 0,
16003                                         statsextinfo->dobj.dumpId);
16004
16005         destroyPQExpBuffer(q);
16006         destroyPQExpBuffer(delq);
16007         destroyPQExpBuffer(labelq);
16008 }
16009
16010 /*
16011  * dumpConstraint
16012  *        write out to fout a user-defined constraint
16013  */
16014 static void
16015 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
16016 {
16017         DumpOptions *dopt = fout->dopt;
16018         TableInfo  *tbinfo = coninfo->contable;
16019         PQExpBuffer q;
16020         PQExpBuffer delq;
16021         char       *tag = NULL;
16022
16023         /* Skip if not to be dumped */
16024         if (!coninfo->dobj.dump || dopt->dataOnly)
16025                 return;
16026
16027         q = createPQExpBuffer();
16028         delq = createPQExpBuffer();
16029
16030         if (coninfo->contype == 'p' ||
16031                 coninfo->contype == 'u' ||
16032                 coninfo->contype == 'x')
16033         {
16034                 /* Index-related constraint */
16035                 IndxInfo   *indxinfo;
16036                 int                     k;
16037
16038                 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
16039
16040                 if (indxinfo == NULL)
16041                         exit_horribly(NULL, "missing index for constraint \"%s\"\n",
16042                                                   coninfo->dobj.name);
16043
16044                 if (dopt->binary_upgrade)
16045                         binary_upgrade_set_pg_class_oids(fout, q,
16046                                                                                          indxinfo->dobj.catId.oid, true);
16047
16048                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
16049                                                   fmtId(tbinfo->dobj.name));
16050                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s ",
16051                                                   fmtId(coninfo->dobj.name));
16052
16053                 if (coninfo->condef)
16054                 {
16055                         /* pg_get_constraintdef should have provided everything */
16056                         appendPQExpBuffer(q, "%s;\n", coninfo->condef);
16057                 }
16058                 else
16059                 {
16060                         appendPQExpBuffer(q, "%s (",
16061                                                           coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
16062                         for (k = 0; k < indxinfo->indnkeys; k++)
16063                         {
16064                                 int                     indkey = (int) indxinfo->indkeys[k];
16065                                 const char *attname;
16066
16067                                 if (indkey == InvalidAttrNumber)
16068                                         break;
16069                                 attname = getAttrName(indkey, tbinfo);
16070
16071                                 appendPQExpBuffer(q, "%s%s",
16072                                                                   (k == 0) ? "" : ", ",
16073                                                                   fmtId(attname));
16074                         }
16075
16076                         appendPQExpBufferChar(q, ')');
16077
16078                         if (nonemptyReloptions(indxinfo->indreloptions))
16079                         {
16080                                 appendPQExpBufferStr(q, " WITH (");
16081                                 appendReloptionsArrayAH(q, indxinfo->indreloptions, "", fout);
16082                                 appendPQExpBufferChar(q, ')');
16083                         }
16084
16085                         if (coninfo->condeferrable)
16086                         {
16087                                 appendPQExpBufferStr(q, " DEFERRABLE");
16088                                 if (coninfo->condeferred)
16089                                         appendPQExpBufferStr(q, " INITIALLY DEFERRED");
16090                         }
16091
16092                         appendPQExpBufferStr(q, ";\n");
16093                 }
16094
16095                 /* If the index is clustered, we need to record that. */
16096                 if (indxinfo->indisclustered)
16097                 {
16098                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
16099                                                           fmtId(tbinfo->dobj.name));
16100                         appendPQExpBuffer(q, " ON %s;\n",
16101                                                           fmtId(indxinfo->dobj.name));
16102                 }
16103
16104                 /*
16105                  * DROP must be fully qualified in case same name appears in
16106                  * pg_catalog
16107                  */
16108                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
16109                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
16110                 appendPQExpBuffer(delq, "%s ",
16111                                                   fmtId(tbinfo->dobj.name));
16112                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16113                                                   fmtId(coninfo->dobj.name));
16114
16115                 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16116
16117                 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16118                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16119                                                  tag,
16120                                                  tbinfo->dobj.namespace->dobj.name,
16121                                                  indxinfo->tablespace,
16122                                                  tbinfo->rolname, false,
16123                                                  "CONSTRAINT", SECTION_POST_DATA,
16124                                                  q->data, delq->data, NULL,
16125                                                  NULL, 0,
16126                                                  NULL, NULL);
16127         }
16128         else if (coninfo->contype == 'f')
16129         {
16130                 /*
16131                  * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
16132                  * current table data is not processed
16133                  */
16134                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
16135                                                   fmtId(tbinfo->dobj.name));
16136                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
16137                                                   fmtId(coninfo->dobj.name),
16138                                                   coninfo->condef);
16139
16140                 /*
16141                  * DROP must be fully qualified in case same name appears in
16142                  * pg_catalog
16143                  */
16144                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
16145                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
16146                 appendPQExpBuffer(delq, "%s ",
16147                                                   fmtId(tbinfo->dobj.name));
16148                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16149                                                   fmtId(coninfo->dobj.name));
16150
16151                 tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16152
16153                 if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16154                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16155                                                  tag,
16156                                                  tbinfo->dobj.namespace->dobj.name,
16157                                                  NULL,
16158                                                  tbinfo->rolname, false,
16159                                                  "FK CONSTRAINT", SECTION_POST_DATA,
16160                                                  q->data, delq->data, NULL,
16161                                                  NULL, 0,
16162                                                  NULL, NULL);
16163         }
16164         else if (coninfo->contype == 'c' && tbinfo)
16165         {
16166                 /* CHECK constraint on a table */
16167
16168                 /* Ignore if not to be dumped separately, or if it was inherited */
16169                 if (coninfo->separate && coninfo->conislocal)
16170                 {
16171                         /* not ONLY since we want it to propagate to children */
16172                         appendPQExpBuffer(q, "ALTER TABLE %s\n",
16173                                                           fmtId(tbinfo->dobj.name));
16174                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
16175                                                           fmtId(coninfo->dobj.name),
16176                                                           coninfo->condef);
16177
16178                         /*
16179                          * DROP must be fully qualified in case same name appears in
16180                          * pg_catalog
16181                          */
16182                         appendPQExpBuffer(delq, "ALTER TABLE %s.",
16183                                                           fmtId(tbinfo->dobj.namespace->dobj.name));
16184                         appendPQExpBuffer(delq, "%s ",
16185                                                           fmtId(tbinfo->dobj.name));
16186                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16187                                                           fmtId(coninfo->dobj.name));
16188
16189                         tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
16190
16191                         if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16192                                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16193                                                          tag,
16194                                                          tbinfo->dobj.namespace->dobj.name,
16195                                                          NULL,
16196                                                          tbinfo->rolname, false,
16197                                                          "CHECK CONSTRAINT", SECTION_POST_DATA,
16198                                                          q->data, delq->data, NULL,
16199                                                          NULL, 0,
16200                                                          NULL, NULL);
16201                 }
16202         }
16203         else if (coninfo->contype == 'c' && tbinfo == NULL)
16204         {
16205                 /* CHECK constraint on a domain */
16206                 TypeInfo   *tyinfo = coninfo->condomain;
16207
16208                 /* Ignore if not to be dumped separately */
16209                 if (coninfo->separate)
16210                 {
16211                         appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
16212                                                           fmtId(tyinfo->dobj.name));
16213                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
16214                                                           fmtId(coninfo->dobj.name),
16215                                                           coninfo->condef);
16216
16217                         /*
16218                          * DROP must be fully qualified in case same name appears in
16219                          * pg_catalog
16220                          */
16221                         appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
16222                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
16223                         appendPQExpBuffer(delq, "%s ",
16224                                                           fmtId(tyinfo->dobj.name));
16225                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
16226                                                           fmtId(coninfo->dobj.name));
16227
16228                         tag = psprintf("%s %s", tyinfo->dobj.name, coninfo->dobj.name);
16229
16230                         if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16231                                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
16232                                                          tag,
16233                                                          tyinfo->dobj.namespace->dobj.name,
16234                                                          NULL,
16235                                                          tyinfo->rolname, false,
16236                                                          "CHECK CONSTRAINT", SECTION_POST_DATA,
16237                                                          q->data, delq->data, NULL,
16238                                                          NULL, 0,
16239                                                          NULL, NULL);
16240                 }
16241         }
16242         else
16243         {
16244                 exit_horribly(NULL, "unrecognized constraint type: %c\n",
16245                                           coninfo->contype);
16246         }
16247
16248         /* Dump Constraint Comments --- only works for table constraints */
16249         if (tbinfo && coninfo->separate &&
16250                 coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16251                 dumpTableConstraintComment(fout, coninfo);
16252
16253         free(tag);
16254         destroyPQExpBuffer(q);
16255         destroyPQExpBuffer(delq);
16256 }
16257
16258 /*
16259  * dumpTableConstraintComment --- dump a constraint's comment if any
16260  *
16261  * This is split out because we need the function in two different places
16262  * depending on whether the constraint is dumped as part of CREATE TABLE
16263  * or as a separate ALTER command.
16264  */
16265 static void
16266 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
16267 {
16268         TableInfo  *tbinfo = coninfo->contable;
16269         PQExpBuffer labelq = createPQExpBuffer();
16270
16271         appendPQExpBuffer(labelq, "CONSTRAINT %s ",
16272                                           fmtId(coninfo->dobj.name));
16273         appendPQExpBuffer(labelq, "ON %s",
16274                                           fmtId(tbinfo->dobj.name));
16275
16276         if (coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16277                 dumpComment(fout, labelq->data,
16278                                         tbinfo->dobj.namespace->dobj.name,
16279                                         tbinfo->rolname,
16280                                         coninfo->dobj.catId, 0,
16281                                         coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
16282
16283         destroyPQExpBuffer(labelq);
16284 }
16285
16286 /*
16287  * findLastBuiltinOid_V71 -
16288  *
16289  * find the last built in oid
16290  *
16291  * For 7.1 through 8.0, we do this by retrieving datlastsysoid from the
16292  * pg_database entry for the current database.
16293  */
16294 static Oid
16295 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
16296 {
16297         PGresult   *res;
16298         Oid                     last_oid;
16299         PQExpBuffer query = createPQExpBuffer();
16300
16301         resetPQExpBuffer(query);
16302         appendPQExpBufferStr(query, "SELECT datlastsysoid from pg_database where datname = ");
16303         appendStringLiteralAH(query, dbname, fout);
16304
16305         res = ExecuteSqlQueryForSingleRow(fout, query->data);
16306         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
16307         PQclear(res);
16308         destroyPQExpBuffer(query);
16309
16310         return last_oid;
16311 }
16312
16313 /*
16314  * dumpSequence
16315  *        write the declaration (not data) of one user-defined sequence
16316  */
16317 static void
16318 dumpSequence(Archive *fout, TableInfo *tbinfo)
16319 {
16320         DumpOptions *dopt = fout->dopt;
16321         PGresult   *res;
16322         char       *startv,
16323                            *incby,
16324                            *maxv,
16325                            *minv,
16326                            *cache,
16327                            *seqtype;
16328         bool            cycled;
16329         bool            is_ascending;
16330         PQExpBuffer query = createPQExpBuffer();
16331         PQExpBuffer delqry = createPQExpBuffer();
16332         PQExpBuffer labelq = createPQExpBuffer();
16333
16334         if (fout->remoteVersion >= 100000)
16335         {
16336                 /* Make sure we are in proper schema */
16337                 selectSourceSchema(fout, "pg_catalog");
16338
16339                 appendPQExpBuffer(query,
16340                                                   "SELECT format_type(seqtypid, NULL), "
16341                                                   "seqstart, seqincrement, "
16342                                                   "seqmax, seqmin, "
16343                                                   "seqcache, seqcycle "
16344                                                   "FROM pg_class c "
16345                                                   "JOIN pg_sequence s ON (s.seqrelid = c.oid) "
16346                                                   "WHERE c.oid = '%u'::oid",
16347                                                   tbinfo->dobj.catId.oid);
16348         }
16349         else if (fout->remoteVersion >= 80400)
16350         {
16351                 /*
16352                  * Before PostgreSQL 10, sequence metadata is in the sequence itself,
16353                  * so switch to the sequence's schema instead of pg_catalog.
16354                  */
16355
16356                 /* Make sure we are in proper schema */
16357                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
16358
16359                 appendPQExpBuffer(query,
16360                                                   "SELECT 'bigint'::name AS sequence_type, "
16361                                                   "start_value, increment_by, max_value, min_value, "
16362                                                   "cache_value, is_cycled FROM %s",
16363                                                   fmtId(tbinfo->dobj.name));
16364         }
16365         else
16366         {
16367                 /* Make sure we are in proper schema */
16368                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
16369
16370                 appendPQExpBuffer(query,
16371                                                   "SELECT 'bigint'::name AS sequence_type, "
16372                                                   "0 AS start_value, increment_by, max_value, min_value, "
16373                                                   "cache_value, is_cycled FROM %s",
16374                                                   fmtId(tbinfo->dobj.name));
16375         }
16376
16377         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
16378
16379         if (PQntuples(res) != 1)
16380         {
16381                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
16382                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
16383                                                                  PQntuples(res)),
16384                                   tbinfo->dobj.name, PQntuples(res));
16385                 exit_nicely(1);
16386         }
16387
16388         seqtype = PQgetvalue(res, 0, 0);
16389         startv = PQgetvalue(res, 0, 1);
16390         incby = PQgetvalue(res, 0, 2);
16391         maxv = PQgetvalue(res, 0, 3);
16392         minv = PQgetvalue(res, 0, 4);
16393         cache = PQgetvalue(res, 0, 5);
16394         cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
16395
16396         is_ascending = incby[0] != '-';
16397
16398         if (is_ascending && atoi(minv) == 1)
16399                 minv = NULL;
16400         if (!is_ascending && atoi(maxv) == -1)
16401                 maxv = NULL;
16402
16403         if (strcmp(seqtype, "smallint") == 0)
16404         {
16405                 if (!is_ascending && atoi(minv) == PG_INT16_MIN)
16406                         minv = NULL;
16407                 if (is_ascending && atoi(maxv) == PG_INT16_MAX)
16408                         maxv = NULL;
16409         }
16410         else if (strcmp(seqtype, "integer") == 0)
16411         {
16412                 if (!is_ascending && atoi(minv) == PG_INT32_MIN)
16413                         minv = NULL;
16414                 if (is_ascending && atoi(maxv) == PG_INT32_MAX)
16415                         maxv = NULL;
16416         }
16417         else if (strcmp(seqtype, "bigint") == 0)
16418         {
16419                 char            bufm[100],
16420                                         bufx[100];
16421
16422                 snprintf(bufm, sizeof(bufm), INT64_FORMAT, PG_INT64_MIN);
16423                 snprintf(bufx, sizeof(bufx), INT64_FORMAT, PG_INT64_MAX);
16424
16425                 if (!is_ascending && strcmp(minv, bufm) == 0)
16426                         minv = NULL;
16427                 if (is_ascending && strcmp(maxv, bufx) == 0)
16428                         maxv = NULL;
16429         }
16430
16431         /*
16432          * DROP must be fully qualified in case same name appears in pg_catalog
16433          */
16434         if (!tbinfo->is_identity_sequence)
16435         {
16436                 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
16437                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
16438                 appendPQExpBuffer(delqry, "%s;\n",
16439                                                   fmtId(tbinfo->dobj.name));
16440         }
16441
16442         resetPQExpBuffer(query);
16443
16444         if (dopt->binary_upgrade)
16445         {
16446                 binary_upgrade_set_pg_class_oids(fout, query,
16447                                                                                  tbinfo->dobj.catId.oid, false);
16448                 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
16449                                                                                                 tbinfo->dobj.catId.oid);
16450         }
16451
16452         if (tbinfo->is_identity_sequence)
16453         {
16454                 TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
16455
16456                 appendPQExpBuffer(query,
16457                                                   "ALTER TABLE %s ",
16458                                                   fmtId(owning_tab->dobj.name));
16459                 appendPQExpBuffer(query,
16460                                                   "ALTER COLUMN %s ADD GENERATED ",
16461                                                   fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16462                 if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_ALWAYS)
16463                         appendPQExpBuffer(query, "ALWAYS");
16464                 else if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_BY_DEFAULT)
16465                         appendPQExpBuffer(query, "BY DEFAULT");
16466                 appendPQExpBuffer(query, " AS IDENTITY (\n    SEQUENCE NAME %s\n",
16467                                                   fmtId(tbinfo->dobj.name));
16468         }
16469         else
16470         {
16471                 appendPQExpBuffer(query,
16472                                                   "CREATE SEQUENCE %s\n",
16473                                                   fmtId(tbinfo->dobj.name));
16474
16475                 if (strcmp(seqtype, "bigint") != 0)
16476                         appendPQExpBuffer(query, "    AS %s\n", seqtype);
16477         }
16478
16479         if (fout->remoteVersion >= 80400)
16480                 appendPQExpBuffer(query, "    START WITH %s\n", startv);
16481
16482         appendPQExpBuffer(query, "    INCREMENT BY %s\n", incby);
16483
16484         if (minv)
16485                 appendPQExpBuffer(query, "    MINVALUE %s\n", minv);
16486         else
16487                 appendPQExpBufferStr(query, "    NO MINVALUE\n");
16488
16489         if (maxv)
16490                 appendPQExpBuffer(query, "    MAXVALUE %s\n", maxv);
16491         else
16492                 appendPQExpBufferStr(query, "    NO MAXVALUE\n");
16493
16494         appendPQExpBuffer(query,
16495                                           "    CACHE %s%s",
16496                                           cache, (cycled ? "\n    CYCLE" : ""));
16497
16498         if (tbinfo->is_identity_sequence)
16499                 appendPQExpBufferStr(query, "\n);\n");
16500         else
16501                 appendPQExpBufferStr(query, ";\n");
16502
16503         appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
16504
16505         /* binary_upgrade:      no need to clear TOAST table oid */
16506
16507         if (dopt->binary_upgrade)
16508                 binary_upgrade_extension_member(query, &tbinfo->dobj,
16509                                                                                 labelq->data);
16510
16511         if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16512                 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
16513                                          tbinfo->dobj.name,
16514                                          tbinfo->dobj.namespace->dobj.name,
16515                                          NULL,
16516                                          tbinfo->rolname,
16517                                          false, "SEQUENCE", SECTION_PRE_DATA,
16518                                          query->data, delqry->data, NULL,
16519                                          NULL, 0,
16520                                          NULL, NULL);
16521
16522         /*
16523          * If the sequence is owned by a table column, emit the ALTER for it as a
16524          * separate TOC entry immediately following the sequence's own entry. It's
16525          * OK to do this rather than using full sorting logic, because the
16526          * dependency that tells us it's owned will have forced the table to be
16527          * created first.  We can't just include the ALTER in the TOC entry
16528          * because it will fail if we haven't reassigned the sequence owner to
16529          * match the table's owner.
16530          *
16531          * We need not schema-qualify the table reference because both sequence
16532          * and table must be in the same schema.
16533          */
16534         if (OidIsValid(tbinfo->owning_tab) && !tbinfo->is_identity_sequence)
16535         {
16536                 TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
16537
16538                 if (owning_tab == NULL)
16539                         exit_horribly(NULL, "failed sanity check, parent table with OID %u of sequence with OID %u not found\n",
16540                                                   tbinfo->owning_tab, tbinfo->dobj.catId.oid);
16541
16542                 if (owning_tab->dobj.dump & DUMP_COMPONENT_DEFINITION)
16543                 {
16544                         resetPQExpBuffer(query);
16545                         appendPQExpBuffer(query, "ALTER SEQUENCE %s",
16546                                                           fmtId(tbinfo->dobj.name));
16547                         appendPQExpBuffer(query, " OWNED BY %s",
16548                                                           fmtId(owning_tab->dobj.name));
16549                         appendPQExpBuffer(query, ".%s;\n",
16550                                                           fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
16551
16552                         if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16553                                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
16554                                                          tbinfo->dobj.name,
16555                                                          tbinfo->dobj.namespace->dobj.name,
16556                                                          NULL,
16557                                                          tbinfo->rolname,
16558                                                          false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
16559                                                          query->data, "", NULL,
16560                                                          &(tbinfo->dobj.dumpId), 1,
16561                                                          NULL, NULL);
16562                 }
16563         }
16564
16565         /* Dump Sequence Comments and Security Labels */
16566         if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16567                 dumpComment(fout, labelq->data,
16568                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16569                                         tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
16570
16571         if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16572                 dumpSecLabel(fout, labelq->data,
16573                                          tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16574                                          tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
16575
16576         PQclear(res);
16577
16578         destroyPQExpBuffer(query);
16579         destroyPQExpBuffer(delqry);
16580         destroyPQExpBuffer(labelq);
16581 }
16582
16583 /*
16584  * dumpSequenceData
16585  *        write the data of one user-defined sequence
16586  */
16587 static void
16588 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
16589 {
16590         TableInfo  *tbinfo = tdinfo->tdtable;
16591         PGresult   *res;
16592         char       *last;
16593         bool            called;
16594         PQExpBuffer query = createPQExpBuffer();
16595
16596         /* Make sure we are in proper schema */
16597         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
16598
16599         appendPQExpBuffer(query,
16600                                           "SELECT last_value, is_called FROM %s",
16601                                           fmtId(tbinfo->dobj.name));
16602
16603         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
16604
16605         if (PQntuples(res) != 1)
16606         {
16607                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
16608                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
16609                                                                  PQntuples(res)),
16610                                   tbinfo->dobj.name, PQntuples(res));
16611                 exit_nicely(1);
16612         }
16613
16614         last = PQgetvalue(res, 0, 0);
16615         called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
16616
16617         resetPQExpBuffer(query);
16618         appendPQExpBufferStr(query, "SELECT pg_catalog.setval(");
16619         appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
16620         appendPQExpBuffer(query, ", %s, %s);\n",
16621                                           last, (called ? "true" : "false"));
16622
16623         if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
16624                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
16625                                          tbinfo->dobj.name,
16626                                          tbinfo->dobj.namespace->dobj.name,
16627                                          NULL,
16628                                          tbinfo->rolname,
16629                                          false, "SEQUENCE SET", SECTION_DATA,
16630                                          query->data, "", NULL,
16631                                          &(tbinfo->dobj.dumpId), 1,
16632                                          NULL, NULL);
16633
16634         PQclear(res);
16635
16636         destroyPQExpBuffer(query);
16637 }
16638
16639 /*
16640  * dumpTrigger
16641  *        write the declaration of one user-defined table trigger
16642  */
16643 static void
16644 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
16645 {
16646         DumpOptions *dopt = fout->dopt;
16647         TableInfo  *tbinfo = tginfo->tgtable;
16648         PQExpBuffer query;
16649         PQExpBuffer delqry;
16650         PQExpBuffer labelq;
16651         char       *tgargs;
16652         size_t          lentgargs;
16653         const char *p;
16654         int                     findx;
16655         char       *tag;
16656
16657         /*
16658          * we needn't check dobj.dump because TriggerInfo wouldn't have been
16659          * created in the first place for non-dumpable triggers
16660          */
16661         if (dopt->dataOnly)
16662                 return;
16663
16664         query = createPQExpBuffer();
16665         delqry = createPQExpBuffer();
16666         labelq = createPQExpBuffer();
16667
16668         /*
16669          * DROP must be fully qualified in case same name appears in pg_catalog
16670          */
16671         appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
16672                                           fmtId(tginfo->dobj.name));
16673         appendPQExpBuffer(delqry, "ON %s.",
16674                                           fmtId(tbinfo->dobj.namespace->dobj.name));
16675         appendPQExpBuffer(delqry, "%s;\n",
16676                                           fmtId(tbinfo->dobj.name));
16677
16678         if (tginfo->tgdef)
16679         {
16680                 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
16681         }
16682         else
16683         {
16684                 if (tginfo->tgisconstraint)
16685                 {
16686                         appendPQExpBufferStr(query, "CREATE CONSTRAINT TRIGGER ");
16687                         appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
16688                 }
16689                 else
16690                 {
16691                         appendPQExpBufferStr(query, "CREATE TRIGGER ");
16692                         appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
16693                 }
16694                 appendPQExpBufferStr(query, "\n    ");
16695
16696                 /* Trigger type */
16697                 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
16698                         appendPQExpBufferStr(query, "BEFORE");
16699                 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
16700                         appendPQExpBufferStr(query, "AFTER");
16701                 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
16702                         appendPQExpBufferStr(query, "INSTEAD OF");
16703                 else
16704                 {
16705                         write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
16706                         exit_nicely(1);
16707                 }
16708
16709                 findx = 0;
16710                 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
16711                 {
16712                         appendPQExpBufferStr(query, " INSERT");
16713                         findx++;
16714                 }
16715                 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
16716                 {
16717                         if (findx > 0)
16718                                 appendPQExpBufferStr(query, " OR DELETE");
16719                         else
16720                                 appendPQExpBufferStr(query, " DELETE");
16721                         findx++;
16722                 }
16723                 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
16724                 {
16725                         if (findx > 0)
16726                                 appendPQExpBufferStr(query, " OR UPDATE");
16727                         else
16728                                 appendPQExpBufferStr(query, " UPDATE");
16729                         findx++;
16730                 }
16731                 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
16732                 {
16733                         if (findx > 0)
16734                                 appendPQExpBufferStr(query, " OR TRUNCATE");
16735                         else
16736                                 appendPQExpBufferStr(query, " TRUNCATE");
16737                         findx++;
16738                 }
16739                 appendPQExpBuffer(query, " ON %s\n",
16740                                                   fmtId(tbinfo->dobj.name));
16741
16742                 if (tginfo->tgisconstraint)
16743                 {
16744                         if (OidIsValid(tginfo->tgconstrrelid))
16745                         {
16746                                 /* regclass output is already quoted */
16747                                 appendPQExpBuffer(query, "    FROM %s\n    ",
16748                                                                   tginfo->tgconstrrelname);
16749                         }
16750                         if (!tginfo->tgdeferrable)
16751                                 appendPQExpBufferStr(query, "NOT ");
16752                         appendPQExpBufferStr(query, "DEFERRABLE INITIALLY ");
16753                         if (tginfo->tginitdeferred)
16754                                 appendPQExpBufferStr(query, "DEFERRED\n");
16755                         else
16756                                 appendPQExpBufferStr(query, "IMMEDIATE\n");
16757                 }
16758
16759                 if (TRIGGER_FOR_ROW(tginfo->tgtype))
16760                         appendPQExpBufferStr(query, "    FOR EACH ROW\n    ");
16761                 else
16762                         appendPQExpBufferStr(query, "    FOR EACH STATEMENT\n    ");
16763
16764                 /* regproc output is already sufficiently quoted */
16765                 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
16766                                                   tginfo->tgfname);
16767
16768                 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
16769                                                                                   &lentgargs);
16770                 p = tgargs;
16771                 for (findx = 0; findx < tginfo->tgnargs; findx++)
16772                 {
16773                         /* find the embedded null that terminates this trigger argument */
16774                         size_t          tlen = strlen(p);
16775
16776                         if (p + tlen >= tgargs + lentgargs)
16777                         {
16778                                 /* hm, not found before end of bytea value... */
16779                                 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
16780                                                   tginfo->tgargs,
16781                                                   tginfo->dobj.name,
16782                                                   tbinfo->dobj.name);
16783                                 exit_nicely(1);
16784                         }
16785
16786                         if (findx > 0)
16787                                 appendPQExpBufferStr(query, ", ");
16788                         appendStringLiteralAH(query, p, fout);
16789                         p += tlen + 1;
16790                 }
16791                 free(tgargs);
16792                 appendPQExpBufferStr(query, ");\n");
16793         }
16794
16795         if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
16796         {
16797                 appendPQExpBuffer(query, "\nALTER TABLE %s ",
16798                                                   fmtId(tbinfo->dobj.name));
16799                 switch (tginfo->tgenabled)
16800                 {
16801                         case 'D':
16802                         case 'f':
16803                                 appendPQExpBufferStr(query, "DISABLE");
16804                                 break;
16805                         case 'A':
16806                                 appendPQExpBufferStr(query, "ENABLE ALWAYS");
16807                                 break;
16808                         case 'R':
16809                                 appendPQExpBufferStr(query, "ENABLE REPLICA");
16810                                 break;
16811                         default:
16812                                 appendPQExpBufferStr(query, "ENABLE");
16813                                 break;
16814                 }
16815                 appendPQExpBuffer(query, " TRIGGER %s;\n",
16816                                                   fmtId(tginfo->dobj.name));
16817         }
16818
16819         appendPQExpBuffer(labelq, "TRIGGER %s ",
16820                                           fmtId(tginfo->dobj.name));
16821         appendPQExpBuffer(labelq, "ON %s",
16822                                           fmtId(tbinfo->dobj.name));
16823
16824         tag = psprintf("%s %s", tbinfo->dobj.name, tginfo->dobj.name);
16825
16826         if (tginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16827                 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
16828                                          tag,
16829                                          tbinfo->dobj.namespace->dobj.name,
16830                                          NULL,
16831                                          tbinfo->rolname, false,
16832                                          "TRIGGER", SECTION_POST_DATA,
16833                                          query->data, delqry->data, NULL,
16834                                          NULL, 0,
16835                                          NULL, NULL);
16836
16837         if (tginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16838                 dumpComment(fout, labelq->data,
16839                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
16840                                         tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
16841
16842         free(tag);
16843         destroyPQExpBuffer(query);
16844         destroyPQExpBuffer(delqry);
16845         destroyPQExpBuffer(labelq);
16846 }
16847
16848 /*
16849  * dumpEventTrigger
16850  *        write the declaration of one user-defined event trigger
16851  */
16852 static void
16853 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
16854 {
16855         DumpOptions *dopt = fout->dopt;
16856         PQExpBuffer query;
16857         PQExpBuffer delqry;
16858         PQExpBuffer labelq;
16859
16860         /* Skip if not to be dumped */
16861         if (!evtinfo->dobj.dump || dopt->dataOnly)
16862                 return;
16863
16864         query = createPQExpBuffer();
16865         delqry = createPQExpBuffer();
16866         labelq = createPQExpBuffer();
16867
16868         appendPQExpBufferStr(query, "CREATE EVENT TRIGGER ");
16869         appendPQExpBufferStr(query, fmtId(evtinfo->dobj.name));
16870         appendPQExpBufferStr(query, " ON ");
16871         appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
16872
16873         if (strcmp("", evtinfo->evttags) != 0)
16874         {
16875                 appendPQExpBufferStr(query, "\n         WHEN TAG IN (");
16876                 appendPQExpBufferStr(query, evtinfo->evttags);
16877                 appendPQExpBufferChar(query, ')');
16878         }
16879
16880         appendPQExpBufferStr(query, "\n   EXECUTE PROCEDURE ");
16881         appendPQExpBufferStr(query, evtinfo->evtfname);
16882         appendPQExpBufferStr(query, "();\n");
16883
16884         if (evtinfo->evtenabled != 'O')
16885         {
16886                 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
16887                                                   fmtId(evtinfo->dobj.name));
16888                 switch (evtinfo->evtenabled)
16889                 {
16890                         case 'D':
16891                                 appendPQExpBufferStr(query, "DISABLE");
16892                                 break;
16893                         case 'A':
16894                                 appendPQExpBufferStr(query, "ENABLE ALWAYS");
16895                                 break;
16896                         case 'R':
16897                                 appendPQExpBufferStr(query, "ENABLE REPLICA");
16898                                 break;
16899                         default:
16900                                 appendPQExpBufferStr(query, "ENABLE");
16901                                 break;
16902                 }
16903                 appendPQExpBufferStr(query, ";\n");
16904         }
16905
16906         appendPQExpBuffer(delqry, "DROP EVENT TRIGGER %s;\n",
16907                                           fmtId(evtinfo->dobj.name));
16908
16909         appendPQExpBuffer(labelq, "EVENT TRIGGER %s",
16910                                           fmtId(evtinfo->dobj.name));
16911
16912         if (evtinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16913                 ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
16914                                          evtinfo->dobj.name, NULL, NULL,
16915                                          evtinfo->evtowner, false,
16916                                          "EVENT TRIGGER", SECTION_POST_DATA,
16917                                          query->data, delqry->data, NULL,
16918                                          NULL, 0,
16919                                          NULL, NULL);
16920
16921         if (evtinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16922                 dumpComment(fout, labelq->data,
16923                                         NULL, evtinfo->evtowner,
16924                                         evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
16925
16926         destroyPQExpBuffer(query);
16927         destroyPQExpBuffer(delqry);
16928         destroyPQExpBuffer(labelq);
16929 }
16930
16931 /*
16932  * dumpRule
16933  *              Dump a rule
16934  */
16935 static void
16936 dumpRule(Archive *fout, RuleInfo *rinfo)
16937 {
16938         DumpOptions *dopt = fout->dopt;
16939         TableInfo  *tbinfo = rinfo->ruletable;
16940         bool            is_view;
16941         PQExpBuffer query;
16942         PQExpBuffer cmd;
16943         PQExpBuffer delcmd;
16944         PQExpBuffer labelq;
16945         PGresult   *res;
16946         char       *tag;
16947
16948         /* Skip if not to be dumped */
16949         if (!rinfo->dobj.dump || dopt->dataOnly)
16950                 return;
16951
16952         /*
16953          * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
16954          * we do not want to dump it as a separate object.
16955          */
16956         if (!rinfo->separate)
16957                 return;
16958
16959         /*
16960          * If it's an ON SELECT rule, we want to print it as a view definition,
16961          * instead of a rule.
16962          */
16963         is_view = (rinfo->ev_type == '1' && rinfo->is_instead);
16964
16965         /*
16966          * Make sure we are in proper schema.
16967          */
16968         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
16969
16970         query = createPQExpBuffer();
16971         cmd = createPQExpBuffer();
16972         delcmd = createPQExpBuffer();
16973         labelq = createPQExpBuffer();
16974
16975         if (is_view)
16976         {
16977                 PQExpBuffer result;
16978
16979                 /*
16980                  * We need OR REPLACE here because we'll be replacing a dummy view.
16981                  * Otherwise this should look largely like the regular view dump code.
16982                  */
16983                 appendPQExpBuffer(cmd, "CREATE OR REPLACE VIEW %s",
16984                                                   fmtId(tbinfo->dobj.name));
16985                 if (nonemptyReloptions(tbinfo->reloptions))
16986                 {
16987                         appendPQExpBufferStr(cmd, " WITH (");
16988                         appendReloptionsArrayAH(cmd, tbinfo->reloptions, "", fout);
16989                         appendPQExpBufferChar(cmd, ')');
16990                 }
16991                 result = createViewAsClause(fout, tbinfo);
16992                 appendPQExpBuffer(cmd, " AS\n%s", result->data);
16993                 destroyPQExpBuffer(result);
16994                 if (tbinfo->checkoption != NULL)
16995                         appendPQExpBuffer(cmd, "\n  WITH %s CHECK OPTION",
16996                                                           tbinfo->checkoption);
16997                 appendPQExpBufferStr(cmd, ";\n");
16998         }
16999         else
17000         {
17001                 /* In the rule case, just print pg_get_ruledef's result verbatim */
17002                 appendPQExpBuffer(query,
17003                                                   "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid)",
17004                                                   rinfo->dobj.catId.oid);
17005
17006                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17007
17008                 if (PQntuples(res) != 1)
17009                 {
17010                         write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
17011                                           rinfo->dobj.name, tbinfo->dobj.name);
17012                         exit_nicely(1);
17013                 }
17014
17015                 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
17016
17017                 PQclear(res);
17018         }
17019
17020         /*
17021          * Add the command to alter the rules replication firing semantics if it
17022          * differs from the default.
17023          */
17024         if (rinfo->ev_enabled != 'O')
17025         {
17026                 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtId(tbinfo->dobj.name));
17027                 switch (rinfo->ev_enabled)
17028                 {
17029                         case 'A':
17030                                 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
17031                                                                   fmtId(rinfo->dobj.name));
17032                                 break;
17033                         case 'R':
17034                                 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
17035                                                                   fmtId(rinfo->dobj.name));
17036                                 break;
17037                         case 'D':
17038                                 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
17039                                                                   fmtId(rinfo->dobj.name));
17040                                 break;
17041                 }
17042         }
17043
17044         /*
17045          * DROP must be fully qualified in case same name appears in pg_catalog
17046          */
17047         if (is_view)
17048         {
17049                 /*
17050                  * We can't DROP a view's ON SELECT rule.  Instead, use CREATE OR
17051                  * REPLACE VIEW to replace the rule with something with minimal
17052                  * dependencies.
17053                  */
17054                 PQExpBuffer result;
17055
17056                 appendPQExpBuffer(delcmd, "CREATE OR REPLACE VIEW %s.",
17057                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
17058                 appendPQExpBuffer(delcmd, "%s",
17059                                                   fmtId(tbinfo->dobj.name));
17060                 result = createDummyViewAsClause(fout, tbinfo);
17061                 appendPQExpBuffer(delcmd, " AS\n%s;\n", result->data);
17062                 destroyPQExpBuffer(result);
17063         }
17064         else
17065         {
17066                 appendPQExpBuffer(delcmd, "DROP RULE %s ",
17067                                                   fmtId(rinfo->dobj.name));
17068                 appendPQExpBuffer(delcmd, "ON %s.",
17069                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
17070                 appendPQExpBuffer(delcmd, "%s;\n",
17071                                                   fmtId(tbinfo->dobj.name));
17072         }
17073
17074         appendPQExpBuffer(labelq, "RULE %s",
17075                                           fmtId(rinfo->dobj.name));
17076         appendPQExpBuffer(labelq, " ON %s",
17077                                           fmtId(tbinfo->dobj.name));
17078
17079         tag = psprintf("%s %s", tbinfo->dobj.name, rinfo->dobj.name);
17080
17081         if (rinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17082                 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
17083                                          tag,
17084                                          tbinfo->dobj.namespace->dobj.name,
17085                                          NULL,
17086                                          tbinfo->rolname, false,
17087                                          "RULE", SECTION_POST_DATA,
17088                                          cmd->data, delcmd->data, NULL,
17089                                          NULL, 0,
17090                                          NULL, NULL);
17091
17092         /* Dump rule comments */
17093         if (rinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17094                 dumpComment(fout, labelq->data,
17095                                         tbinfo->dobj.namespace->dobj.name,
17096                                         tbinfo->rolname,
17097                                         rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
17098
17099         free(tag);
17100         destroyPQExpBuffer(query);
17101         destroyPQExpBuffer(cmd);
17102         destroyPQExpBuffer(delcmd);
17103         destroyPQExpBuffer(labelq);
17104 }
17105
17106 /*
17107  * getExtensionMembership --- obtain extension membership data
17108  *
17109  * We need to identify objects that are extension members as soon as they're
17110  * loaded, so that we can correctly determine whether they need to be dumped.
17111  * Generally speaking, extension member objects will get marked as *not* to
17112  * be dumped, as they will be recreated by the single CREATE EXTENSION
17113  * command.  However, in binary upgrade mode we still need to dump the members
17114  * individually.
17115  */
17116 void
17117 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
17118                                            int numExtensions)
17119 {
17120         PQExpBuffer query;
17121         PGresult   *res;
17122         int                     ntups,
17123                                 nextmembers,
17124                                 i;
17125         int                     i_classid,
17126                                 i_objid,
17127                                 i_refobjid;
17128         ExtensionMemberId *extmembers;
17129         ExtensionInfo *ext;
17130
17131         /* Nothing to do if no extensions */
17132         if (numExtensions == 0)
17133                 return;
17134
17135         /* Make sure we are in proper schema */
17136         selectSourceSchema(fout, "pg_catalog");
17137
17138         query = createPQExpBuffer();
17139
17140         /* refclassid constraint is redundant but may speed the search */
17141         appendPQExpBufferStr(query, "SELECT "
17142                                                  "classid, objid, refobjid "
17143                                                  "FROM pg_depend "
17144                                                  "WHERE refclassid = 'pg_extension'::regclass "
17145                                                  "AND deptype = 'e' "
17146                                                  "ORDER BY 3");
17147
17148         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17149
17150         ntups = PQntuples(res);
17151
17152         i_classid = PQfnumber(res, "classid");
17153         i_objid = PQfnumber(res, "objid");
17154         i_refobjid = PQfnumber(res, "refobjid");
17155
17156         extmembers = (ExtensionMemberId *) pg_malloc(ntups * sizeof(ExtensionMemberId));
17157         nextmembers = 0;
17158
17159         /*
17160          * Accumulate data into extmembers[].
17161          *
17162          * Since we ordered the SELECT by referenced ID, we can expect that
17163          * multiple entries for the same extension will appear together; this
17164          * saves on searches.
17165          */
17166         ext = NULL;
17167
17168         for (i = 0; i < ntups; i++)
17169         {
17170                 CatalogId       objId;
17171                 Oid                     extId;
17172
17173                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17174                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17175                 extId = atooid(PQgetvalue(res, i, i_refobjid));
17176
17177                 if (ext == NULL ||
17178                         ext->dobj.catId.oid != extId)
17179                         ext = findExtensionByOid(extId);
17180
17181                 if (ext == NULL)
17182                 {
17183                         /* shouldn't happen */
17184                         fprintf(stderr, "could not find referenced extension %u\n", extId);
17185                         continue;
17186                 }
17187
17188                 extmembers[nextmembers].catId = objId;
17189                 extmembers[nextmembers].ext = ext;
17190                 nextmembers++;
17191         }
17192
17193         PQclear(res);
17194
17195         /* Remember the data for use later */
17196         setExtensionMembership(extmembers, nextmembers);
17197
17198         destroyPQExpBuffer(query);
17199 }
17200
17201 /*
17202  * processExtensionTables --- deal with extension configuration tables
17203  *
17204  * There are two parts to this process:
17205  *
17206  * 1. Identify and create dump records for extension configuration tables.
17207  *
17208  *        Extensions can mark tables as "configuration", which means that the user
17209  *        is able and expected to modify those tables after the extension has been
17210  *        loaded.  For these tables, we dump out only the data- the structure is
17211  *        expected to be handled at CREATE EXTENSION time, including any indexes or
17212  *        foreign keys, which brings us to-
17213  *
17214  * 2. Record FK dependencies between configuration tables.
17215  *
17216  *        Due to the FKs being created at CREATE EXTENSION time and therefore before
17217  *        the data is loaded, we have to work out what the best order for reloading
17218  *        the data is, to avoid FK violations when the tables are restored.  This is
17219  *        not perfect- we can't handle circular dependencies and if any exist they
17220  *        will cause an invalid dump to be produced (though at least all of the data
17221  *        is included for a user to manually restore).  This is currently documented
17222  *        but perhaps we can provide a better solution in the future.
17223  */
17224 void
17225 processExtensionTables(Archive *fout, ExtensionInfo extinfo[],
17226                                            int numExtensions)
17227 {
17228         DumpOptions *dopt = fout->dopt;
17229         PQExpBuffer query;
17230         PGresult   *res;
17231         int                     ntups,
17232                                 i;
17233         int                     i_conrelid,
17234                                 i_confrelid;
17235
17236         /* Nothing to do if no extensions */
17237         if (numExtensions == 0)
17238                 return;
17239
17240         /*
17241          * Identify extension configuration tables and create TableDataInfo
17242          * objects for them, ensuring their data will be dumped even though the
17243          * tables themselves won't be.
17244          *
17245          * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
17246          * user data in a configuration table is treated like schema data. This
17247          * seems appropriate since system data in a config table would get
17248          * reloaded by CREATE EXTENSION.
17249          */
17250         for (i = 0; i < numExtensions; i++)
17251         {
17252                 ExtensionInfo *curext = &(extinfo[i]);
17253                 char       *extconfig = curext->extconfig;
17254                 char       *extcondition = curext->extcondition;
17255                 char      **extconfigarray = NULL;
17256                 char      **extconditionarray = NULL;
17257                 int                     nconfigitems;
17258                 int                     nconditionitems;
17259
17260                 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
17261                         parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
17262                         nconfigitems == nconditionitems)
17263                 {
17264                         int                     j;
17265
17266                         for (j = 0; j < nconfigitems; j++)
17267                         {
17268                                 TableInfo  *configtbl;
17269                                 Oid                     configtbloid = atooid(extconfigarray[j]);
17270                                 bool            dumpobj =
17271                                 curext->dobj.dump & DUMP_COMPONENT_DEFINITION;
17272
17273                                 configtbl = findTableByOid(configtbloid);
17274                                 if (configtbl == NULL)
17275                                         continue;
17276
17277                                 /*
17278                                  * Tables of not-to-be-dumped extensions shouldn't be dumped
17279                                  * unless the table or its schema is explicitly included
17280                                  */
17281                                 if (!(curext->dobj.dump & DUMP_COMPONENT_DEFINITION))
17282                                 {
17283                                         /* check table explicitly requested */
17284                                         if (table_include_oids.head != NULL &&
17285                                                 simple_oid_list_member(&table_include_oids,
17286                                                                                            configtbloid))
17287                                                 dumpobj = true;
17288
17289                                         /* check table's schema explicitly requested */
17290                                         if (configtbl->dobj.namespace->dobj.dump &
17291                                                 DUMP_COMPONENT_DATA)
17292                                                 dumpobj = true;
17293                                 }
17294
17295                                 /* check table excluded by an exclusion switch */
17296                                 if (table_exclude_oids.head != NULL &&
17297                                         simple_oid_list_member(&table_exclude_oids,
17298                                                                                    configtbloid))
17299                                         dumpobj = false;
17300
17301                                 /* check schema excluded by an exclusion switch */
17302                                 if (simple_oid_list_member(&schema_exclude_oids,
17303                                                                                    configtbl->dobj.namespace->dobj.catId.oid))
17304                                         dumpobj = false;
17305
17306                                 if (dumpobj)
17307                                 {
17308                                         /*
17309                                          * Note: config tables are dumped without OIDs regardless
17310                                          * of the --oids setting.  This is because row filtering
17311                                          * conditions aren't compatible with dumping OIDs.
17312                                          */
17313                                         makeTableDataInfo(dopt, configtbl, false);
17314                                         if (configtbl->dataObj != NULL)
17315                                         {
17316                                                 if (strlen(extconditionarray[j]) > 0)
17317                                                         configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
17318                                         }
17319                                 }
17320                         }
17321                 }
17322                 if (extconfigarray)
17323                         free(extconfigarray);
17324                 if (extconditionarray)
17325                         free(extconditionarray);
17326         }
17327
17328         /*
17329          * Now that all the TableInfoData objects have been created for all the
17330          * extensions, check their FK dependencies and register them to try and
17331          * dump the data out in an order that they can be restored in.
17332          *
17333          * Note that this is not a problem for user tables as their FKs are
17334          * recreated after the data has been loaded.
17335          */
17336
17337         /* Make sure we are in proper schema */
17338         selectSourceSchema(fout, "pg_catalog");
17339
17340         query = createPQExpBuffer();
17341
17342         printfPQExpBuffer(query,
17343                                           "SELECT conrelid, confrelid "
17344                                           "FROM pg_constraint "
17345                                           "JOIN pg_depend ON (objid = confrelid) "
17346                                           "WHERE contype = 'f' "
17347                                           "AND refclassid = 'pg_extension'::regclass "
17348                                           "AND classid = 'pg_class'::regclass;");
17349
17350         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17351         ntups = PQntuples(res);
17352
17353         i_conrelid = PQfnumber(res, "conrelid");
17354         i_confrelid = PQfnumber(res, "confrelid");
17355
17356         /* Now get the dependencies and register them */
17357         for (i = 0; i < ntups; i++)
17358         {
17359                 Oid                     conrelid,
17360                                         confrelid;
17361                 TableInfo  *reftable,
17362                                    *contable;
17363
17364                 conrelid = atooid(PQgetvalue(res, i, i_conrelid));
17365                 confrelid = atooid(PQgetvalue(res, i, i_confrelid));
17366                 contable = findTableByOid(conrelid);
17367                 reftable = findTableByOid(confrelid);
17368
17369                 if (reftable == NULL ||
17370                         reftable->dataObj == NULL ||
17371                         contable == NULL ||
17372                         contable->dataObj == NULL)
17373                         continue;
17374
17375                 /*
17376                  * Make referencing TABLE_DATA object depend on the referenced table's
17377                  * TABLE_DATA object.
17378                  */
17379                 addObjectDependency(&contable->dataObj->dobj,
17380                                                         reftable->dataObj->dobj.dumpId);
17381         }
17382         PQclear(res);
17383         destroyPQExpBuffer(query);
17384 }
17385
17386 /*
17387  * getDependencies --- obtain available dependency data
17388  */
17389 static void
17390 getDependencies(Archive *fout)
17391 {
17392         PQExpBuffer query;
17393         PGresult   *res;
17394         int                     ntups,
17395                                 i;
17396         int                     i_classid,
17397                                 i_objid,
17398                                 i_refclassid,
17399                                 i_refobjid,
17400                                 i_deptype;
17401         DumpableObject *dobj,
17402                            *refdobj;
17403
17404         if (g_verbose)
17405                 write_msg(NULL, "reading dependency data\n");
17406
17407         /* Make sure we are in proper schema */
17408         selectSourceSchema(fout, "pg_catalog");
17409
17410         query = createPQExpBuffer();
17411
17412         /*
17413          * PIN dependencies aren't interesting, and EXTENSION dependencies were
17414          * already processed by getExtensionMembership.
17415          */
17416         appendPQExpBufferStr(query, "SELECT "
17417                                                  "classid, objid, refclassid, refobjid, deptype "
17418                                                  "FROM pg_depend "
17419                                                  "WHERE deptype != 'p' AND deptype != 'e' "
17420                                                  "ORDER BY 1,2");
17421
17422         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17423
17424         ntups = PQntuples(res);
17425
17426         i_classid = PQfnumber(res, "classid");
17427         i_objid = PQfnumber(res, "objid");
17428         i_refclassid = PQfnumber(res, "refclassid");
17429         i_refobjid = PQfnumber(res, "refobjid");
17430         i_deptype = PQfnumber(res, "deptype");
17431
17432         /*
17433          * Since we ordered the SELECT by referencing ID, we can expect that
17434          * multiple entries for the same object will appear together; this saves
17435          * on searches.
17436          */
17437         dobj = NULL;
17438
17439         for (i = 0; i < ntups; i++)
17440         {
17441                 CatalogId       objId;
17442                 CatalogId       refobjId;
17443                 char            deptype;
17444
17445                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
17446                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
17447                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
17448                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
17449                 deptype = *(PQgetvalue(res, i, i_deptype));
17450
17451                 if (dobj == NULL ||
17452                         dobj->catId.tableoid != objId.tableoid ||
17453                         dobj->catId.oid != objId.oid)
17454                         dobj = findObjectByCatalogId(objId);
17455
17456                 /*
17457                  * Failure to find objects mentioned in pg_depend is not unexpected,
17458                  * since for example we don't collect info about TOAST tables.
17459                  */
17460                 if (dobj == NULL)
17461                 {
17462 #ifdef NOT_USED
17463                         fprintf(stderr, "no referencing object %u %u\n",
17464                                         objId.tableoid, objId.oid);
17465 #endif
17466                         continue;
17467                 }
17468
17469                 refdobj = findObjectByCatalogId(refobjId);
17470
17471                 if (refdobj == NULL)
17472                 {
17473 #ifdef NOT_USED
17474                         fprintf(stderr, "no referenced object %u %u\n",
17475                                         refobjId.tableoid, refobjId.oid);
17476 #endif
17477                         continue;
17478                 }
17479
17480                 /*
17481                  * Ordinarily, table rowtypes have implicit dependencies on their
17482                  * tables.  However, for a composite type the implicit dependency goes
17483                  * the other way in pg_depend; which is the right thing for DROP but
17484                  * it doesn't produce the dependency ordering we need. So in that one
17485                  * case, we reverse the direction of the dependency.
17486                  */
17487                 if (deptype == 'i' &&
17488                         dobj->objType == DO_TABLE &&
17489                         refdobj->objType == DO_TYPE)
17490                         addObjectDependency(refdobj, dobj->dumpId);
17491                 else
17492                         /* normal case */
17493                         addObjectDependency(dobj, refdobj->dumpId);
17494         }
17495
17496         PQclear(res);
17497
17498         destroyPQExpBuffer(query);
17499 }
17500
17501
17502 /*
17503  * createBoundaryObjects - create dummy DumpableObjects to represent
17504  * dump section boundaries.
17505  */
17506 static DumpableObject *
17507 createBoundaryObjects(void)
17508 {
17509         DumpableObject *dobjs;
17510
17511         dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
17512
17513         dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
17514         dobjs[0].catId = nilCatalogId;
17515         AssignDumpId(dobjs + 0);
17516         dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
17517
17518         dobjs[1].objType = DO_POST_DATA_BOUNDARY;
17519         dobjs[1].catId = nilCatalogId;
17520         AssignDumpId(dobjs + 1);
17521         dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
17522
17523         return dobjs;
17524 }
17525
17526 /*
17527  * addBoundaryDependencies - add dependencies as needed to enforce the dump
17528  * section boundaries.
17529  */
17530 static void
17531 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
17532                                                 DumpableObject *boundaryObjs)
17533 {
17534         DumpableObject *preDataBound = boundaryObjs + 0;
17535         DumpableObject *postDataBound = boundaryObjs + 1;
17536         int                     i;
17537
17538         for (i = 0; i < numObjs; i++)
17539         {
17540                 DumpableObject *dobj = dobjs[i];
17541
17542                 /*
17543                  * The classification of object types here must match the SECTION_xxx
17544                  * values assigned during subsequent ArchiveEntry calls!
17545                  */
17546                 switch (dobj->objType)
17547                 {
17548                         case DO_NAMESPACE:
17549                         case DO_EXTENSION:
17550                         case DO_TYPE:
17551                         case DO_SHELL_TYPE:
17552                         case DO_FUNC:
17553                         case DO_AGG:
17554                         case DO_OPERATOR:
17555                         case DO_ACCESS_METHOD:
17556                         case DO_OPCLASS:
17557                         case DO_OPFAMILY:
17558                         case DO_COLLATION:
17559                         case DO_CONVERSION:
17560                         case DO_TABLE:
17561                         case DO_ATTRDEF:
17562                         case DO_PROCLANG:
17563                         case DO_CAST:
17564                         case DO_DUMMY_TYPE:
17565                         case DO_TSPARSER:
17566                         case DO_TSDICT:
17567                         case DO_TSTEMPLATE:
17568                         case DO_TSCONFIG:
17569                         case DO_FDW:
17570                         case DO_FOREIGN_SERVER:
17571                         case DO_TRANSFORM:
17572                         case DO_BLOB:
17573                                 /* Pre-data objects: must come before the pre-data boundary */
17574                                 addObjectDependency(preDataBound, dobj->dumpId);
17575                                 break;
17576                         case DO_TABLE_DATA:
17577                         case DO_SEQUENCE_SET:
17578                         case DO_BLOB_DATA:
17579                                 /* Data objects: must come between the boundaries */
17580                                 addObjectDependency(dobj, preDataBound->dumpId);
17581                                 addObjectDependency(postDataBound, dobj->dumpId);
17582                                 break;
17583                         case DO_INDEX:
17584                         case DO_STATSEXT:
17585                         case DO_REFRESH_MATVIEW:
17586                         case DO_TRIGGER:
17587                         case DO_EVENT_TRIGGER:
17588                         case DO_DEFAULT_ACL:
17589                         case DO_POLICY:
17590                         case DO_PUBLICATION:
17591                         case DO_PUBLICATION_REL:
17592                         case DO_SUBSCRIPTION:
17593                                 /* Post-data objects: must come after the post-data boundary */
17594                                 addObjectDependency(dobj, postDataBound->dumpId);
17595                                 break;
17596                         case DO_RULE:
17597                                 /* Rules are post-data, but only if dumped separately */
17598                                 if (((RuleInfo *) dobj)->separate)
17599                                         addObjectDependency(dobj, postDataBound->dumpId);
17600                                 break;
17601                         case DO_CONSTRAINT:
17602                         case DO_FK_CONSTRAINT:
17603                                 /* Constraints are post-data, but only if dumped separately */
17604                                 if (((ConstraintInfo *) dobj)->separate)
17605                                         addObjectDependency(dobj, postDataBound->dumpId);
17606                                 break;
17607                         case DO_PRE_DATA_BOUNDARY:
17608                                 /* nothing to do */
17609                                 break;
17610                         case DO_POST_DATA_BOUNDARY:
17611                                 /* must come after the pre-data boundary */
17612                                 addObjectDependency(dobj, preDataBound->dumpId);
17613                                 break;
17614                 }
17615         }
17616 }
17617
17618
17619 /*
17620  * BuildArchiveDependencies - create dependency data for archive TOC entries
17621  *
17622  * The raw dependency data obtained by getDependencies() is not terribly
17623  * useful in an archive dump, because in many cases there are dependency
17624  * chains linking through objects that don't appear explicitly in the dump.
17625  * For example, a view will depend on its _RETURN rule while the _RETURN rule
17626  * will depend on other objects --- but the rule will not appear as a separate
17627  * object in the dump.  We need to adjust the view's dependencies to include
17628  * whatever the rule depends on that is included in the dump.
17629  *
17630  * Just to make things more complicated, there are also "special" dependencies
17631  * such as the dependency of a TABLE DATA item on its TABLE, which we must
17632  * not rearrange because pg_restore knows that TABLE DATA only depends on
17633  * its table.  In these cases we must leave the dependencies strictly as-is
17634  * even if they refer to not-to-be-dumped objects.
17635  *
17636  * To handle this, the convention is that "special" dependencies are created
17637  * during ArchiveEntry calls, and an archive TOC item that has any such
17638  * entries will not be touched here.  Otherwise, we recursively search the
17639  * DumpableObject data structures to build the correct dependencies for each
17640  * archive TOC item.
17641  */
17642 static void
17643 BuildArchiveDependencies(Archive *fout)
17644 {
17645         ArchiveHandle *AH = (ArchiveHandle *) fout;
17646         TocEntry   *te;
17647
17648         /* Scan all TOC entries in the archive */
17649         for (te = AH->toc->next; te != AH->toc; te = te->next)
17650         {
17651                 DumpableObject *dobj;
17652                 DumpId     *dependencies;
17653                 int                     nDeps;
17654                 int                     allocDeps;
17655
17656                 /* No need to process entries that will not be dumped */
17657                 if (te->reqs == 0)
17658                         continue;
17659                 /* Ignore entries that already have "special" dependencies */
17660                 if (te->nDeps > 0)
17661                         continue;
17662                 /* Otherwise, look up the item's original DumpableObject, if any */
17663                 dobj = findObjectByDumpId(te->dumpId);
17664                 if (dobj == NULL)
17665                         continue;
17666                 /* No work if it has no dependencies */
17667                 if (dobj->nDeps <= 0)
17668                         continue;
17669                 /* Set up work array */
17670                 allocDeps = 64;
17671                 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
17672                 nDeps = 0;
17673                 /* Recursively find all dumpable dependencies */
17674                 findDumpableDependencies(AH, dobj,
17675                                                                  &dependencies, &nDeps, &allocDeps);
17676                 /* And save 'em ... */
17677                 if (nDeps > 0)
17678                 {
17679                         dependencies = (DumpId *) pg_realloc(dependencies,
17680                                                                                                  nDeps * sizeof(DumpId));
17681                         te->dependencies = dependencies;
17682                         te->nDeps = nDeps;
17683                 }
17684                 else
17685                         free(dependencies);
17686         }
17687 }
17688
17689 /* Recursive search subroutine for BuildArchiveDependencies */
17690 static void
17691 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
17692                                                  DumpId **dependencies, int *nDeps, int *allocDeps)
17693 {
17694         int                     i;
17695
17696         /*
17697          * Ignore section boundary objects: if we search through them, we'll
17698          * report lots of bogus dependencies.
17699          */
17700         if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
17701                 dobj->objType == DO_POST_DATA_BOUNDARY)
17702                 return;
17703
17704         for (i = 0; i < dobj->nDeps; i++)
17705         {
17706                 DumpId          depid = dobj->dependencies[i];
17707
17708                 if (TocIDRequired(AH, depid) != 0)
17709                 {
17710                         /* Object will be dumped, so just reference it as a dependency */
17711                         if (*nDeps >= *allocDeps)
17712                         {
17713                                 *allocDeps *= 2;
17714                                 *dependencies = (DumpId *) pg_realloc(*dependencies,
17715                                                                                                           *allocDeps * sizeof(DumpId));
17716                         }
17717                         (*dependencies)[*nDeps] = depid;
17718                         (*nDeps)++;
17719                 }
17720                 else
17721                 {
17722                         /*
17723                          * Object will not be dumped, so recursively consider its deps. We
17724                          * rely on the assumption that sortDumpableObjects already broke
17725                          * any dependency loops, else we might recurse infinitely.
17726                          */
17727                         DumpableObject *otherdobj = findObjectByDumpId(depid);
17728
17729                         if (otherdobj)
17730                                 findDumpableDependencies(AH, otherdobj,
17731                                                                                  dependencies, nDeps, allocDeps);
17732                 }
17733         }
17734 }
17735
17736
17737 /*
17738  * selectSourceSchema - make the specified schema the active search path
17739  * in the source database.
17740  *
17741  * NB: pg_catalog is explicitly searched after the specified schema;
17742  * so user names are only qualified if they are cross-schema references,
17743  * and system names are only qualified if they conflict with a user name
17744  * in the current schema.
17745  *
17746  * Whenever the selected schema is not pg_catalog, be careful to qualify
17747  * references to system catalogs and types in our emitted commands!
17748  *
17749  * This function is called only from selectSourceSchemaOnAH and
17750  * selectSourceSchema.
17751  */
17752 static void
17753 selectSourceSchema(Archive *fout, const char *schemaName)
17754 {
17755         PQExpBuffer query;
17756
17757         /* This is checked by the callers already */
17758         Assert(schemaName != NULL && *schemaName != '\0');
17759
17760         query = createPQExpBuffer();
17761         appendPQExpBuffer(query, "SET search_path = %s",
17762                                           fmtId(schemaName));
17763         if (strcmp(schemaName, "pg_catalog") != 0)
17764                 appendPQExpBufferStr(query, ", pg_catalog");
17765
17766         ExecuteSqlStatement(fout, query->data);
17767
17768         destroyPQExpBuffer(query);
17769 }
17770
17771 /*
17772  * getFormattedTypeName - retrieve a nicely-formatted type name for the
17773  * given type name.
17774  *
17775  * NB: the result may depend on the currently-selected search_path; this is
17776  * why we don't try to cache the names.
17777  */
17778 static char *
17779 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
17780 {
17781         char       *result;
17782         PQExpBuffer query;
17783         PGresult   *res;
17784
17785         if (oid == 0)
17786         {
17787                 if ((opts & zeroAsOpaque) != 0)
17788                         return pg_strdup(g_opaque_type);
17789                 else if ((opts & zeroAsAny) != 0)
17790                         return pg_strdup("'any'");
17791                 else if ((opts & zeroAsStar) != 0)
17792                         return pg_strdup("*");
17793                 else if ((opts & zeroAsNone) != 0)
17794                         return pg_strdup("NONE");
17795         }
17796
17797         query = createPQExpBuffer();
17798         appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
17799                                           oid);
17800
17801         res = ExecuteSqlQueryForSingleRow(fout, query->data);
17802
17803         /* result of format_type is already quoted */
17804         result = pg_strdup(PQgetvalue(res, 0, 0));
17805
17806         PQclear(res);
17807         destroyPQExpBuffer(query);
17808
17809         return result;
17810 }
17811
17812 /*
17813  * Return a column list clause for the given relation.
17814  *
17815  * Special case: if there are no undropped columns in the relation, return
17816  * "", not an invalid "()" column list.
17817  */
17818 static const char *
17819 fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer)
17820 {
17821         int                     numatts = ti->numatts;
17822         char      **attnames = ti->attnames;
17823         bool       *attisdropped = ti->attisdropped;
17824         bool            needComma;
17825         int                     i;
17826
17827         appendPQExpBufferChar(buffer, '(');
17828         needComma = false;
17829         for (i = 0; i < numatts; i++)
17830         {
17831                 if (attisdropped[i])
17832                         continue;
17833                 if (needComma)
17834                         appendPQExpBufferStr(buffer, ", ");
17835                 appendPQExpBufferStr(buffer, fmtId(attnames[i]));
17836                 needComma = true;
17837         }
17838
17839         if (!needComma)
17840                 return "";                              /* no undropped columns */
17841
17842         appendPQExpBufferChar(buffer, ')');
17843         return buffer->data;
17844 }
17845
17846 /*
17847  * Check if a reloptions array is nonempty.
17848  */
17849 static bool
17850 nonemptyReloptions(const char *reloptions)
17851 {
17852         /* Don't want to print it if it's just "{}" */
17853         return (reloptions != NULL && strlen(reloptions) > 2);
17854 }
17855
17856 /*
17857  * Format a reloptions array and append it to the given buffer.
17858  *
17859  * "prefix" is prepended to the option names; typically it's "" or "toast.".
17860  */
17861 static void
17862 appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
17863                                                 const char *prefix, Archive *fout)
17864 {
17865         bool            res;
17866
17867         res = appendReloptionsArray(buffer, reloptions, prefix, fout->encoding,
17868                                                                 fout->std_strings);
17869         if (!res)
17870                 write_msg(NULL, "WARNING: could not parse reloptions array\n");
17871 }