]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_dump.c
Create libpgcommon, and move pg_malloc et al to it
[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-2013, 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 run on
18  *      SnapshotNow time, ie they look at the currently committed state.  So
19  *      it is possible to get 'cache lookup failed' error if someone
20  *      performs DDL changes while a dump is happening. The window for this
21  *      sort of thing is from the acquisition of the transaction snapshot to
22  *      getSchemaData() (when pg_dump acquires AccessShareLock on every
23  *      table it intends to dump). It isn't very large, 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
33 #include "postgres_fe.h"
34
35 #include <unistd.h>
36 #include <ctype.h>
37 #ifdef ENABLE_NLS
38 #include <locale.h>
39 #endif
40 #ifdef HAVE_TERMIOS_H
41 #include <termios.h>
42 #endif
43
44 #include "getopt_long.h"
45
46 #include "access/attnum.h"
47 #include "access/sysattr.h"
48 #include "access/transam.h"
49 #include "catalog/pg_cast.h"
50 #include "catalog/pg_class.h"
51 #include "catalog/pg_default_acl.h"
52 #include "catalog/pg_event_trigger.h"
53 #include "catalog/pg_largeobject.h"
54 #include "catalog/pg_largeobject_metadata.h"
55 #include "catalog/pg_proc.h"
56 #include "catalog/pg_trigger.h"
57 #include "catalog/pg_type.h"
58 #include "libpq/libpq-fs.h"
59
60 #include "pg_backup_archiver.h"
61 #include "pg_backup_db.h"
62 #include "dumputils.h"
63
64 extern char *optarg;
65 extern int      optind,
66                         opterr;
67
68
69 typedef struct
70 {
71         const char *descr;                      /* comment for an object */
72         Oid                     classoid;               /* object class (catalog OID) */
73         Oid                     objoid;                 /* object OID */
74         int                     objsubid;               /* subobject (table column #) */
75 } CommentItem;
76
77 typedef struct
78 {
79         const char *provider;           /* label provider of this security label */
80         const char *label;                      /* security label for an object */
81         Oid                     classoid;               /* object class (catalog OID) */
82         Oid                     objoid;                 /* object OID */
83         int                     objsubid;               /* subobject (table column #) */
84 } SecLabelItem;
85
86 /* global decls */
87 bool            g_verbose;                      /* User wants verbose narration of our
88                                                                  * activities. */
89
90 /* various user-settable parameters */
91 bool            schemaOnly;
92 bool            dataOnly;
93 int                     dumpSections;           /* bitmask of chosen sections */
94 bool            aclsSkip;
95 const char *lockWaitTimeout;
96
97 /* subquery used to convert user ID (eg, datdba) to user name */
98 static const char *username_subquery;
99
100 /* obsolete as of 7.3: */
101 static Oid      g_last_builtin_oid; /* value of the last builtin oid */
102
103 /*
104  * Object inclusion/exclusion lists
105  *
106  * The string lists record the patterns given by command-line switches,
107  * which we then convert to lists of OIDs of matching objects.
108  */
109 static SimpleStringList schema_include_patterns = {NULL, NULL};
110 static SimpleOidList schema_include_oids = {NULL, NULL};
111 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
112 static SimpleOidList schema_exclude_oids = {NULL, NULL};
113
114 static SimpleStringList table_include_patterns = {NULL, NULL};
115 static SimpleOidList table_include_oids = {NULL, NULL};
116 static SimpleStringList table_exclude_patterns = {NULL, NULL};
117 static SimpleOidList table_exclude_oids = {NULL, NULL};
118 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
119 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
120
121 /* default, if no "inclusion" switches appear, is to dump everything */
122 static bool include_everything = true;
123
124 char            g_opaque_type[10];      /* name for the opaque type */
125
126 /* placeholders for the delimiters for comments */
127 char            g_comment_start[10];
128 char            g_comment_end[10];
129
130 static const CatalogId nilCatalogId = {0, 0};
131
132 /* flags for various command-line long options */
133 static int      binary_upgrade = 0;
134 static int      disable_dollar_quoting = 0;
135 static int      dump_inserts = 0;
136 static int      column_inserts = 0;
137 static int      no_security_labels = 0;
138 static int      no_unlogged_table_data = 0;
139 static int      serializable_deferrable = 0;
140
141
142 static void help(const char *progname);
143 static void setup_connection(Archive *AH, const char *dumpencoding,
144                                  char *use_role);
145 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
146 static void expand_schema_name_patterns(Archive *fout,
147                                                         SimpleStringList *patterns,
148                                                         SimpleOidList *oids);
149 static void expand_table_name_patterns(Archive *fout,
150                                                    SimpleStringList *patterns,
151                                                    SimpleOidList *oids);
152 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid, Oid objoid);
153 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
154 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
155 static void dumpComment(Archive *fout, const char *target,
156                         const char *namespace, const char *owner,
157                         CatalogId catalogId, int subid, DumpId dumpId);
158 static int findComments(Archive *fout, Oid classoid, Oid objoid,
159                          CommentItem **items);
160 static int      collectComments(Archive *fout, CommentItem **items);
161 static void dumpSecLabel(Archive *fout, const char *target,
162                          const char *namespace, const char *owner,
163                          CatalogId catalogId, int subid, DumpId dumpId);
164 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
165                           SecLabelItem **items);
166 static int      collectSecLabels(Archive *fout, SecLabelItem **items);
167 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
168 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
169 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
170 static void dumpType(Archive *fout, TypeInfo *tyinfo);
171 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
172 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
173 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
174 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
175 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
176 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
177 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
178 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
179 static void dumpFunc(Archive *fout, FuncInfo *finfo);
180 static void dumpCast(Archive *fout, CastInfo *cast);
181 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
182 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
183 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
184 static void dumpCollation(Archive *fout, CollInfo *convinfo);
185 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
186 static void dumpRule(Archive *fout, RuleInfo *rinfo);
187 static void dumpAgg(Archive *fout, AggInfo *agginfo);
188 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
189 static void dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo);
190 static void dumpTable(Archive *fout, TableInfo *tbinfo);
191 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
192 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
193 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
194 static void dumpSequenceData(Archive *fout, TableDataInfo *tdinfo);
195 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
196 static void 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);
213
214 static void getDependencies(Archive *fout);
215 static void BuildArchiveDependencies(Archive *fout);
216 static void findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
217                                                  DumpId **dependencies, int *nDeps, int *allocDeps);
218
219 static DumpableObject *createBoundaryObjects(void);
220 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
221                                                 DumpableObject *boundaryObjs);
222
223 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
224 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
225 static void makeTableDataInfo(TableInfo *tbinfo, bool oids);
226 static void getTableDataFKConstraints(void);
227 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
228 static char *format_function_arguments_old(Archive *fout,
229                                                           FuncInfo *finfo, int nallargs,
230                                                           char **allargtypes,
231                                                           char **argmodes,
232                                                           char **argnames);
233 static char *format_function_signature(Archive *fout,
234                                                   FuncInfo *finfo, bool honor_quotes);
235 static const char *convertRegProcReference(Archive *fout,
236                                                 const char *proc);
237 static const char *convertOperatorReference(Archive *fout, const char *opr);
238 static const char *convertTSFunction(Archive *fout, Oid funcOid);
239 static Oid      findLastBuiltinOid_V71(Archive *fout, const char *);
240 static Oid      findLastBuiltinOid_V70(Archive *fout);
241 static void selectSourceSchema(Archive *fout, const char *schemaName);
242 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
243 static char *myFormatType(const char *typname, int32 typmod);
244 static const char *fmtQualifiedId(Archive *fout,
245                            const char *schema, const char *id);
246 static void getBlobs(Archive *fout);
247 static void dumpBlob(Archive *fout, BlobInfo *binfo);
248 static int      dumpBlobs(Archive *fout, void *arg);
249 static void dumpDatabase(Archive *AH);
250 static void dumpEncoding(Archive *AH);
251 static void dumpStdStrings(Archive *AH);
252 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
253                                                                 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
254 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
255                                                                  PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
256 static void binary_upgrade_set_pg_class_oids(Archive *fout,
257                                                                  PQExpBuffer upgrade_buffer,
258                                                                  Oid pg_class_oid, bool is_index);
259 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
260                                                                 DumpableObject *dobj,
261                                                                 const char *objlabel);
262 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
263 static const char *fmtCopyColumnList(const TableInfo *ti);
264 static PGresult *ExecuteSqlQueryForSingleRow(Archive *fout, char *query);
265
266
267 int
268 main(int argc, char **argv)
269 {
270         int                     c;
271         const char *filename = NULL;
272         const char *format = "p";
273         const char *dbname = NULL;
274         const char *pghost = NULL;
275         const char *pgport = NULL;
276         const char *username = NULL;
277         const char *dumpencoding = NULL;
278         bool            oids = false;
279         TableInfo  *tblinfo;
280         int                     numTables;
281         DumpableObject **dobjs;
282         int                     numObjs;
283         DumpableObject *boundaryObjs;
284         int                     i;
285         enum trivalue prompt_password = TRI_DEFAULT;
286         int                     compressLevel = -1;
287         int                     plainText = 0;
288         int                     outputClean = 0;
289         int                     outputCreateDB = 0;
290         bool            outputBlobs = false;
291         int                     outputNoOwner = 0;
292         char       *outputSuperuser = NULL;
293         char       *use_role = NULL;
294         int                     my_version;
295         int                     optindex;
296         RestoreOptions *ropt;
297         ArchiveFormat archiveFormat = archUnknown;
298         ArchiveMode archiveMode;
299         Archive    *fout;                       /* the script file */
300
301         static int      disable_triggers = 0;
302         static int      outputNoTablespaces = 0;
303         static int      use_setsessauth = 0;
304
305         static struct option long_options[] = {
306                 {"data-only", no_argument, NULL, 'a'},
307                 {"blobs", no_argument, NULL, 'b'},
308                 {"clean", no_argument, NULL, 'c'},
309                 {"create", no_argument, NULL, 'C'},
310                 {"file", required_argument, NULL, 'f'},
311                 {"format", required_argument, NULL, 'F'},
312                 {"host", required_argument, NULL, 'h'},
313                 {"ignore-version", no_argument, NULL, 'i'},
314                 {"no-reconnect", no_argument, NULL, 'R'},
315                 {"oids", no_argument, NULL, 'o'},
316                 {"no-owner", no_argument, NULL, 'O'},
317                 {"port", required_argument, NULL, 'p'},
318                 {"schema", required_argument, NULL, 'n'},
319                 {"exclude-schema", required_argument, NULL, 'N'},
320                 {"schema-only", no_argument, NULL, 's'},
321                 {"superuser", required_argument, NULL, 'S'},
322                 {"table", required_argument, NULL, 't'},
323                 {"exclude-table", required_argument, NULL, 'T'},
324                 {"no-password", no_argument, NULL, 'w'},
325                 {"password", no_argument, NULL, 'W'},
326                 {"username", required_argument, NULL, 'U'},
327                 {"verbose", no_argument, NULL, 'v'},
328                 {"no-privileges", no_argument, NULL, 'x'},
329                 {"no-acl", no_argument, NULL, 'x'},
330                 {"compress", required_argument, NULL, 'Z'},
331                 {"encoding", required_argument, NULL, 'E'},
332                 {"help", no_argument, NULL, '?'},
333                 {"version", no_argument, NULL, 'V'},
334
335                 /*
336                  * the following options don't have an equivalent short option letter
337                  */
338                 {"attribute-inserts", no_argument, &column_inserts, 1},
339                 {"binary-upgrade", no_argument, &binary_upgrade, 1},
340                 {"column-inserts", no_argument, &column_inserts, 1},
341                 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
342                 {"disable-triggers", no_argument, &disable_triggers, 1},
343                 {"exclude-table-data", required_argument, NULL, 4},
344                 {"inserts", no_argument, &dump_inserts, 1},
345                 {"lock-wait-timeout", required_argument, NULL, 2},
346                 {"no-tablespaces", no_argument, &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, &serializable_deferrable, 1},
351                 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
352                 {"no-security-labels", no_argument, &no_security_labels, 1},
353                 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
354
355                 {NULL, 0, NULL, 0}
356         };
357
358         set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
359
360         g_verbose = false;
361
362         strcpy(g_comment_start, "-- ");
363         g_comment_end[0] = '\0';
364         strcpy(g_opaque_type, "opaque");
365
366         dataOnly = schemaOnly = false;
367         dumpSections = DUMP_UNSECTIONED;
368         lockWaitTimeout = NULL;
369
370         progname = get_progname(argv[0]);
371
372         /* Set default options based on progname */
373         if (strcmp(progname, "pg_backup") == 0)
374                 format = "c";
375
376         if (argc > 1)
377         {
378                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
379                 {
380                         help(progname);
381                         exit_nicely(0);
382                 }
383                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
384                 {
385                         puts("pg_dump (PostgreSQL) " PG_VERSION);
386                         exit_nicely(0);
387                 }
388         }
389
390         while ((c = getopt_long(argc, argv, "abcCE:f:F:h:in:N:oOp:RsS:t:T:U:vwWxZ:",
391                                                         long_options, &optindex)) != -1)
392         {
393                 switch (c)
394                 {
395                         case 'a':                       /* Dump data only */
396                                 dataOnly = true;
397                                 break;
398
399                         case 'b':                       /* Dump blobs */
400                                 outputBlobs = true;
401                                 break;
402
403                         case 'c':                       /* clean (i.e., drop) schema prior to create */
404                                 outputClean = 1;
405                                 break;
406
407                         case 'C':                       /* Create DB */
408                                 outputCreateDB = 1;
409                                 break;
410
411                         case 'E':                       /* Dump encoding */
412                                 dumpencoding = pg_strdup(optarg);
413                                 break;
414
415                         case 'f':
416                                 filename = pg_strdup(optarg);
417                                 break;
418
419                         case 'F':
420                                 format = pg_strdup(optarg);
421                                 break;
422
423                         case 'h':                       /* server host */
424                                 pghost = pg_strdup(optarg);
425                                 break;
426
427                         case 'i':
428                                 /* ignored, deprecated option */
429                                 break;
430
431                         case 'n':                       /* include schema(s) */
432                                 simple_string_list_append(&schema_include_patterns, optarg);
433                                 include_everything = false;
434                                 break;
435
436                         case 'N':                       /* exclude schema(s) */
437                                 simple_string_list_append(&schema_exclude_patterns, optarg);
438                                 break;
439
440                         case 'o':                       /* Dump oids */
441                                 oids = true;
442                                 break;
443
444                         case 'O':                       /* Don't reconnect to match owner */
445                                 outputNoOwner = 1;
446                                 break;
447
448                         case 'p':                       /* server port */
449                                 pgport = pg_strdup(optarg);
450                                 break;
451
452                         case 'R':
453                                 /* no-op, still accepted for backwards compatibility */
454                                 break;
455
456                         case 's':                       /* dump schema only */
457                                 schemaOnly = true;
458                                 break;
459
460                         case 'S':                       /* Username for superuser in plain text output */
461                                 outputSuperuser = pg_strdup(optarg);
462                                 break;
463
464                         case 't':                       /* include table(s) */
465                                 simple_string_list_append(&table_include_patterns, optarg);
466                                 include_everything = false;
467                                 break;
468
469                         case 'T':                       /* exclude table(s) */
470                                 simple_string_list_append(&table_exclude_patterns, optarg);
471                                 break;
472
473                         case 'U':
474                                 username = pg_strdup(optarg);
475                                 break;
476
477                         case 'v':                       /* verbose */
478                                 g_verbose = true;
479                                 break;
480
481                         case 'w':
482                                 prompt_password = TRI_NO;
483                                 break;
484
485                         case 'W':
486                                 prompt_password = TRI_YES;
487                                 break;
488
489                         case 'x':                       /* skip ACL dump */
490                                 aclsSkip = true;
491                                 break;
492
493                         case 'Z':                       /* Compression Level */
494                                 compressLevel = atoi(optarg);
495                                 break;
496
497                         case 0:
498                                 /* This covers the long options. */
499                                 break;
500
501                         case 2:                         /* lock-wait-timeout */
502                                 lockWaitTimeout = pg_strdup(optarg);
503                                 break;
504
505                         case 3:                         /* SET ROLE */
506                                 use_role = pg_strdup(optarg);
507                                 break;
508
509                         case 4:                         /* exclude table(s) data */
510                                 simple_string_list_append(&tabledata_exclude_patterns, optarg);
511                                 break;
512
513                         case 5:                         /* section */
514                                 set_dump_section(optarg, &dumpSections);
515                                 break;
516
517                         default:
518                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
519                                 exit_nicely(1);
520                 }
521         }
522
523         /* Get database name from command line */
524         if (optind < argc)
525                 dbname = argv[optind++];
526
527         /* Complain if any arguments remain */
528         if (optind < argc)
529         {
530                 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
531                                 progname, argv[optind]);
532                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
533                                 progname);
534                 exit_nicely(1);
535         }
536
537         /* --column-inserts implies --inserts */
538         if (column_inserts)
539                 dump_inserts = 1;
540
541         if (dataOnly && schemaOnly)
542                 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
543
544         if (dataOnly && outputClean)
545                 exit_horribly(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
546
547         if (dump_inserts && oids)
548         {
549                 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
550                 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
551                 exit_nicely(1);
552         }
553
554         /* Identify archive format to emit */
555         archiveFormat = parseArchiveFormat(format, &archiveMode);
556
557         /* archiveFormat specific setup */
558         if (archiveFormat == archNull)
559                 plainText = 1;
560
561         /* Custom and directory formats are compressed by default, others not */
562         if (compressLevel == -1)
563         {
564                 if (archiveFormat == archCustom || archiveFormat == archDirectory)
565                         compressLevel = Z_DEFAULT_COMPRESSION;
566                 else
567                         compressLevel = 0;
568         }
569
570         /* Open the output file */
571         fout = CreateArchive(filename, archiveFormat, compressLevel, archiveMode);
572
573         /* Register the cleanup hook */
574         on_exit_close_archive(fout);
575
576         if (fout == NULL)
577                 exit_horribly(NULL, "could not open output file \"%s\" for writing\n", filename);
578
579         /* Let the archiver know how noisy to be */
580         fout->verbose = g_verbose;
581
582         my_version = parse_version(PG_VERSION);
583         if (my_version < 0)
584                 exit_horribly(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
585
586         /*
587          * We allow the server to be back to 7.0, and up to any minor release of
588          * our own major version.  (See also version check in pg_dumpall.c.)
589          */
590         fout->minRemoteVersion = 70000;
591         fout->maxRemoteVersion = (my_version / 100) * 100 + 99;
592
593         /*
594          * Open the database using the Archiver, so it knows about it. Errors mean
595          * death.
596          */
597         ConnectDatabase(fout, dbname, pghost, pgport, username, prompt_password);
598         setup_connection(fout, dumpencoding, use_role);
599
600         /*
601          * Disable security label support if server version < v9.1.x (prevents
602          * access to nonexistent pg_seclabel catalog)
603          */
604         if (fout->remoteVersion < 90100)
605                 no_security_labels = 1;
606
607         /*
608          * When running against 9.0 or later, check if we are in recovery mode,
609          * which means we are on a hot standby.
610          */
611         if (fout->remoteVersion >= 90000)
612         {
613                 PGresult *res = ExecuteSqlQueryForSingleRow(fout, "SELECT pg_catalog.pg_is_in_recovery()");
614                 if (strcmp(PQgetvalue(res, 0, 0), "t") == 0)
615                 {
616                         /*
617                          * On hot standby slaves, never try to dump unlogged table data,
618                          * since it will just throw an error.
619                          */
620                         no_unlogged_table_data = true;
621                 }
622                 PQclear(res);
623         }
624
625         /*
626          * Start transaction-snapshot mode transaction to dump consistent data.
627          */
628         ExecuteSqlStatement(fout, "BEGIN");
629         if (fout->remoteVersion >= 90100)
630         {
631                 if (serializable_deferrable)
632                         ExecuteSqlStatement(fout,
633                                                                 "SET TRANSACTION ISOLATION LEVEL "
634                                                                 "SERIALIZABLE, READ ONLY, DEFERRABLE");
635                 else
636                         ExecuteSqlStatement(fout,
637                                                                 "SET TRANSACTION ISOLATION LEVEL "
638                                                                 "REPEATABLE READ, READ ONLY");
639         }
640         else if (fout->remoteVersion >= 70400)
641         {
642                 /* note: comma was not accepted in SET TRANSACTION before 8.0 */
643                 ExecuteSqlStatement(fout,
644                                                         "SET TRANSACTION ISOLATION LEVEL "
645                                                         "SERIALIZABLE READ ONLY");
646         }
647         else
648                 ExecuteSqlStatement(fout,
649                                                         "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
650
651         /* Select the appropriate subquery to convert user IDs to names */
652         if (fout->remoteVersion >= 80100)
653                 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
654         else if (fout->remoteVersion >= 70300)
655                 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
656         else
657                 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
658
659         /* Find the last built-in OID, if needed */
660         if (fout->remoteVersion < 70300)
661         {
662                 if (fout->remoteVersion >= 70100)
663                         g_last_builtin_oid = findLastBuiltinOid_V71(fout,
664                                                                                                   PQdb(GetConnection(fout)));
665                 else
666                         g_last_builtin_oid = findLastBuiltinOid_V70(fout);
667                 if (g_verbose)
668                         write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
669         }
670
671         /* Expand schema selection patterns into OID lists */
672         if (schema_include_patterns.head != NULL)
673         {
674                 expand_schema_name_patterns(fout, &schema_include_patterns,
675                                                                         &schema_include_oids);
676                 if (schema_include_oids.head == NULL)
677                         exit_horribly(NULL, "No matching schemas were found\n");
678         }
679         expand_schema_name_patterns(fout, &schema_exclude_patterns,
680                                                                 &schema_exclude_oids);
681         /* non-matching exclusion patterns aren't an error */
682
683         /* Expand table selection patterns into OID lists */
684         if (table_include_patterns.head != NULL)
685         {
686                 expand_table_name_patterns(fout, &table_include_patterns,
687                                                                    &table_include_oids);
688                 if (table_include_oids.head == NULL)
689                         exit_horribly(NULL, "No matching tables were found\n");
690         }
691         expand_table_name_patterns(fout, &table_exclude_patterns,
692                                                            &table_exclude_oids);
693
694         expand_table_name_patterns(fout, &tabledata_exclude_patterns,
695                                                            &tabledata_exclude_oids);
696
697         /* non-matching exclusion patterns aren't an error */
698
699         /*
700          * Dumping blobs is now default unless we saw an inclusion switch or -s
701          * ... but even if we did see one of these, -b turns it back on.
702          */
703         if (include_everything && !schemaOnly)
704                 outputBlobs = true;
705
706         /*
707          * Now scan the database and create DumpableObject structs for all the
708          * objects we intend to dump.
709          */
710         tblinfo = getSchemaData(fout, &numTables);
711
712         if (fout->remoteVersion < 80400)
713                 guessConstraintInheritance(tblinfo, numTables);
714
715         if (!schemaOnly)
716         {
717                 getTableData(tblinfo, numTables, oids);
718                 if (dataOnly)
719                         getTableDataFKConstraints();
720         }
721
722         if (outputBlobs)
723                 getBlobs(fout);
724
725         /*
726          * Collect dependency data to assist in ordering the objects.
727          */
728         getDependencies(fout);
729
730         /* Lastly, create dummy objects to represent the section boundaries */
731         boundaryObjs = createBoundaryObjects();
732
733         /* Get pointers to all the known DumpableObjects */
734         getDumpableObjects(&dobjs, &numObjs);
735
736         /*
737          * Add dummy dependencies to enforce the dump section ordering.
738          */
739         addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
740
741         /*
742          * Sort the objects into a safe dump order (no forward references).
743          *
744          * In 7.3 or later, we can rely on dependency information to help us
745          * determine a safe order, so the initial sort is mostly for cosmetic
746          * purposes: we sort by name to ensure that logically identical schemas
747          * will dump identically.  Before 7.3 we don't have dependencies and we
748          * use OID ordering as an (unreliable) guide to creation order.
749          */
750         if (fout->remoteVersion >= 70300)
751                 sortDumpableObjectsByTypeName(dobjs, numObjs);
752         else
753                 sortDumpableObjectsByTypeOid(dobjs, numObjs);
754
755         sortDumpableObjects(dobjs, numObjs,
756                                                 boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
757
758         /*
759          * Create archive TOC entries for all the objects to be dumped, in a safe
760          * order.
761          */
762
763         /* First the special ENCODING and STDSTRINGS entries. */
764         dumpEncoding(fout);
765         dumpStdStrings(fout);
766
767         /* The database item is always next, unless we don't want it at all */
768         if (include_everything && !dataOnly)
769                 dumpDatabase(fout);
770
771         /* Now the rearrangeable objects. */
772         for (i = 0; i < numObjs; i++)
773                 dumpDumpableObject(fout, dobjs[i]);
774
775         /*
776          * Set up options info to ensure we dump what we want.
777          */
778         ropt = NewRestoreOptions();
779         ropt->filename = filename;
780         ropt->dropSchema = outputClean;
781         ropt->dataOnly = dataOnly;
782         ropt->schemaOnly = schemaOnly;
783         ropt->dumpSections = dumpSections;
784         ropt->aclsSkip = aclsSkip;
785         ropt->superuser = outputSuperuser;
786         ropt->createDB = outputCreateDB;
787         ropt->noOwner = outputNoOwner;
788         ropt->noTablespace = outputNoTablespaces;
789         ropt->disable_triggers = disable_triggers;
790         ropt->use_setsessauth = use_setsessauth;
791
792         if (compressLevel == -1)
793                 ropt->compression = 0;
794         else
795                 ropt->compression = compressLevel;
796
797         ropt->suppressDumpWarnings = true;      /* We've already shown them */
798
799         SetArchiveRestoreOptions(fout, ropt);
800
801         /*
802          * The archive's TOC entries are now marked as to which ones will
803          * actually be output, so we can set up their dependency lists properly.
804          * This isn't necessary for plain-text output, though.
805          */
806         if (!plainText)
807                 BuildArchiveDependencies(fout);
808
809         /*
810          * And finally we can do the actual output.
811          *
812          * Note: for non-plain-text output formats, the output file is written
813          * inside CloseArchive().  This is, um, bizarre; but not worth changing
814          * right now.
815          */
816         if (plainText)
817                 RestoreArchive(fout);
818
819         CloseArchive(fout);
820
821         exit_nicely(0);
822 }
823
824
825 static void
826 help(const char *progname)
827 {
828         printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
829         printf(_("Usage:\n"));
830         printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
831
832         printf(_("\nGeneral options:\n"));
833         printf(_("  -f, --file=FILENAME          output file or directory name\n"));
834         printf(_("  -F, --format=c|d|t|p         output file format (custom, directory, tar,\n"
835                          "                               plain text (default))\n"));
836         printf(_("  -v, --verbose                verbose mode\n"));
837         printf(_("  -V, --version                output version information, then exit\n"));
838         printf(_("  -Z, --compress=0-9           compression level for compressed formats\n"));
839         printf(_("  --lock-wait-timeout=TIMEOUT  fail after waiting TIMEOUT for a table lock\n"));
840         printf(_("  -?, --help                   show this help, then exit\n"));
841
842         printf(_("\nOptions controlling the output content:\n"));
843         printf(_("  -a, --data-only              dump only the data, not the schema\n"));
844         printf(_("  -b, --blobs                  include large objects in dump\n"));
845         printf(_("  -c, --clean                  clean (drop) database objects before recreating\n"));
846         printf(_("  -C, --create                 include commands to create database in dump\n"));
847         printf(_("  -E, --encoding=ENCODING      dump the data in encoding ENCODING\n"));
848         printf(_("  -n, --schema=SCHEMA          dump the named schema(s) only\n"));
849         printf(_("  -N, --exclude-schema=SCHEMA  do NOT dump the named schema(s)\n"));
850         printf(_("  -o, --oids                   include OIDs in dump\n"));
851         printf(_("  -O, --no-owner               skip restoration of object ownership in\n"
852                          "                               plain-text format\n"));
853         printf(_("  -s, --schema-only            dump only the schema, no data\n"));
854         printf(_("  -S, --superuser=NAME         superuser user name to use in plain-text format\n"));
855         printf(_("  -t, --table=TABLE            dump the named table(s) only\n"));
856         printf(_("  -T, --exclude-table=TABLE    do NOT dump the named table(s)\n"));
857         printf(_("  -x, --no-privileges          do not dump privileges (grant/revoke)\n"));
858         printf(_("  --binary-upgrade             for use by upgrade utilities only\n"));
859         printf(_("  --column-inserts             dump data as INSERT commands with column names\n"));
860         printf(_("  --disable-dollar-quoting     disable dollar quoting, use SQL standard quoting\n"));
861         printf(_("  --disable-triggers           disable triggers during data-only restore\n"));
862         printf(_("  --exclude-table-data=TABLE   do NOT dump data for the named table(s)\n"));
863         printf(_("  --inserts                    dump data as INSERT commands, rather than COPY\n"));
864         printf(_("  --no-security-labels         do not dump security label assignments\n"));
865         printf(_("  --no-tablespaces             do not dump tablespace assignments\n"));
866         printf(_("  --no-unlogged-table-data     do not dump unlogged table data\n"));
867         printf(_("  --quote-all-identifiers      quote all identifiers, even if not key words\n"));
868         printf(_("  --section=SECTION            dump named section (pre-data, data, or post-data)\n"));
869         printf(_("  --serializable-deferrable    wait until the dump can run without anomalies\n"));
870         printf(_("  --use-set-session-authorization\n"
871                          "                               use SET SESSION AUTHORIZATION commands instead of\n"
872                          "                               ALTER OWNER commands to set ownership\n"));
873
874         printf(_("\nConnection options:\n"));
875         printf(_("  -h, --host=HOSTNAME      database server host or socket directory\n"));
876         printf(_("  -p, --port=PORT          database server port number\n"));
877         printf(_("  -U, --username=NAME      connect as specified database user\n"));
878         printf(_("  -w, --no-password        never prompt for password\n"));
879         printf(_("  -W, --password           force password prompt (should happen automatically)\n"));
880         printf(_("  --role=ROLENAME          do SET ROLE before dump\n"));
881
882         printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
883                          "variable value is used.\n\n"));
884         printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
885 }
886
887 static void
888 setup_connection(Archive *AH, const char *dumpencoding, char *use_role)
889 {
890         PGconn     *conn = GetConnection(AH);
891         const char *std_strings;
892
893         /* Set the client encoding if requested */
894         if (dumpencoding)
895         {
896                 if (PQsetClientEncoding(conn, dumpencoding) < 0)
897                         exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
898                                                   dumpencoding);
899         }
900
901         /*
902          * Get the active encoding and the standard_conforming_strings setting, so
903          * we know how to escape strings.
904          */
905         AH->encoding = PQclientEncoding(conn);
906
907         std_strings = PQparameterStatus(conn, "standard_conforming_strings");
908         AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
909
910         /* Set the role if requested */
911         if (use_role && AH->remoteVersion >= 80100)
912         {
913                 PQExpBuffer query = createPQExpBuffer();
914
915                 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
916                 ExecuteSqlStatement(AH, query->data);
917                 destroyPQExpBuffer(query);
918         }
919
920         /* Set the datestyle to ISO to ensure the dump's portability */
921         ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
922
923         /* Likewise, avoid using sql_standard intervalstyle */
924         if (AH->remoteVersion >= 80400)
925                 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
926
927         /*
928          * If supported, set extra_float_digits so that we can dump float data
929          * exactly (given correctly implemented float I/O code, anyway)
930          */
931         if (AH->remoteVersion >= 90000)
932                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
933         else if (AH->remoteVersion >= 70400)
934                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
935
936         /*
937          * If synchronized scanning is supported, disable it, to prevent
938          * unpredictable changes in row ordering across a dump and reload.
939          */
940         if (AH->remoteVersion >= 80300)
941                 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
942
943         /*
944          * Disable timeouts if supported.
945          */
946         if (AH->remoteVersion >= 70300)
947                 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
948
949         /*
950          * Quote all identifiers, if requested.
951          */
952         if (quote_all_identifiers && AH->remoteVersion >= 90100)
953                 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
954 }
955
956 static ArchiveFormat
957 parseArchiveFormat(const char *format, ArchiveMode *mode)
958 {
959         ArchiveFormat archiveFormat;
960
961         *mode = archModeWrite;
962
963         if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
964         {
965                 /* This is used by pg_dumpall, and is not documented */
966                 archiveFormat = archNull;
967                 *mode = archModeAppend;
968         }
969         else if (pg_strcasecmp(format, "c") == 0)
970                 archiveFormat = archCustom;
971         else if (pg_strcasecmp(format, "custom") == 0)
972                 archiveFormat = archCustom;
973         else if (pg_strcasecmp(format, "d") == 0)
974                 archiveFormat = archDirectory;
975         else if (pg_strcasecmp(format, "directory") == 0)
976                 archiveFormat = archDirectory;
977         else if (pg_strcasecmp(format, "p") == 0)
978                 archiveFormat = archNull;
979         else if (pg_strcasecmp(format, "plain") == 0)
980                 archiveFormat = archNull;
981         else if (pg_strcasecmp(format, "t") == 0)
982                 archiveFormat = archTar;
983         else if (pg_strcasecmp(format, "tar") == 0)
984                 archiveFormat = archTar;
985         else
986                 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
987         return archiveFormat;
988 }
989
990 /*
991  * Find the OIDs of all schemas matching the given list of patterns,
992  * and append them to the given OID list.
993  */
994 static void
995 expand_schema_name_patterns(Archive *fout,
996                                                         SimpleStringList *patterns,
997                                                         SimpleOidList *oids)
998 {
999         PQExpBuffer query;
1000         PGresult   *res;
1001         SimpleStringListCell *cell;
1002         int                     i;
1003
1004         if (patterns->head == NULL)
1005                 return;                                 /* nothing to do */
1006
1007         if (fout->remoteVersion < 70300)
1008                 exit_horribly(NULL, "server version must be at least 7.3 to use schema selection switches\n");
1009
1010         query = createPQExpBuffer();
1011
1012         /*
1013          * We use UNION ALL rather than UNION; this might sometimes result in
1014          * duplicate entries in the OID list, but we don't care.
1015          */
1016
1017         for (cell = patterns->head; cell; cell = cell->next)
1018         {
1019                 if (cell != patterns->head)
1020                         appendPQExpBuffer(query, "UNION ALL\n");
1021                 appendPQExpBuffer(query,
1022                                                   "SELECT oid FROM pg_catalog.pg_namespace n\n");
1023                 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1024                                                           false, NULL, "n.nspname", NULL, NULL);
1025         }
1026
1027         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1028
1029         for (i = 0; i < PQntuples(res); i++)
1030         {
1031                 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1032         }
1033
1034         PQclear(res);
1035         destroyPQExpBuffer(query);
1036 }
1037
1038 /*
1039  * Find the OIDs of all tables matching the given list of patterns,
1040  * and append them to the given OID list.
1041  */
1042 static void
1043 expand_table_name_patterns(Archive *fout,
1044                                                    SimpleStringList *patterns, SimpleOidList *oids)
1045 {
1046         PQExpBuffer query;
1047         PGresult   *res;
1048         SimpleStringListCell *cell;
1049         int                     i;
1050
1051         if (patterns->head == NULL)
1052                 return;                                 /* nothing to do */
1053
1054         query = createPQExpBuffer();
1055
1056         /*
1057          * We use UNION ALL rather than UNION; this might sometimes result in
1058          * duplicate entries in the OID list, but we don't care.
1059          */
1060
1061         for (cell = patterns->head; cell; cell = cell->next)
1062         {
1063                 if (cell != patterns->head)
1064                         appendPQExpBuffer(query, "UNION ALL\n");
1065                 appendPQExpBuffer(query,
1066                                                   "SELECT c.oid"
1067                                                   "\nFROM pg_catalog.pg_class c"
1068                 "\n     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1069                                                   "\nWHERE c.relkind in ('%c', '%c', '%c', '%c')\n",
1070                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1071                                                   RELKIND_FOREIGN_TABLE);
1072                 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1073                                                           false, "n.nspname", "c.relname", NULL,
1074                                                           "pg_catalog.pg_table_is_visible(c.oid)");
1075         }
1076
1077         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1078
1079         for (i = 0; i < PQntuples(res); i++)
1080         {
1081                 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1082         }
1083
1084         PQclear(res);
1085         destroyPQExpBuffer(query);
1086 }
1087
1088 /*
1089  * selectDumpableNamespace: policy-setting subroutine
1090  *              Mark a namespace as to be dumped or not
1091  */
1092 static void
1093 selectDumpableNamespace(NamespaceInfo *nsinfo)
1094 {
1095         /*
1096          * If specific tables are being dumped, do not dump any complete
1097          * namespaces. If specific namespaces are being dumped, dump just those
1098          * namespaces. Otherwise, dump all non-system namespaces.
1099          */
1100         if (table_include_oids.head != NULL)
1101                 nsinfo->dobj.dump = false;
1102         else if (schema_include_oids.head != NULL)
1103                 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
1104                                                                                                    nsinfo->dobj.catId.oid);
1105         else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1106                          strcmp(nsinfo->dobj.name, "information_schema") == 0)
1107                 nsinfo->dobj.dump = false;
1108         else
1109                 nsinfo->dobj.dump = true;
1110
1111         /*
1112          * In any case, a namespace can be excluded by an exclusion switch
1113          */
1114         if (nsinfo->dobj.dump &&
1115                 simple_oid_list_member(&schema_exclude_oids,
1116                                                            nsinfo->dobj.catId.oid))
1117                 nsinfo->dobj.dump = false;
1118 }
1119
1120 /*
1121  * selectDumpableTable: policy-setting subroutine
1122  *              Mark a table as to be dumped or not
1123  */
1124 static void
1125 selectDumpableTable(TableInfo *tbinfo)
1126 {
1127         /*
1128          * If specific tables are being dumped, dump just those tables; else, dump
1129          * according to the parent namespace's dump flag.
1130          */
1131         if (table_include_oids.head != NULL)
1132                 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1133                                                                                                    tbinfo->dobj.catId.oid);
1134         else
1135                 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1136
1137         /*
1138          * In any case, a table can be excluded by an exclusion switch
1139          */
1140         if (tbinfo->dobj.dump &&
1141                 simple_oid_list_member(&table_exclude_oids,
1142                                                            tbinfo->dobj.catId.oid))
1143                 tbinfo->dobj.dump = false;
1144 }
1145
1146 /*
1147  * selectDumpableType: policy-setting subroutine
1148  *              Mark a type as to be dumped or not
1149  *
1150  * If it's a table's rowtype or an autogenerated array type, we also apply a
1151  * special type code to facilitate sorting into the desired order.      (We don't
1152  * want to consider those to be ordinary types because that would bring tables
1153  * up into the datatype part of the dump order.)  We still set the object's
1154  * dump flag; that's not going to cause the dummy type to be dumped, but we
1155  * need it so that casts involving such types will be dumped correctly -- see
1156  * dumpCast.  This means the flag should be set the same as for the underlying
1157  * object (the table or base type).
1158  */
1159 static void
1160 selectDumpableType(TypeInfo *tyinfo)
1161 {
1162         /* skip complex types, except for standalone composite types */
1163         if (OidIsValid(tyinfo->typrelid) &&
1164                 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1165         {
1166                 TableInfo  *tytable = findTableByOid(tyinfo->typrelid);
1167
1168                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1169                 if (tytable != NULL)
1170                         tyinfo->dobj.dump = tytable->dobj.dump;
1171                 else
1172                         tyinfo->dobj.dump = false;
1173                 return;
1174         }
1175
1176         /* skip auto-generated array types */
1177         if (tyinfo->isArray)
1178         {
1179                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1180
1181                 /*
1182                  * Fall through to set the dump flag; we assume that the subsequent
1183                  * rules will do the same thing as they would for the array's base
1184                  * type.  (We cannot reliably look up the base type here, since
1185                  * getTypes may not have processed it yet.)
1186                  */
1187         }
1188
1189         /* dump only types in dumpable namespaces */
1190         if (!tyinfo->dobj.namespace->dobj.dump)
1191                 tyinfo->dobj.dump = false;
1192
1193         /* skip undefined placeholder types */
1194         else if (!tyinfo->isDefined)
1195                 tyinfo->dobj.dump = false;
1196
1197         else
1198                 tyinfo->dobj.dump = true;
1199 }
1200
1201 /*
1202  * selectDumpableDefaultACL: policy-setting subroutine
1203  *              Mark a default ACL as to be dumped or not
1204  *
1205  * For per-schema default ACLs, dump if the schema is to be dumped.
1206  * Otherwise dump if we are dumping "everything".  Note that dataOnly
1207  * and aclsSkip are checked separately.
1208  */
1209 static void
1210 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1211 {
1212         if (dinfo->dobj.namespace)
1213                 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1214         else
1215                 dinfo->dobj.dump = include_everything;
1216 }
1217
1218 /*
1219  * selectDumpableExtension: policy-setting subroutine
1220  *              Mark an extension as to be dumped or not
1221  *
1222  * Normally, we dump all extensions, or none of them if include_everything
1223  * is false (i.e., a --schema or --table switch was given).  However, in
1224  * binary-upgrade mode it's necessary to skip built-in extensions, since we
1225  * assume those will already be installed in the target database.  We identify
1226  * such extensions by their having OIDs in the range reserved for initdb.
1227  */
1228 static void
1229 selectDumpableExtension(ExtensionInfo *extinfo)
1230 {
1231         if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1232                 extinfo->dobj.dump = false;
1233         else
1234                 extinfo->dobj.dump = include_everything;
1235 }
1236
1237 /*
1238  * selectDumpableObject: policy-setting subroutine
1239  *              Mark a generic dumpable object as to be dumped or not
1240  *
1241  * Use this only for object types without a special-case routine above.
1242  */
1243 static void
1244 selectDumpableObject(DumpableObject *dobj)
1245 {
1246         /*
1247          * Default policy is to dump if parent namespace is dumpable, or always
1248          * for non-namespace-associated items.
1249          */
1250         if (dobj->namespace)
1251                 dobj->dump = dobj->namespace->dobj.dump;
1252         else
1253                 dobj->dump = true;
1254 }
1255
1256 /*
1257  *      Dump a table's contents for loading using the COPY command
1258  *      - this routine is called by the Archiver when it wants the table
1259  *        to be dumped.
1260  */
1261
1262 static int
1263 dumpTableData_copy(Archive *fout, void *dcontext)
1264 {
1265         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1266         TableInfo  *tbinfo = tdinfo->tdtable;
1267         const char *classname = tbinfo->dobj.name;
1268         const bool      hasoids = tbinfo->hasoids;
1269         const bool      oids = tdinfo->oids;
1270         PQExpBuffer q = createPQExpBuffer();
1271         PGconn     *conn = GetConnection(fout);
1272         PGresult   *res;
1273         int                     ret;
1274         char       *copybuf;
1275         const char *column_list;
1276
1277         if (g_verbose)
1278                 write_msg(NULL, "dumping contents of table %s\n", classname);
1279
1280         /*
1281          * Make sure we are in proper schema.  We will qualify the table name
1282          * below anyway (in case its name conflicts with a pg_catalog table); but
1283          * this ensures reproducible results in case the table contains regproc,
1284          * regclass, etc columns.
1285          */
1286         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1287
1288         /*
1289          * If possible, specify the column list explicitly so that we have no
1290          * possibility of retrieving data in the wrong column order.  (The default
1291          * column ordering of COPY will not be what we want in certain corner
1292          * cases involving ADD COLUMN and inheritance.)
1293          */
1294         if (fout->remoteVersion >= 70300)
1295                 column_list = fmtCopyColumnList(tbinfo);
1296         else
1297                 column_list = "";               /* can't select columns in COPY */
1298
1299         if (oids && hasoids)
1300         {
1301                 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1302                                                   fmtQualifiedId(fout,
1303                                                                                  tbinfo->dobj.namespace->dobj.name,
1304                                                                                  classname),
1305                                                   column_list);
1306         }
1307         else if (tdinfo->filtercond)
1308         {
1309                 /* Note: this syntax is only supported in 8.2 and up */
1310                 appendPQExpBufferStr(q, "COPY (SELECT ");
1311                 /* klugery to get rid of parens in column list */
1312                 if (strlen(column_list) > 2)
1313                 {
1314                         appendPQExpBufferStr(q, column_list + 1);
1315                         q->data[q->len - 1] = ' ';
1316                 }
1317                 else
1318                         appendPQExpBufferStr(q, "* ");
1319                 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1320                                                   fmtQualifiedId(fout,
1321                                                                                  tbinfo->dobj.namespace->dobj.name,
1322                                                                                  classname),
1323                                                   tdinfo->filtercond);
1324         }
1325         else
1326         {
1327                 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1328                                                   fmtQualifiedId(fout,
1329                                                                                  tbinfo->dobj.namespace->dobj.name,
1330                                                                                  classname),
1331                                                   column_list);
1332         }
1333         res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1334         PQclear(res);
1335
1336         for (;;)
1337         {
1338                 ret = PQgetCopyData(conn, &copybuf, 0);
1339
1340                 if (ret < 0)
1341                         break;                          /* done or error */
1342
1343                 if (copybuf)
1344                 {
1345                         WriteData(fout, copybuf, ret);
1346                         PQfreemem(copybuf);
1347                 }
1348
1349                 /* ----------
1350                  * THROTTLE:
1351                  *
1352                  * There was considerable discussion in late July, 2000 regarding
1353                  * slowing down pg_dump when backing up large tables. Users with both
1354                  * slow & fast (multi-processor) machines experienced performance
1355                  * degradation when doing a backup.
1356                  *
1357                  * Initial attempts based on sleeping for a number of ms for each ms
1358                  * of work were deemed too complex, then a simple 'sleep in each loop'
1359                  * implementation was suggested. The latter failed because the loop
1360                  * was too tight. Finally, the following was implemented:
1361                  *
1362                  * If throttle is non-zero, then
1363                  *              See how long since the last sleep.
1364                  *              Work out how long to sleep (based on ratio).
1365                  *              If sleep is more than 100ms, then
1366                  *                      sleep
1367                  *                      reset timer
1368                  *              EndIf
1369                  * EndIf
1370                  *
1371                  * where the throttle value was the number of ms to sleep per ms of
1372                  * work. The calculation was done in each loop.
1373                  *
1374                  * Most of the hard work is done in the backend, and this solution
1375                  * still did not work particularly well: on slow machines, the ratio
1376                  * was 50:1, and on medium paced machines, 1:1, and on fast
1377                  * multi-processor machines, it had little or no effect, for reasons
1378                  * that were unclear.
1379                  *
1380                  * Further discussion ensued, and the proposal was dropped.
1381                  *
1382                  * For those people who want this feature, it can be implemented using
1383                  * gettimeofday in each loop, calculating the time since last sleep,
1384                  * multiplying that by the sleep ratio, then if the result is more
1385                  * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1386                  * function to sleep for a subsecond period ie.
1387                  *
1388                  * select(0, NULL, NULL, NULL, &tvi);
1389                  *
1390                  * This will return after the interval specified in the structure tvi.
1391                  * Finally, call gettimeofday again to save the 'last sleep time'.
1392                  * ----------
1393                  */
1394         }
1395         archprintf(fout, "\\.\n\n\n");
1396
1397         if (ret == -2)
1398         {
1399                 /* copy data transfer failed */
1400                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1401                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1402                 write_msg(NULL, "The command was: %s\n", q->data);
1403                 exit_nicely(1);
1404         }
1405
1406         /* Check command status and return to normal libpq state */
1407         res = PQgetResult(conn);
1408         if (PQresultStatus(res) != PGRES_COMMAND_OK)
1409         {
1410                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1411                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1412                 write_msg(NULL, "The command was: %s\n", q->data);
1413                 exit_nicely(1);
1414         }
1415         PQclear(res);
1416
1417         destroyPQExpBuffer(q);
1418         return 1;
1419 }
1420
1421 /*
1422  * Dump table data using INSERT commands.
1423  *
1424  * Caution: when we restore from an archive file direct to database, the
1425  * INSERT commands emitted by this function have to be parsed by
1426  * pg_backup_db.c's ExecuteInsertCommands(), which will not handle comments,
1427  * E'' strings, or dollar-quoted strings.  So don't emit anything like that.
1428  */
1429 static int
1430 dumpTableData_insert(Archive *fout, void *dcontext)
1431 {
1432         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1433         TableInfo  *tbinfo = tdinfo->tdtable;
1434         const char *classname = tbinfo->dobj.name;
1435         PQExpBuffer q = createPQExpBuffer();
1436         PGresult   *res;
1437         int                     tuple;
1438         int                     nfields;
1439         int                     field;
1440
1441         /*
1442          * Make sure we are in proper schema.  We will qualify the table name
1443          * below anyway (in case its name conflicts with a pg_catalog table); but
1444          * this ensures reproducible results in case the table contains regproc,
1445          * regclass, etc columns.
1446          */
1447         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1448
1449         if (fout->remoteVersion >= 70100)
1450         {
1451                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1452                                                   "SELECT * FROM ONLY %s",
1453                                                   fmtQualifiedId(fout,
1454                                                                                  tbinfo->dobj.namespace->dobj.name,
1455                                                                                  classname));
1456         }
1457         else
1458         {
1459                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1460                                                   "SELECT * FROM %s",
1461                                                   fmtQualifiedId(fout,
1462                                                                                  tbinfo->dobj.namespace->dobj.name,
1463                                                                                  classname));
1464         }
1465         if (tdinfo->filtercond)
1466                 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1467
1468         ExecuteSqlStatement(fout, q->data);
1469
1470         while (1)
1471         {
1472                 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1473                                                           PGRES_TUPLES_OK);
1474                 nfields = PQnfields(res);
1475                 for (tuple = 0; tuple < PQntuples(res); tuple++)
1476                 {
1477                         archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1478                         if (nfields == 0)
1479                         {
1480                                 /* corner case for zero-column table */
1481                                 archprintf(fout, "DEFAULT VALUES;\n");
1482                                 continue;
1483                         }
1484                         if (column_inserts)
1485                         {
1486                                 resetPQExpBuffer(q);
1487                                 appendPQExpBuffer(q, "(");
1488                                 for (field = 0; field < nfields; field++)
1489                                 {
1490                                         if (field > 0)
1491                                                 appendPQExpBuffer(q, ", ");
1492                                         appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1493                                 }
1494                                 appendPQExpBuffer(q, ") ");
1495                                 archputs(q->data, fout);
1496                         }
1497                         archprintf(fout, "VALUES (");
1498                         for (field = 0; field < nfields; field++)
1499                         {
1500                                 if (field > 0)
1501                                         archprintf(fout, ", ");
1502                                 if (PQgetisnull(res, tuple, field))
1503                                 {
1504                                         archprintf(fout, "NULL");
1505                                         continue;
1506                                 }
1507
1508                                 /* XXX This code is partially duplicated in ruleutils.c */
1509                                 switch (PQftype(res, field))
1510                                 {
1511                                         case INT2OID:
1512                                         case INT4OID:
1513                                         case INT8OID:
1514                                         case OIDOID:
1515                                         case FLOAT4OID:
1516                                         case FLOAT8OID:
1517                                         case NUMERICOID:
1518                                                 {
1519                                                         /*
1520                                                          * These types are printed without quotes unless
1521                                                          * they contain values that aren't accepted by the
1522                                                          * scanner unquoted (e.g., 'NaN').      Note that
1523                                                          * strtod() and friends might accept NaN, so we
1524                                                          * can't use that to test.
1525                                                          *
1526                                                          * In reality we only need to defend against
1527                                                          * infinity and NaN, so we need not get too crazy
1528                                                          * about pattern matching here.
1529                                                          */
1530                                                         const char *s = PQgetvalue(res, tuple, field);
1531
1532                                                         if (strspn(s, "0123456789 +-eE.") == strlen(s))
1533                                                                 archprintf(fout, "%s", s);
1534                                                         else
1535                                                                 archprintf(fout, "'%s'", s);
1536                                                 }
1537                                                 break;
1538
1539                                         case BITOID:
1540                                         case VARBITOID:
1541                                                 archprintf(fout, "B'%s'",
1542                                                                    PQgetvalue(res, tuple, field));
1543                                                 break;
1544
1545                                         case BOOLOID:
1546                                                 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1547                                                         archprintf(fout, "true");
1548                                                 else
1549                                                         archprintf(fout, "false");
1550                                                 break;
1551
1552                                         default:
1553                                                 /* All other types are printed as string literals. */
1554                                                 resetPQExpBuffer(q);
1555                                                 appendStringLiteralAH(q,
1556                                                                                           PQgetvalue(res, tuple, field),
1557                                                                                           fout);
1558                                                 archputs(q->data, fout);
1559                                                 break;
1560                                 }
1561                         }
1562                         archprintf(fout, ");\n");
1563                 }
1564
1565                 if (PQntuples(res) <= 0)
1566                 {
1567                         PQclear(res);
1568                         break;
1569                 }
1570                 PQclear(res);
1571         }
1572
1573         archprintf(fout, "\n\n");
1574
1575         ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
1576
1577         destroyPQExpBuffer(q);
1578         return 1;
1579 }
1580
1581
1582 /*
1583  * dumpTableData -
1584  *        dump the contents of a single table
1585  *
1586  * Actually, this just makes an ArchiveEntry for the table contents.
1587  */
1588 static void
1589 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1590 {
1591         TableInfo  *tbinfo = tdinfo->tdtable;
1592         PQExpBuffer copyBuf = createPQExpBuffer();
1593         DataDumperPtr dumpFn;
1594         char       *copyStmt;
1595
1596         if (!dump_inserts)
1597         {
1598                 /* Dump/restore using COPY */
1599                 dumpFn = dumpTableData_copy;
1600                 /* must use 2 steps here 'cause fmtId is nonreentrant */
1601                 appendPQExpBuffer(copyBuf, "COPY %s ",
1602                                                   fmtId(tbinfo->dobj.name));
1603                 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1604                                                   fmtCopyColumnList(tbinfo),
1605                                           (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1606                 copyStmt = copyBuf->data;
1607         }
1608         else
1609         {
1610                 /* Restore using INSERT */
1611                 dumpFn = dumpTableData_insert;
1612                 copyStmt = NULL;
1613         }
1614
1615         /*
1616          * Note: although the TableDataInfo is a full DumpableObject, we treat its
1617          * dependency on its table as "special" and pass it to ArchiveEntry now.
1618          * See comments for BuildArchiveDependencies.
1619          */
1620         ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1621                                  tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1622                                  NULL, tbinfo->rolname,
1623                                  false, "TABLE DATA", SECTION_DATA,
1624                                  "", "", copyStmt,
1625                                  &(tbinfo->dobj.dumpId), 1,
1626                                  dumpFn, tdinfo);
1627
1628         destroyPQExpBuffer(copyBuf);
1629 }
1630
1631 /*
1632  * getTableData -
1633  *        set up dumpable objects representing the contents of tables
1634  */
1635 static void
1636 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1637 {
1638         int                     i;
1639
1640         for (i = 0; i < numTables; i++)
1641         {
1642                 if (tblinfo[i].dobj.dump)
1643                         makeTableDataInfo(&(tblinfo[i]), oids);
1644         }
1645 }
1646
1647 /*
1648  * Make a dumpable object for the data of this specific table
1649  *
1650  * Note: we make a TableDataInfo if and only if we are going to dump the
1651  * table data; the "dump" flag in such objects isn't used.
1652  */
1653 static void
1654 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1655 {
1656         TableDataInfo *tdinfo;
1657
1658         /*
1659          * Nothing to do if we already decided to dump the table.  This will
1660          * happen for "config" tables.
1661          */
1662         if (tbinfo->dataObj != NULL)
1663                 return;
1664
1665         /* Skip VIEWs (no data to dump) */
1666         if (tbinfo->relkind == RELKIND_VIEW)
1667                 return;
1668         /* Skip FOREIGN TABLEs (no data to dump) */
1669         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
1670                 return;
1671
1672         /* Don't dump data in unlogged tables, if so requested */
1673         if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
1674                 no_unlogged_table_data)
1675                 return;
1676
1677         /* Check that the data is not explicitly excluded */
1678         if (simple_oid_list_member(&tabledata_exclude_oids,
1679                                                            tbinfo->dobj.catId.oid))
1680                 return;
1681
1682         /* OK, let's dump it */
1683         tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
1684
1685         tdinfo->dobj.objType = DO_TABLE_DATA;
1686
1687         /*
1688          * Note: use tableoid 0 so that this object won't be mistaken for
1689          * something that pg_depend entries apply to.
1690          */
1691         tdinfo->dobj.catId.tableoid = 0;
1692         tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
1693         AssignDumpId(&tdinfo->dobj);
1694         tdinfo->dobj.name = tbinfo->dobj.name;
1695         tdinfo->dobj.namespace = tbinfo->dobj.namespace;
1696         tdinfo->tdtable = tbinfo;
1697         tdinfo->oids = oids;
1698         tdinfo->filtercond = NULL;      /* might get set later */
1699         addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
1700
1701         tbinfo->dataObj = tdinfo;
1702 }
1703
1704 /*
1705  * getTableDataFKConstraints -
1706  *        add dump-order dependencies reflecting foreign key constraints
1707  *
1708  * This code is executed only in a data-only dump --- in schema+data dumps
1709  * we handle foreign key issues by not creating the FK constraints until
1710  * after the data is loaded.  In a data-only dump, however, we want to
1711  * order the table data objects in such a way that a table's referenced
1712  * tables are restored first.  (In the presence of circular references or
1713  * self-references this may be impossible; we'll detect and complain about
1714  * that during the dependency sorting step.)
1715  */
1716 static void
1717 getTableDataFKConstraints(void)
1718 {
1719         DumpableObject **dobjs;
1720         int                     numObjs;
1721         int                     i;
1722
1723         /* Search through all the dumpable objects for FK constraints */
1724         getDumpableObjects(&dobjs, &numObjs);
1725         for (i = 0; i < numObjs; i++)
1726         {
1727                 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
1728                 {
1729                         ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
1730                         TableInfo  *ftable;
1731
1732                         /* Not interesting unless both tables are to be dumped */
1733                         if (cinfo->contable == NULL ||
1734                                 cinfo->contable->dataObj == NULL)
1735                                 continue;
1736                         ftable = findTableByOid(cinfo->confrelid);
1737                         if (ftable == NULL ||
1738                                 ftable->dataObj == NULL)
1739                                 continue;
1740
1741                         /*
1742                          * Okay, make referencing table's TABLE_DATA object depend on the
1743                          * referenced table's TABLE_DATA object.
1744                          */
1745                         addObjectDependency(&cinfo->contable->dataObj->dobj,
1746                                                                 ftable->dataObj->dobj.dumpId);
1747                 }
1748         }
1749         free(dobjs);
1750 }
1751
1752
1753 /*
1754  * guessConstraintInheritance:
1755  *      In pre-8.4 databases, we can't tell for certain which constraints
1756  *      are inherited.  We assume a CHECK constraint is inherited if its name
1757  *      matches the name of any constraint in the parent.  Originally this code
1758  *      tried to compare the expression texts, but that can fail for various
1759  *      reasons --- for example, if the parent and child tables are in different
1760  *      schemas, reverse-listing of function calls may produce different text
1761  *      (schema-qualified or not) depending on search path.
1762  *
1763  *      In 8.4 and up we can rely on the conislocal field to decide which
1764  *      constraints must be dumped; much safer.
1765  *
1766  *      This function assumes all conislocal flags were initialized to TRUE.
1767  *      It clears the flag on anything that seems to be inherited.
1768  */
1769 static void
1770 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
1771 {
1772         int                     i,
1773                                 j,
1774                                 k;
1775
1776         for (i = 0; i < numTables; i++)
1777         {
1778                 TableInfo  *tbinfo = &(tblinfo[i]);
1779                 int                     numParents;
1780                 TableInfo **parents;
1781                 TableInfo  *parent;
1782
1783                 /* Sequences and views never have parents */
1784                 if (tbinfo->relkind == RELKIND_SEQUENCE ||
1785                         tbinfo->relkind == RELKIND_VIEW)
1786                         continue;
1787
1788                 /* Don't bother computing anything for non-target tables, either */
1789                 if (!tbinfo->dobj.dump)
1790                         continue;
1791
1792                 numParents = tbinfo->numParents;
1793                 parents = tbinfo->parents;
1794
1795                 if (numParents == 0)
1796                         continue;                       /* nothing to see here, move along */
1797
1798                 /* scan for inherited CHECK constraints */
1799                 for (j = 0; j < tbinfo->ncheck; j++)
1800                 {
1801                         ConstraintInfo *constr;
1802
1803                         constr = &(tbinfo->checkexprs[j]);
1804
1805                         for (k = 0; k < numParents; k++)
1806                         {
1807                                 int                     l;
1808
1809                                 parent = parents[k];
1810                                 for (l = 0; l < parent->ncheck; l++)
1811                                 {
1812                                         ConstraintInfo *pconstr = &(parent->checkexprs[l]);
1813
1814                                         if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
1815                                         {
1816                                                 constr->conislocal = false;
1817                                                 break;
1818                                         }
1819                                 }
1820                                 if (!constr->conislocal)
1821                                         break;
1822                         }
1823                 }
1824         }
1825 }
1826
1827
1828 /*
1829  * dumpDatabase:
1830  *      dump the database definition
1831  */
1832 static void
1833 dumpDatabase(Archive *fout)
1834 {
1835         PQExpBuffer dbQry = createPQExpBuffer();
1836         PQExpBuffer delQry = createPQExpBuffer();
1837         PQExpBuffer creaQry = createPQExpBuffer();
1838         PGconn     *conn = GetConnection(fout);
1839         PGresult   *res;
1840         int                     i_tableoid,
1841                                 i_oid,
1842                                 i_dba,
1843                                 i_encoding,
1844                                 i_collate,
1845                                 i_ctype,
1846                                 i_frozenxid,
1847                                 i_tablespace;
1848         CatalogId       dbCatId;
1849         DumpId          dbDumpId;
1850         const char *datname,
1851                            *dba,
1852                            *encoding,
1853                            *collate,
1854                            *ctype,
1855                            *tablespace;
1856         uint32          frozenxid;
1857
1858         datname = PQdb(conn);
1859
1860         if (g_verbose)
1861                 write_msg(NULL, "saving database definition\n");
1862
1863         /* Make sure we are in proper schema */
1864         selectSourceSchema(fout, "pg_catalog");
1865
1866         /* Get the database owner and parameters from pg_database */
1867         if (fout->remoteVersion >= 80400)
1868         {
1869                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1870                                                   "(%s datdba) AS dba, "
1871                                                   "pg_encoding_to_char(encoding) AS encoding, "
1872                                                   "datcollate, datctype, datfrozenxid, "
1873                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1874                                           "shobj_description(oid, 'pg_database') AS description "
1875
1876                                                   "FROM pg_database "
1877                                                   "WHERE datname = ",
1878                                                   username_subquery);
1879                 appendStringLiteralAH(dbQry, datname, fout);
1880         }
1881         else if (fout->remoteVersion >= 80200)
1882         {
1883                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1884                                                   "(%s datdba) AS dba, "
1885                                                   "pg_encoding_to_char(encoding) AS encoding, "
1886                                            "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1887                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1888                                           "shobj_description(oid, 'pg_database') AS description "
1889
1890                                                   "FROM pg_database "
1891                                                   "WHERE datname = ",
1892                                                   username_subquery);
1893                 appendStringLiteralAH(dbQry, datname, fout);
1894         }
1895         else if (fout->remoteVersion >= 80000)
1896         {
1897                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1898                                                   "(%s datdba) AS dba, "
1899                                                   "pg_encoding_to_char(encoding) AS encoding, "
1900                                            "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1901                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
1902                                                   "FROM pg_database "
1903                                                   "WHERE datname = ",
1904                                                   username_subquery);
1905                 appendStringLiteralAH(dbQry, datname, fout);
1906         }
1907         else if (fout->remoteVersion >= 70100)
1908         {
1909                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1910                                                   "(%s datdba) AS dba, "
1911                                                   "pg_encoding_to_char(encoding) AS encoding, "
1912                                                   "NULL AS datcollate, NULL AS datctype, "
1913                                                   "0 AS datfrozenxid, "
1914                                                   "NULL AS tablespace "
1915                                                   "FROM pg_database "
1916                                                   "WHERE datname = ",
1917                                                   username_subquery);
1918                 appendStringLiteralAH(dbQry, datname, fout);
1919         }
1920         else
1921         {
1922                 appendPQExpBuffer(dbQry, "SELECT "
1923                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1924                                                   "oid, "
1925                                                   "(%s datdba) AS dba, "
1926                                                   "pg_encoding_to_char(encoding) AS encoding, "
1927                                                   "NULL AS datcollate, NULL AS datctype, "
1928                                                   "0 AS datfrozenxid, "
1929                                                   "NULL AS tablespace "
1930                                                   "FROM pg_database "
1931                                                   "WHERE datname = ",
1932                                                   username_subquery);
1933                 appendStringLiteralAH(dbQry, datname, fout);
1934         }
1935
1936         res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
1937
1938         i_tableoid = PQfnumber(res, "tableoid");
1939         i_oid = PQfnumber(res, "oid");
1940         i_dba = PQfnumber(res, "dba");
1941         i_encoding = PQfnumber(res, "encoding");
1942         i_collate = PQfnumber(res, "datcollate");
1943         i_ctype = PQfnumber(res, "datctype");
1944         i_frozenxid = PQfnumber(res, "datfrozenxid");
1945         i_tablespace = PQfnumber(res, "tablespace");
1946
1947         dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1948         dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1949         dba = PQgetvalue(res, 0, i_dba);
1950         encoding = PQgetvalue(res, 0, i_encoding);
1951         collate = PQgetvalue(res, 0, i_collate);
1952         ctype = PQgetvalue(res, 0, i_ctype);
1953         frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
1954         tablespace = PQgetvalue(res, 0, i_tablespace);
1955
1956         appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1957                                           fmtId(datname));
1958         if (strlen(encoding) > 0)
1959         {
1960                 appendPQExpBuffer(creaQry, " ENCODING = ");
1961                 appendStringLiteralAH(creaQry, encoding, fout);
1962         }
1963         if (strlen(collate) > 0)
1964         {
1965                 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
1966                 appendStringLiteralAH(creaQry, collate, fout);
1967         }
1968         if (strlen(ctype) > 0)
1969         {
1970                 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
1971                 appendStringLiteralAH(creaQry, ctype, fout);
1972         }
1973         if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1974                 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1975                                                   fmtId(tablespace));
1976         appendPQExpBuffer(creaQry, ";\n");
1977
1978         if (binary_upgrade)
1979         {
1980                 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
1981                 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
1982                                                   "SET datfrozenxid = '%u'\n"
1983                                                   "WHERE        datname = ",
1984                                                   frozenxid);
1985                 appendStringLiteralAH(creaQry, datname, fout);
1986                 appendPQExpBuffer(creaQry, ";\n");
1987
1988         }
1989
1990         appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1991                                           fmtId(datname));
1992
1993         dbDumpId = createDumpId();
1994
1995         ArchiveEntry(fout,
1996                                  dbCatId,               /* catalog ID */
1997                                  dbDumpId,              /* dump ID */
1998                                  datname,               /* Name */
1999                                  NULL,                  /* Namespace */
2000                                  NULL,                  /* Tablespace */
2001                                  dba,                   /* Owner */
2002                                  false,                 /* with oids */
2003                                  "DATABASE",    /* Desc */
2004                                  SECTION_PRE_DATA,              /* Section */
2005                                  creaQry->data, /* Create */
2006                                  delQry->data,  /* Del */
2007                                  NULL,                  /* Copy */
2008                                  NULL,                  /* Deps */
2009                                  0,                             /* # Deps */
2010                                  NULL,                  /* Dumper */
2011                                  NULL);                 /* Dumper Arg */
2012
2013         /*
2014          * pg_largeobject and pg_largeobject_metadata come from the old system
2015          * intact, so set their relfrozenxids.
2016          */
2017         if (binary_upgrade)
2018         {
2019                 PGresult   *lo_res;
2020                 PQExpBuffer loFrozenQry = createPQExpBuffer();
2021                 PQExpBuffer loOutQry = createPQExpBuffer();
2022                 int                     i_relfrozenxid;
2023
2024                 /*
2025                  * pg_largeobject
2026                  */
2027                 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2028                                                   "FROM pg_catalog.pg_class\n"
2029                                                   "WHERE oid = %u;\n",
2030                                                   LargeObjectRelationId);
2031
2032                 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2033
2034                 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2035
2036                 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject.relfrozenxid\n");
2037                 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2038                                                   "SET relfrozenxid = '%u'\n"
2039                                                   "WHERE oid = %u;\n",
2040                                                   atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2041                                                   LargeObjectRelationId);
2042                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2043                                          "pg_largeobject", NULL, NULL, "",
2044                                          false, "pg_largeobject", SECTION_PRE_DATA,
2045                                          loOutQry->data, "", NULL,
2046                                          NULL, 0,
2047                                          NULL, NULL);
2048
2049                 PQclear(lo_res);
2050
2051                 /*
2052                  * pg_largeobject_metadata
2053                  */
2054                 if (fout->remoteVersion >= 90000)
2055                 {
2056                         resetPQExpBuffer(loFrozenQry);
2057                         resetPQExpBuffer(loOutQry);
2058
2059                         appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2060                                                           "FROM pg_catalog.pg_class\n"
2061                                                           "WHERE oid = %u;\n",
2062                                                           LargeObjectMetadataRelationId);
2063
2064                         lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2065
2066                         i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2067
2068                         appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata.relfrozenxid\n");
2069                         appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2070                                                           "SET relfrozenxid = '%u'\n"
2071                                                           "WHERE oid = %u;\n",
2072                                                           atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2073                                                           LargeObjectMetadataRelationId);
2074                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2075                                                  "pg_largeobject_metadata", NULL, NULL, "",
2076                                                  false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2077                                                  loOutQry->data, "", NULL,
2078                                                  NULL, 0,
2079                                                  NULL, NULL);
2080
2081                         PQclear(lo_res);
2082                 }
2083
2084                 destroyPQExpBuffer(loFrozenQry);
2085                 destroyPQExpBuffer(loOutQry);
2086         }
2087
2088         /* Dump DB comment if any */
2089         if (fout->remoteVersion >= 80200)
2090         {
2091                 /*
2092                  * 8.2 keeps comments on shared objects in a shared table, so we
2093                  * cannot use the dumpComment used for other database objects.
2094                  */
2095                 char       *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2096
2097                 if (comment && strlen(comment))
2098                 {
2099                         resetPQExpBuffer(dbQry);
2100
2101                         /*
2102                          * Generates warning when loaded into a differently-named
2103                          * database.
2104                          */
2105                         appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2106                         appendStringLiteralAH(dbQry, comment, fout);
2107                         appendPQExpBuffer(dbQry, ";\n");
2108
2109                         ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2110                                                  dba, false, "COMMENT", SECTION_NONE,
2111                                                  dbQry->data, "", NULL,
2112                                                  &dbDumpId, 1, NULL, NULL);
2113                 }
2114         }
2115         else
2116         {
2117                 resetPQExpBuffer(dbQry);
2118                 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2119                 dumpComment(fout, dbQry->data, NULL, "",
2120                                         dbCatId, 0, dbDumpId);
2121         }
2122
2123         PQclear(res);
2124
2125         /* Dump shared security label. */
2126         if (!no_security_labels && fout->remoteVersion >= 90200)
2127         {
2128                 PQExpBuffer seclabelQry = createPQExpBuffer();
2129
2130                 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2131                 res = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2132                 resetPQExpBuffer(seclabelQry);
2133                 emitShSecLabels(conn, res, seclabelQry, "DATABASE", datname);
2134                 if (strlen(seclabelQry->data))
2135                         ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2136                                                  dba, false, "SECURITY LABEL", SECTION_NONE,
2137                                                  seclabelQry->data, "", NULL,
2138                                                  &dbDumpId, 1, NULL, NULL);
2139                 destroyPQExpBuffer(seclabelQry);
2140         }
2141
2142         destroyPQExpBuffer(dbQry);
2143         destroyPQExpBuffer(delQry);
2144         destroyPQExpBuffer(creaQry);
2145 }
2146
2147
2148 /*
2149  * dumpEncoding: put the correct encoding into the archive
2150  */
2151 static void
2152 dumpEncoding(Archive *AH)
2153 {
2154         const char *encname = pg_encoding_to_char(AH->encoding);
2155         PQExpBuffer qry = createPQExpBuffer();
2156
2157         if (g_verbose)
2158                 write_msg(NULL, "saving encoding = %s\n", encname);
2159
2160         appendPQExpBuffer(qry, "SET client_encoding = ");
2161         appendStringLiteralAH(qry, encname, AH);
2162         appendPQExpBuffer(qry, ";\n");
2163
2164         ArchiveEntry(AH, nilCatalogId, createDumpId(),
2165                                  "ENCODING", NULL, NULL, "",
2166                                  false, "ENCODING", SECTION_PRE_DATA,
2167                                  qry->data, "", NULL,
2168                                  NULL, 0,
2169                                  NULL, NULL);
2170
2171         destroyPQExpBuffer(qry);
2172 }
2173
2174
2175 /*
2176  * dumpStdStrings: put the correct escape string behavior into the archive
2177  */
2178 static void
2179 dumpStdStrings(Archive *AH)
2180 {
2181         const char *stdstrings = AH->std_strings ? "on" : "off";
2182         PQExpBuffer qry = createPQExpBuffer();
2183
2184         if (g_verbose)
2185                 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2186                                   stdstrings);
2187
2188         appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2189                                           stdstrings);
2190
2191         ArchiveEntry(AH, nilCatalogId, createDumpId(),
2192                                  "STDSTRINGS", NULL, NULL, "",
2193                                  false, "STDSTRINGS", SECTION_PRE_DATA,
2194                                  qry->data, "", NULL,
2195                                  NULL, 0,
2196                                  NULL, NULL);
2197
2198         destroyPQExpBuffer(qry);
2199 }
2200
2201
2202 /*
2203  * getBlobs:
2204  *      Collect schema-level data about large objects
2205  */
2206 static void
2207 getBlobs(Archive *fout)
2208 {
2209         PQExpBuffer blobQry = createPQExpBuffer();
2210         BlobInfo   *binfo;
2211         DumpableObject *bdata;
2212         PGresult   *res;
2213         int                     ntups;
2214         int                     i;
2215
2216         /* Verbose message */
2217         if (g_verbose)
2218                 write_msg(NULL, "reading large objects\n");
2219
2220         /* Make sure we are in proper schema */
2221         selectSourceSchema(fout, "pg_catalog");
2222
2223         /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2224         if (fout->remoteVersion >= 90000)
2225                 appendPQExpBuffer(blobQry,
2226                                                   "SELECT oid, (%s lomowner) AS rolname, lomacl"
2227                                                   " FROM pg_largeobject_metadata",
2228                                                   username_subquery);
2229         else if (fout->remoteVersion >= 70100)
2230                 appendPQExpBuffer(blobQry,
2231                                                   "SELECT DISTINCT loid, NULL::oid, NULL::oid"
2232                                                   " FROM pg_largeobject");
2233         else
2234                 appendPQExpBuffer(blobQry,
2235                                                   "SELECT oid, NULL::oid, NULL::oid"
2236                                                   " FROM pg_class WHERE relkind = 'l'");
2237
2238         res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
2239
2240         ntups = PQntuples(res);
2241         if (ntups > 0)
2242         {
2243                 /*
2244                  * Each large object has its own BLOB archive entry.
2245                  */
2246                 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2247
2248                 for (i = 0; i < ntups; i++)
2249                 {
2250                         binfo[i].dobj.objType = DO_BLOB;
2251                         binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2252                         binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
2253                         AssignDumpId(&binfo[i].dobj);
2254
2255                         binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, 0));
2256                         if (!PQgetisnull(res, i, 1))
2257                                 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, 1));
2258                         else
2259                                 binfo[i].rolname = "";
2260                         if (!PQgetisnull(res, i, 2))
2261                                 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, 2));
2262                         else
2263                                 binfo[i].blobacl = NULL;
2264                 }
2265
2266                 /*
2267                  * If we have any large objects, a "BLOBS" archive entry is needed.
2268                  * This is just a placeholder for sorting; it carries no data now.
2269                  */
2270                 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2271                 bdata->objType = DO_BLOB_DATA;
2272                 bdata->catId = nilCatalogId;
2273                 AssignDumpId(bdata);
2274                 bdata->name = pg_strdup("BLOBS");
2275         }
2276
2277         PQclear(res);
2278         destroyPQExpBuffer(blobQry);
2279 }
2280
2281 /*
2282  * dumpBlob
2283  *
2284  * dump the definition (metadata) of the given large object
2285  */
2286 static void
2287 dumpBlob(Archive *fout, BlobInfo *binfo)
2288 {
2289         PQExpBuffer cquery = createPQExpBuffer();
2290         PQExpBuffer dquery = createPQExpBuffer();
2291
2292         appendPQExpBuffer(cquery,
2293                                           "SELECT pg_catalog.lo_create('%s');\n",
2294                                           binfo->dobj.name);
2295
2296         appendPQExpBuffer(dquery,
2297                                           "SELECT pg_catalog.lo_unlink('%s');\n",
2298                                           binfo->dobj.name);
2299
2300         ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
2301                                  binfo->dobj.name,
2302                                  NULL, NULL,
2303                                  binfo->rolname, false,
2304                                  "BLOB", SECTION_PRE_DATA,
2305                                  cquery->data, dquery->data, NULL,
2306                                  NULL, 0,
2307                                  NULL, NULL);
2308
2309         /* set up tag for comment and/or ACL */
2310         resetPQExpBuffer(cquery);
2311         appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2312
2313         /* Dump comment if any */
2314         dumpComment(fout, cquery->data,
2315                                 NULL, binfo->rolname,
2316                                 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2317
2318         /* Dump security label if any */
2319         dumpSecLabel(fout, cquery->data,
2320                                  NULL, binfo->rolname,
2321                                  binfo->dobj.catId, 0, binfo->dobj.dumpId);
2322
2323         /* Dump ACL if any */
2324         if (binfo->blobacl)
2325                 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2326                                 binfo->dobj.name, NULL, cquery->data,
2327                                 NULL, binfo->rolname, binfo->blobacl);
2328
2329         destroyPQExpBuffer(cquery);
2330         destroyPQExpBuffer(dquery);
2331 }
2332
2333 /*
2334  * dumpBlobs:
2335  *      dump the data contents of all large objects
2336  */
2337 static int
2338 dumpBlobs(Archive *fout, void *arg)
2339 {
2340         const char *blobQry;
2341         const char *blobFetchQry;
2342         PGconn     *conn = GetConnection(fout);
2343         PGresult   *res;
2344         char            buf[LOBBUFSIZE];
2345         int                     ntups;
2346         int                     i;
2347         int                     cnt;
2348
2349         if (g_verbose)
2350                 write_msg(NULL, "saving large objects\n");
2351
2352         /* Make sure we are in proper schema */
2353         selectSourceSchema(fout, "pg_catalog");
2354
2355         /*
2356          * Currently, we re-fetch all BLOB OIDs using a cursor.  Consider scanning
2357          * the already-in-memory dumpable objects instead...
2358          */
2359         if (fout->remoteVersion >= 90000)
2360                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2361         else if (fout->remoteVersion >= 70100)
2362                 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2363         else
2364                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2365
2366         ExecuteSqlStatement(fout, blobQry);
2367
2368         /* Command to fetch from cursor */
2369         blobFetchQry = "FETCH 1000 IN bloboid";
2370
2371         do
2372         {
2373                 /* Do a fetch */
2374                 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
2375
2376                 /* Process the tuples, if any */
2377                 ntups = PQntuples(res);
2378                 for (i = 0; i < ntups; i++)
2379                 {
2380                         Oid                     blobOid;
2381                         int                     loFd;
2382
2383                         blobOid = atooid(PQgetvalue(res, i, 0));
2384                         /* Open the BLOB */
2385                         loFd = lo_open(conn, blobOid, INV_READ);
2386                         if (loFd == -1)
2387                                 exit_horribly(NULL, "could not open large object %u: %s",
2388                                                           blobOid, PQerrorMessage(conn));
2389
2390                         StartBlob(fout, blobOid);
2391
2392                         /* Now read it in chunks, sending data to archive */
2393                         do
2394                         {
2395                                 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
2396                                 if (cnt < 0)
2397                                         exit_horribly(NULL, "error reading large object %u: %s",
2398                                                                   blobOid, PQerrorMessage(conn));
2399
2400                                 WriteData(fout, buf, cnt);
2401                         } while (cnt > 0);
2402
2403                         lo_close(conn, loFd);
2404
2405                         EndBlob(fout, blobOid);
2406                 }
2407
2408                 PQclear(res);
2409         } while (ntups > 0);
2410
2411         return 1;
2412 }
2413
2414 static void
2415 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
2416                                                                                  PQExpBuffer upgrade_buffer,
2417                                                                                  Oid pg_type_oid)
2418 {
2419         PQExpBuffer upgrade_query = createPQExpBuffer();
2420         PGresult   *upgrade_res;
2421         Oid                     pg_type_array_oid;
2422
2423         appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2424         appendPQExpBuffer(upgrade_buffer,
2425          "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2426                                           pg_type_oid);
2427
2428         /* we only support old >= 8.3 for binary upgrades */
2429         appendPQExpBuffer(upgrade_query,
2430                                           "SELECT typarray "
2431                                           "FROM pg_catalog.pg_type "
2432                                           "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2433                                           pg_type_oid);
2434
2435         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2436
2437         pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2438
2439         if (OidIsValid(pg_type_array_oid))
2440         {
2441                 appendPQExpBuffer(upgrade_buffer,
2442                            "\n-- For binary upgrade, must preserve pg_type array oid\n");
2443                 appendPQExpBuffer(upgrade_buffer,
2444                                                   "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2445                                                   pg_type_array_oid);
2446         }
2447
2448         PQclear(upgrade_res);
2449         destroyPQExpBuffer(upgrade_query);
2450 }
2451
2452 static bool
2453 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
2454                                                                                 PQExpBuffer upgrade_buffer,
2455                                                                                 Oid pg_rel_oid)
2456 {
2457         PQExpBuffer upgrade_query = createPQExpBuffer();
2458         PGresult   *upgrade_res;
2459         Oid                     pg_type_oid;
2460         bool            toast_set = false;
2461
2462         /* we only support old >= 8.3 for binary upgrades */
2463         appendPQExpBuffer(upgrade_query,
2464                                           "SELECT c.reltype AS crel, t.reltype AS trel "
2465                                           "FROM pg_catalog.pg_class c "
2466                                           "LEFT JOIN pg_catalog.pg_class t ON "
2467                                           "  (c.reltoastrelid = t.oid) "
2468                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
2469                                           pg_rel_oid);
2470
2471         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2472
2473         pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2474
2475         binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
2476                                                                                          pg_type_oid);
2477
2478         if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2479         {
2480                 /* Toast tables do not have pg_type array rows */
2481                 Oid                     pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2482                                                                                         PQfnumber(upgrade_res, "trel")));
2483
2484                 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2485                 appendPQExpBuffer(upgrade_buffer,
2486                                                   "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2487                                                   pg_type_toast_oid);
2488
2489                 toast_set = true;
2490         }
2491
2492         PQclear(upgrade_res);
2493         destroyPQExpBuffer(upgrade_query);
2494
2495         return toast_set;
2496 }
2497
2498 static void
2499 binary_upgrade_set_pg_class_oids(Archive *fout,
2500                                                                  PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2501                                                                  bool is_index)
2502 {
2503         PQExpBuffer upgrade_query = createPQExpBuffer();
2504         PGresult   *upgrade_res;
2505         Oid                     pg_class_reltoastrelid;
2506         Oid                     pg_class_reltoastidxid;
2507
2508         appendPQExpBuffer(upgrade_query,
2509                                           "SELECT c.reltoastrelid, t.reltoastidxid "
2510                                           "FROM pg_catalog.pg_class c LEFT JOIN "
2511                                           "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2512                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
2513                                           pg_class_oid);
2514
2515         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2516
2517         pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2518         pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2519
2520         appendPQExpBuffer(upgrade_buffer,
2521                                    "\n-- For binary upgrade, must preserve pg_class oids\n");
2522
2523         if (!is_index)
2524         {
2525                 appendPQExpBuffer(upgrade_buffer,
2526                                                   "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2527                                                   pg_class_oid);
2528                 /* only tables have toast tables, not indexes */
2529                 if (OidIsValid(pg_class_reltoastrelid))
2530                 {
2531                         /*
2532                          * One complexity is that the table definition might not require
2533                          * the creation of a TOAST table, and the TOAST table might have
2534                          * been created long after table creation, when the table was
2535                          * loaded with wide data.  By setting the TOAST oid we force
2536                          * creation of the TOAST heap and TOAST index by the backend so we
2537                          * can cleanly copy the files during binary upgrade.
2538                          */
2539
2540                         appendPQExpBuffer(upgrade_buffer,
2541                                                           "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2542                                                           pg_class_reltoastrelid);
2543
2544                         /* every toast table has an index */
2545                         appendPQExpBuffer(upgrade_buffer,
2546                                                           "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2547                                                           pg_class_reltoastidxid);
2548                 }
2549         }
2550         else
2551                 appendPQExpBuffer(upgrade_buffer,
2552                                                   "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2553                                                   pg_class_oid);
2554
2555         appendPQExpBuffer(upgrade_buffer, "\n");
2556
2557         PQclear(upgrade_res);
2558         destroyPQExpBuffer(upgrade_query);
2559 }
2560
2561 /*
2562  * If the DumpableObject is a member of an extension, add a suitable
2563  * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2564  */
2565 static void
2566 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2567                                                                 DumpableObject *dobj,
2568                                                                 const char *objlabel)
2569 {
2570         DumpableObject *extobj = NULL;
2571         int                     i;
2572
2573         if (!dobj->ext_member)
2574                 return;
2575
2576         /*
2577          * Find the parent extension.  We could avoid this search if we wanted to
2578          * add a link field to DumpableObject, but the space costs of that would
2579          * be considerable.  We assume that member objects could only have a
2580          * direct dependency on their own extension, not any others.
2581          */
2582         for (i = 0; i < dobj->nDeps; i++)
2583         {
2584                 extobj = findObjectByDumpId(dobj->dependencies[i]);
2585                 if (extobj && extobj->objType == DO_EXTENSION)
2586                         break;
2587                 extobj = NULL;
2588         }
2589         if (extobj == NULL)
2590                 exit_horribly(NULL, "could not find parent extension for %s\n", objlabel);
2591
2592         appendPQExpBuffer(upgrade_buffer,
2593           "\n-- For binary upgrade, handle extension membership the hard way\n");
2594         appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2595                                           fmtId(extobj->name),
2596                                           objlabel);
2597 }
2598
2599 /*
2600  * getNamespaces:
2601  *        read all namespaces in the system catalogs and return them in the
2602  * NamespaceInfo* structure
2603  *
2604  *      numNamespaces is set to the number of namespaces read in
2605  */
2606 NamespaceInfo *
2607 getNamespaces(Archive *fout, int *numNamespaces)
2608 {
2609         PGresult   *res;
2610         int                     ntups;
2611         int                     i;
2612         PQExpBuffer query;
2613         NamespaceInfo *nsinfo;
2614         int                     i_tableoid;
2615         int                     i_oid;
2616         int                     i_nspname;
2617         int                     i_rolname;
2618         int                     i_nspacl;
2619
2620         /*
2621          * Before 7.3, there are no real namespaces; create two dummy entries, one
2622          * for user stuff and one for system stuff.
2623          */
2624         if (fout->remoteVersion < 70300)
2625         {
2626                 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2627
2628                 nsinfo[0].dobj.objType = DO_NAMESPACE;
2629                 nsinfo[0].dobj.catId.tableoid = 0;
2630                 nsinfo[0].dobj.catId.oid = 0;
2631                 AssignDumpId(&nsinfo[0].dobj);
2632                 nsinfo[0].dobj.name = pg_strdup("public");
2633                 nsinfo[0].rolname = pg_strdup("");
2634                 nsinfo[0].nspacl = pg_strdup("");
2635
2636                 selectDumpableNamespace(&nsinfo[0]);
2637
2638                 nsinfo[1].dobj.objType = DO_NAMESPACE;
2639                 nsinfo[1].dobj.catId.tableoid = 0;
2640                 nsinfo[1].dobj.catId.oid = 1;
2641                 AssignDumpId(&nsinfo[1].dobj);
2642                 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2643                 nsinfo[1].rolname = pg_strdup("");
2644                 nsinfo[1].nspacl = pg_strdup("");
2645
2646                 selectDumpableNamespace(&nsinfo[1]);
2647
2648                 *numNamespaces = 2;
2649
2650                 return nsinfo;
2651         }
2652
2653         query = createPQExpBuffer();
2654
2655         /* Make sure we are in proper schema */
2656         selectSourceSchema(fout, "pg_catalog");
2657
2658         /*
2659          * we fetch all namespaces including system ones, so that every object we
2660          * read in can be linked to a containing namespace.
2661          */
2662         appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2663                                           "(%s nspowner) AS rolname, "
2664                                           "nspacl FROM pg_namespace",
2665                                           username_subquery);
2666
2667         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2668
2669         ntups = PQntuples(res);
2670
2671         nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2672
2673         i_tableoid = PQfnumber(res, "tableoid");
2674         i_oid = PQfnumber(res, "oid");
2675         i_nspname = PQfnumber(res, "nspname");
2676         i_rolname = PQfnumber(res, "rolname");
2677         i_nspacl = PQfnumber(res, "nspacl");
2678
2679         for (i = 0; i < ntups; i++)
2680         {
2681                 nsinfo[i].dobj.objType = DO_NAMESPACE;
2682                 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2683                 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2684                 AssignDumpId(&nsinfo[i].dobj);
2685                 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2686                 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2687                 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2688
2689                 /* Decide whether to dump this namespace */
2690                 selectDumpableNamespace(&nsinfo[i]);
2691
2692                 if (strlen(nsinfo[i].rolname) == 0)
2693                         write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2694                                           nsinfo[i].dobj.name);
2695         }
2696
2697         PQclear(res);
2698         destroyPQExpBuffer(query);
2699
2700         *numNamespaces = ntups;
2701
2702         return nsinfo;
2703 }
2704
2705 /*
2706  * findNamespace:
2707  *              given a namespace OID and an object OID, look up the info read by
2708  *              getNamespaces
2709  *
2710  * NB: for pre-7.3 source database, we use object OID to guess whether it's
2711  * a system object or not.      In 7.3 and later there is no guessing, and we
2712  * don't use objoid at all.
2713  */
2714 static NamespaceInfo *
2715 findNamespace(Archive *fout, Oid nsoid, Oid objoid)
2716 {
2717         NamespaceInfo *nsinfo;
2718
2719         if (fout->remoteVersion >= 70300)
2720         {
2721                 nsinfo = findNamespaceByOid(nsoid);
2722         }
2723         else
2724         {
2725                 /* This code depends on the dummy objects set up by getNamespaces. */
2726                 Oid                     i;
2727
2728                 if (objoid > g_last_builtin_oid)
2729                         i = 0;                          /* user object */
2730                 else
2731                         i = 1;                          /* system object */
2732                 nsinfo = findNamespaceByOid(i);
2733         }
2734
2735         if (nsinfo == NULL)
2736                 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
2737
2738         return nsinfo;
2739 }
2740
2741 /*
2742  * getExtensions:
2743  *        read all extensions in the system catalogs and return them in the
2744  * ExtensionInfo* structure
2745  *
2746  *      numExtensions is set to the number of extensions read in
2747  */
2748 ExtensionInfo *
2749 getExtensions(Archive *fout, int *numExtensions)
2750 {
2751         PGresult   *res;
2752         int                     ntups;
2753         int                     i;
2754         PQExpBuffer query;
2755         ExtensionInfo *extinfo;
2756         int                     i_tableoid;
2757         int                     i_oid;
2758         int                     i_extname;
2759         int                     i_nspname;
2760         int                     i_extrelocatable;
2761         int                     i_extversion;
2762         int                     i_extconfig;
2763         int                     i_extcondition;
2764
2765         /*
2766          * Before 9.1, there are no extensions.
2767          */
2768         if (fout->remoteVersion < 90100)
2769         {
2770                 *numExtensions = 0;
2771                 return NULL;
2772         }
2773
2774         query = createPQExpBuffer();
2775
2776         /* Make sure we are in proper schema */
2777         selectSourceSchema(fout, "pg_catalog");
2778
2779         appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
2780                                           "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
2781                                           "FROM pg_extension x "
2782                                           "JOIN pg_namespace n ON n.oid = x.extnamespace");
2783
2784         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2785
2786         ntups = PQntuples(res);
2787
2788         extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
2789
2790         i_tableoid = PQfnumber(res, "tableoid");
2791         i_oid = PQfnumber(res, "oid");
2792         i_extname = PQfnumber(res, "extname");
2793         i_nspname = PQfnumber(res, "nspname");
2794         i_extrelocatable = PQfnumber(res, "extrelocatable");
2795         i_extversion = PQfnumber(res, "extversion");
2796         i_extconfig = PQfnumber(res, "extconfig");
2797         i_extcondition = PQfnumber(res, "extcondition");
2798
2799         for (i = 0; i < ntups; i++)
2800         {
2801                 extinfo[i].dobj.objType = DO_EXTENSION;
2802                 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2803                 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2804                 AssignDumpId(&extinfo[i].dobj);
2805                 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
2806                 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
2807                 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
2808                 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
2809                 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
2810                 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
2811
2812                 /* Decide whether we want to dump it */
2813                 selectDumpableExtension(&(extinfo[i]));
2814         }
2815
2816         PQclear(res);
2817         destroyPQExpBuffer(query);
2818
2819         *numExtensions = ntups;
2820
2821         return extinfo;
2822 }
2823
2824 /*
2825  * getTypes:
2826  *        read all types in the system catalogs and return them in the
2827  * TypeInfo* structure
2828  *
2829  *      numTypes is set to the number of types read in
2830  *
2831  * NB: this must run after getFuncs() because we assume we can do
2832  * findFuncByOid().
2833  */
2834 TypeInfo *
2835 getTypes(Archive *fout, int *numTypes)
2836 {
2837         PGresult   *res;
2838         int                     ntups;
2839         int                     i;
2840         PQExpBuffer query = createPQExpBuffer();
2841         TypeInfo   *tyinfo;
2842         ShellTypeInfo *stinfo;
2843         int                     i_tableoid;
2844         int                     i_oid;
2845         int                     i_typname;
2846         int                     i_typnamespace;
2847         int                     i_typacl;
2848         int                     i_rolname;
2849         int                     i_typinput;
2850         int                     i_typoutput;
2851         int                     i_typelem;
2852         int                     i_typrelid;
2853         int                     i_typrelkind;
2854         int                     i_typtype;
2855         int                     i_typisdefined;
2856         int                     i_isarray;
2857
2858         /*
2859          * we include even the built-in types because those may be used as array
2860          * elements by user-defined types
2861          *
2862          * we filter out the built-in types when we dump out the types
2863          *
2864          * same approach for undefined (shell) types and array types
2865          *
2866          * Note: as of 8.3 we can reliably detect whether a type is an
2867          * auto-generated array type by checking the element type's typarray.
2868          * (Before that the test is capable of generating false positives.) We
2869          * still check for name beginning with '_', though, so as to avoid the
2870          * cost of the subselect probe for all standard types.  This would have to
2871          * be revisited if the backend ever allows renaming of array types.
2872          */
2873
2874         /* Make sure we are in proper schema */
2875         selectSourceSchema(fout, "pg_catalog");
2876
2877         if (fout->remoteVersion >= 90200)
2878         {
2879                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2880                                                   "typnamespace, typacl, "
2881                                                   "(%s typowner) AS rolname, "
2882                                                   "typinput::oid AS typinput, "
2883                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2884                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2885                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2886                                                   "typtype, typisdefined, "
2887                                                   "typname[0] = '_' AND typelem != 0 AND "
2888                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2889                                                   "FROM pg_type",
2890                                                   username_subquery);
2891         }
2892         else if (fout->remoteVersion >= 80300)
2893         {
2894                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2895                                                   "typnamespace, '{=U}' AS typacl, "
2896                                                   "(%s typowner) AS rolname, "
2897                                                   "typinput::oid AS typinput, "
2898                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2899                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2900                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2901                                                   "typtype, typisdefined, "
2902                                                   "typname[0] = '_' AND typelem != 0 AND "
2903                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2904                                                   "FROM pg_type",
2905                                                   username_subquery);
2906         }
2907         else if (fout->remoteVersion >= 70300)
2908         {
2909                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2910                                                   "typnamespace, '{=U}' AS typacl, "
2911                                                   "(%s typowner) AS rolname, "
2912                                                   "typinput::oid AS typinput, "
2913                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2914                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2915                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2916                                                   "typtype, typisdefined, "
2917                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2918                                                   "FROM pg_type",
2919                                                   username_subquery);
2920         }
2921         else if (fout->remoteVersion >= 70100)
2922         {
2923                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2924                                                   "0::oid AS typnamespace, '{=U}' AS typacl, "
2925                                                   "(%s typowner) AS rolname, "
2926                                                   "typinput::oid AS typinput, "
2927                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2928                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2929                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2930                                                   "typtype, typisdefined, "
2931                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2932                                                   "FROM pg_type",
2933                                                   username_subquery);
2934         }
2935         else
2936         {
2937                 appendPQExpBuffer(query, "SELECT "
2938                  "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
2939                                                   "oid, typname, "
2940                                                   "0::oid AS typnamespace, '{=U}' AS typacl, "
2941                                                   "(%s typowner) AS rolname, "
2942                                                   "typinput::oid AS typinput, "
2943                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2944                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2945                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2946                                                   "typtype, typisdefined, "
2947                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2948                                                   "FROM pg_type",
2949                                                   username_subquery);
2950         }
2951
2952         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2953
2954         ntups = PQntuples(res);
2955
2956         tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
2957
2958         i_tableoid = PQfnumber(res, "tableoid");
2959         i_oid = PQfnumber(res, "oid");
2960         i_typname = PQfnumber(res, "typname");
2961         i_typnamespace = PQfnumber(res, "typnamespace");
2962         i_typacl = PQfnumber(res, "typacl");
2963         i_rolname = PQfnumber(res, "rolname");
2964         i_typinput = PQfnumber(res, "typinput");
2965         i_typoutput = PQfnumber(res, "typoutput");
2966         i_typelem = PQfnumber(res, "typelem");
2967         i_typrelid = PQfnumber(res, "typrelid");
2968         i_typrelkind = PQfnumber(res, "typrelkind");
2969         i_typtype = PQfnumber(res, "typtype");
2970         i_typisdefined = PQfnumber(res, "typisdefined");
2971         i_isarray = PQfnumber(res, "isarray");
2972
2973         for (i = 0; i < ntups; i++)
2974         {
2975                 tyinfo[i].dobj.objType = DO_TYPE;
2976                 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2977                 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2978                 AssignDumpId(&tyinfo[i].dobj);
2979                 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
2980                 tyinfo[i].dobj.namespace =
2981                         findNamespace(fout,
2982                                                   atooid(PQgetvalue(res, i, i_typnamespace)),
2983                                                   tyinfo[i].dobj.catId.oid);
2984                 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2985                 tyinfo[i].typacl = pg_strdup(PQgetvalue(res, i, i_typacl));
2986                 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
2987                 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
2988                 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
2989                 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
2990                 tyinfo[i].shellType = NULL;
2991
2992                 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
2993                         tyinfo[i].isDefined = true;
2994                 else
2995                         tyinfo[i].isDefined = false;
2996
2997                 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
2998                         tyinfo[i].isArray = true;
2999                 else
3000                         tyinfo[i].isArray = false;
3001
3002                 /* Decide whether we want to dump it */
3003                 selectDumpableType(&tyinfo[i]);
3004
3005                 /*
3006                  * If it's a domain, fetch info about its constraints, if any
3007                  */
3008                 tyinfo[i].nDomChecks = 0;
3009                 tyinfo[i].domChecks = NULL;
3010                 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
3011                         getDomainConstraints(fout, &(tyinfo[i]));
3012
3013                 /*
3014                  * If it's a base type, make a DumpableObject representing a shell
3015                  * definition of the type.      We will need to dump that ahead of the I/O
3016                  * functions for the type.      Similarly, range types need a shell
3017                  * definition in case they have a canonicalize function.
3018                  *
3019                  * Note: the shell type doesn't have a catId.  You might think it
3020                  * should copy the base type's catId, but then it might capture the
3021                  * pg_depend entries for the type, which we don't want.
3022                  */
3023                 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
3024                                                                         tyinfo[i].typtype == TYPTYPE_RANGE))
3025                 {
3026                         stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
3027                         stinfo->dobj.objType = DO_SHELL_TYPE;
3028                         stinfo->dobj.catId = nilCatalogId;
3029                         AssignDumpId(&stinfo->dobj);
3030                         stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
3031                         stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
3032                         stinfo->baseType = &(tyinfo[i]);
3033                         tyinfo[i].shellType = stinfo;
3034
3035                         /*
3036                          * Initially mark the shell type as not to be dumped.  We'll only
3037                          * dump it if the I/O or canonicalize functions need to be dumped;
3038                          * this is taken care of while sorting dependencies.
3039                          */
3040                         stinfo->dobj.dump = false;
3041
3042                         /*
3043                          * However, if dumping from pre-7.3, there will be no dependency
3044                          * info so we have to fake it here.  We only need to worry about
3045                          * typinput and typoutput since the other functions only exist
3046                          * post-7.3.
3047                          */
3048                         if (fout->remoteVersion < 70300)
3049                         {
3050                                 Oid                     typinput;
3051                                 Oid                     typoutput;
3052                                 FuncInfo   *funcInfo;
3053
3054                                 typinput = atooid(PQgetvalue(res, i, i_typinput));
3055                                 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
3056
3057                                 funcInfo = findFuncByOid(typinput);
3058                                 if (funcInfo && funcInfo->dobj.dump)
3059                                 {
3060                                         /* base type depends on function */
3061                                         addObjectDependency(&tyinfo[i].dobj,
3062                                                                                 funcInfo->dobj.dumpId);
3063                                         /* function depends on shell type */
3064                                         addObjectDependency(&funcInfo->dobj,
3065                                                                                 stinfo->dobj.dumpId);
3066                                         /* mark shell type as to be dumped */
3067                                         stinfo->dobj.dump = true;
3068                                 }
3069
3070                                 funcInfo = findFuncByOid(typoutput);
3071                                 if (funcInfo && funcInfo->dobj.dump)
3072                                 {
3073                                         /* base type depends on function */
3074                                         addObjectDependency(&tyinfo[i].dobj,
3075                                                                                 funcInfo->dobj.dumpId);
3076                                         /* function depends on shell type */
3077                                         addObjectDependency(&funcInfo->dobj,
3078                                                                                 stinfo->dobj.dumpId);
3079                                         /* mark shell type as to be dumped */
3080                                         stinfo->dobj.dump = true;
3081                                 }
3082                         }
3083                 }
3084
3085                 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3086                         write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3087                                           tyinfo[i].dobj.name);
3088         }
3089
3090         *numTypes = ntups;
3091
3092         PQclear(res);
3093
3094         destroyPQExpBuffer(query);
3095
3096         return tyinfo;
3097 }
3098
3099 /*
3100  * getOperators:
3101  *        read all operators in the system catalogs and return them in the
3102  * OprInfo* structure
3103  *
3104  *      numOprs is set to the number of operators read in
3105  */
3106 OprInfo *
3107 getOperators(Archive *fout, int *numOprs)
3108 {
3109         PGresult   *res;
3110         int                     ntups;
3111         int                     i;
3112         PQExpBuffer query = createPQExpBuffer();
3113         OprInfo    *oprinfo;
3114         int                     i_tableoid;
3115         int                     i_oid;
3116         int                     i_oprname;
3117         int                     i_oprnamespace;
3118         int                     i_rolname;
3119         int                     i_oprkind;
3120         int                     i_oprcode;
3121
3122         /*
3123          * find all operators, including builtin operators; we filter out
3124          * system-defined operators at dump-out time.
3125          */
3126
3127         /* Make sure we are in proper schema */
3128         selectSourceSchema(fout, "pg_catalog");
3129
3130         if (fout->remoteVersion >= 70300)
3131         {
3132                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3133                                                   "oprnamespace, "
3134                                                   "(%s oprowner) AS rolname, "
3135                                                   "oprkind, "
3136                                                   "oprcode::oid AS oprcode "
3137                                                   "FROM pg_operator",
3138                                                   username_subquery);
3139         }
3140         else if (fout->remoteVersion >= 70100)
3141         {
3142                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3143                                                   "0::oid AS oprnamespace, "
3144                                                   "(%s oprowner) AS rolname, "
3145                                                   "oprkind, "
3146                                                   "oprcode::oid AS oprcode "
3147                                                   "FROM pg_operator",
3148                                                   username_subquery);
3149         }
3150         else
3151         {
3152                 appendPQExpBuffer(query, "SELECT "
3153                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3154                                                   "oid, oprname, "
3155                                                   "0::oid AS oprnamespace, "
3156                                                   "(%s oprowner) AS rolname, "
3157                                                   "oprkind, "
3158                                                   "oprcode::oid AS oprcode "
3159                                                   "FROM pg_operator",
3160                                                   username_subquery);
3161         }
3162
3163         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3164
3165         ntups = PQntuples(res);
3166         *numOprs = ntups;
3167
3168         oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3169
3170         i_tableoid = PQfnumber(res, "tableoid");
3171         i_oid = PQfnumber(res, "oid");
3172         i_oprname = PQfnumber(res, "oprname");
3173         i_oprnamespace = PQfnumber(res, "oprnamespace");
3174         i_rolname = PQfnumber(res, "rolname");
3175         i_oprkind = PQfnumber(res, "oprkind");
3176         i_oprcode = PQfnumber(res, "oprcode");
3177
3178         for (i = 0; i < ntups; i++)
3179         {
3180                 oprinfo[i].dobj.objType = DO_OPERATOR;
3181                 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3182                 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3183                 AssignDumpId(&oprinfo[i].dobj);
3184                 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3185                 oprinfo[i].dobj.namespace =
3186                         findNamespace(fout,
3187                                                   atooid(PQgetvalue(res, i, i_oprnamespace)),
3188                                                   oprinfo[i].dobj.catId.oid);
3189                 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3190                 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3191                 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3192
3193                 /* Decide whether we want to dump it */
3194                 selectDumpableObject(&(oprinfo[i].dobj));
3195
3196                 if (strlen(oprinfo[i].rolname) == 0)
3197                         write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3198                                           oprinfo[i].dobj.name);
3199         }
3200
3201         PQclear(res);
3202
3203         destroyPQExpBuffer(query);
3204
3205         return oprinfo;
3206 }
3207
3208 /*
3209  * getCollations:
3210  *        read all collations in the system catalogs and return them in the
3211  * CollInfo* structure
3212  *
3213  *      numCollations is set to the number of collations read in
3214  */
3215 CollInfo *
3216 getCollations(Archive *fout, int *numCollations)
3217 {
3218         PGresult   *res;
3219         int                     ntups;
3220         int                     i;
3221         PQExpBuffer query;
3222         CollInfo   *collinfo;
3223         int                     i_tableoid;
3224         int                     i_oid;
3225         int                     i_collname;
3226         int                     i_collnamespace;
3227         int                     i_rolname;
3228
3229         /* Collations didn't exist pre-9.1 */
3230         if (fout->remoteVersion < 90100)
3231         {
3232                 *numCollations = 0;
3233                 return NULL;
3234         }
3235
3236         query = createPQExpBuffer();
3237
3238         /*
3239          * find all collations, including builtin collations; we filter out
3240          * system-defined collations at dump-out time.
3241          */
3242
3243         /* Make sure we are in proper schema */
3244         selectSourceSchema(fout, "pg_catalog");
3245
3246         appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3247                                           "collnamespace, "
3248                                           "(%s collowner) AS rolname "
3249                                           "FROM pg_collation",
3250                                           username_subquery);
3251
3252         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3253
3254         ntups = PQntuples(res);
3255         *numCollations = ntups;
3256
3257         collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3258
3259         i_tableoid = PQfnumber(res, "tableoid");
3260         i_oid = PQfnumber(res, "oid");
3261         i_collname = PQfnumber(res, "collname");
3262         i_collnamespace = PQfnumber(res, "collnamespace");
3263         i_rolname = PQfnumber(res, "rolname");
3264
3265         for (i = 0; i < ntups; i++)
3266         {
3267                 collinfo[i].dobj.objType = DO_COLLATION;
3268                 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3269                 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3270                 AssignDumpId(&collinfo[i].dobj);
3271                 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3272                 collinfo[i].dobj.namespace =
3273                         findNamespace(fout,
3274                                                   atooid(PQgetvalue(res, i, i_collnamespace)),
3275                                                   collinfo[i].dobj.catId.oid);
3276                 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3277
3278                 /* Decide whether we want to dump it */
3279                 selectDumpableObject(&(collinfo[i].dobj));
3280         }
3281
3282         PQclear(res);
3283
3284         destroyPQExpBuffer(query);
3285
3286         return collinfo;
3287 }
3288
3289 /*
3290  * getConversions:
3291  *        read all conversions in the system catalogs and return them in the
3292  * ConvInfo* structure
3293  *
3294  *      numConversions is set to the number of conversions read in
3295  */
3296 ConvInfo *
3297 getConversions(Archive *fout, int *numConversions)
3298 {
3299         PGresult   *res;
3300         int                     ntups;
3301         int                     i;
3302         PQExpBuffer query = createPQExpBuffer();
3303         ConvInfo   *convinfo;
3304         int                     i_tableoid;
3305         int                     i_oid;
3306         int                     i_conname;
3307         int                     i_connamespace;
3308         int                     i_rolname;
3309
3310         /* Conversions didn't exist pre-7.3 */
3311         if (fout->remoteVersion < 70300)
3312         {
3313                 *numConversions = 0;
3314                 return NULL;
3315         }
3316
3317         /*
3318          * find all conversions, including builtin conversions; we filter out
3319          * system-defined conversions at dump-out time.
3320          */
3321
3322         /* Make sure we are in proper schema */
3323         selectSourceSchema(fout, "pg_catalog");
3324
3325         appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3326                                           "connamespace, "
3327                                           "(%s conowner) AS rolname "
3328                                           "FROM pg_conversion",
3329                                           username_subquery);
3330
3331         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3332
3333         ntups = PQntuples(res);
3334         *numConversions = ntups;
3335
3336         convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3337
3338         i_tableoid = PQfnumber(res, "tableoid");
3339         i_oid = PQfnumber(res, "oid");
3340         i_conname = PQfnumber(res, "conname");
3341         i_connamespace = PQfnumber(res, "connamespace");
3342         i_rolname = PQfnumber(res, "rolname");
3343
3344         for (i = 0; i < ntups; i++)
3345         {
3346                 convinfo[i].dobj.objType = DO_CONVERSION;
3347                 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3348                 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3349                 AssignDumpId(&convinfo[i].dobj);
3350                 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3351                 convinfo[i].dobj.namespace =
3352                         findNamespace(fout,
3353                                                   atooid(PQgetvalue(res, i, i_connamespace)),
3354                                                   convinfo[i].dobj.catId.oid);
3355                 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3356
3357                 /* Decide whether we want to dump it */
3358                 selectDumpableObject(&(convinfo[i].dobj));
3359         }
3360
3361         PQclear(res);
3362
3363         destroyPQExpBuffer(query);
3364
3365         return convinfo;
3366 }
3367
3368 /*
3369  * getOpclasses:
3370  *        read all opclasses in the system catalogs and return them in the
3371  * OpclassInfo* structure
3372  *
3373  *      numOpclasses is set to the number of opclasses read in
3374  */
3375 OpclassInfo *
3376 getOpclasses(Archive *fout, int *numOpclasses)
3377 {
3378         PGresult   *res;
3379         int                     ntups;
3380         int                     i;
3381         PQExpBuffer query = createPQExpBuffer();
3382         OpclassInfo *opcinfo;
3383         int                     i_tableoid;
3384         int                     i_oid;
3385         int                     i_opcname;
3386         int                     i_opcnamespace;
3387         int                     i_rolname;
3388
3389         /*
3390          * find all opclasses, including builtin opclasses; we filter out
3391          * system-defined opclasses at dump-out time.
3392          */
3393
3394         /* Make sure we are in proper schema */
3395         selectSourceSchema(fout, "pg_catalog");
3396
3397         if (fout->remoteVersion >= 70300)
3398         {
3399                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3400                                                   "opcnamespace, "
3401                                                   "(%s opcowner) AS rolname "
3402                                                   "FROM pg_opclass",
3403                                                   username_subquery);
3404         }
3405         else if (fout->remoteVersion >= 70100)
3406         {
3407                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3408                                                   "0::oid AS opcnamespace, "
3409                                                   "''::name AS rolname "
3410                                                   "FROM pg_opclass");
3411         }
3412         else
3413         {
3414                 appendPQExpBuffer(query, "SELECT "
3415                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3416                                                   "oid, opcname, "
3417                                                   "0::oid AS opcnamespace, "
3418                                                   "''::name AS rolname "
3419                                                   "FROM pg_opclass");
3420         }
3421
3422         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3423
3424         ntups = PQntuples(res);
3425         *numOpclasses = ntups;
3426
3427         opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3428
3429         i_tableoid = PQfnumber(res, "tableoid");
3430         i_oid = PQfnumber(res, "oid");
3431         i_opcname = PQfnumber(res, "opcname");
3432         i_opcnamespace = PQfnumber(res, "opcnamespace");
3433         i_rolname = PQfnumber(res, "rolname");
3434
3435         for (i = 0; i < ntups; i++)
3436         {
3437                 opcinfo[i].dobj.objType = DO_OPCLASS;
3438                 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3439                 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3440                 AssignDumpId(&opcinfo[i].dobj);
3441                 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3442                 opcinfo[i].dobj.namespace =
3443                         findNamespace(fout,
3444                                                   atooid(PQgetvalue(res, i, i_opcnamespace)),
3445                                                   opcinfo[i].dobj.catId.oid);
3446                 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3447
3448                 /* Decide whether we want to dump it */
3449                 selectDumpableObject(&(opcinfo[i].dobj));
3450
3451                 if (fout->remoteVersion >= 70300)
3452                 {
3453                         if (strlen(opcinfo[i].rolname) == 0)
3454                                 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3455                                                   opcinfo[i].dobj.name);
3456                 }
3457         }
3458
3459         PQclear(res);
3460
3461         destroyPQExpBuffer(query);
3462
3463         return opcinfo;
3464 }
3465
3466 /*
3467  * getOpfamilies:
3468  *        read all opfamilies in the system catalogs and return them in the
3469  * OpfamilyInfo* structure
3470  *
3471  *      numOpfamilies is set to the number of opfamilies read in
3472  */
3473 OpfamilyInfo *
3474 getOpfamilies(Archive *fout, int *numOpfamilies)
3475 {
3476         PGresult   *res;
3477         int                     ntups;
3478         int                     i;
3479         PQExpBuffer query;
3480         OpfamilyInfo *opfinfo;
3481         int                     i_tableoid;
3482         int                     i_oid;
3483         int                     i_opfname;
3484         int                     i_opfnamespace;
3485         int                     i_rolname;
3486
3487         /* Before 8.3, there is no separate concept of opfamilies */
3488         if (fout->remoteVersion < 80300)
3489         {
3490                 *numOpfamilies = 0;
3491                 return NULL;
3492         }
3493
3494         query = createPQExpBuffer();
3495
3496         /*
3497          * find all opfamilies, including builtin opfamilies; we filter out
3498          * system-defined opfamilies at dump-out time.
3499          */
3500
3501         /* Make sure we are in proper schema */
3502         selectSourceSchema(fout, "pg_catalog");
3503
3504         appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3505                                           "opfnamespace, "
3506                                           "(%s opfowner) AS rolname "
3507                                           "FROM pg_opfamily",
3508                                           username_subquery);
3509
3510         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3511
3512         ntups = PQntuples(res);
3513         *numOpfamilies = ntups;
3514
3515         opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3516
3517         i_tableoid = PQfnumber(res, "tableoid");
3518         i_oid = PQfnumber(res, "oid");
3519         i_opfname = PQfnumber(res, "opfname");
3520         i_opfnamespace = PQfnumber(res, "opfnamespace");
3521         i_rolname = PQfnumber(res, "rolname");
3522
3523         for (i = 0; i < ntups; i++)
3524         {
3525                 opfinfo[i].dobj.objType = DO_OPFAMILY;
3526                 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3527                 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3528                 AssignDumpId(&opfinfo[i].dobj);
3529                 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3530                 opfinfo[i].dobj.namespace =
3531                         findNamespace(fout,
3532                                                   atooid(PQgetvalue(res, i, i_opfnamespace)),
3533                                                   opfinfo[i].dobj.catId.oid);
3534                 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3535
3536                 /* Decide whether we want to dump it */
3537                 selectDumpableObject(&(opfinfo[i].dobj));
3538
3539                 if (fout->remoteVersion >= 70300)
3540                 {
3541                         if (strlen(opfinfo[i].rolname) == 0)
3542                                 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3543                                                   opfinfo[i].dobj.name);
3544                 }
3545         }
3546
3547         PQclear(res);
3548
3549         destroyPQExpBuffer(query);
3550
3551         return opfinfo;
3552 }
3553
3554 /*
3555  * getAggregates:
3556  *        read all the user-defined aggregates in the system catalogs and
3557  * return them in the AggInfo* structure
3558  *
3559  * numAggs is set to the number of aggregates read in
3560  */
3561 AggInfo *
3562 getAggregates(Archive *fout, int *numAggs)
3563 {
3564         PGresult   *res;
3565         int                     ntups;
3566         int                     i;
3567         PQExpBuffer query = createPQExpBuffer();
3568         AggInfo    *agginfo;
3569         int                     i_tableoid;
3570         int                     i_oid;
3571         int                     i_aggname;
3572         int                     i_aggnamespace;
3573         int                     i_pronargs;
3574         int                     i_proargtypes;
3575         int                     i_rolname;
3576         int                     i_aggacl;
3577         int                     i_proiargs;
3578
3579         /* Make sure we are in proper schema */
3580         selectSourceSchema(fout, "pg_catalog");
3581
3582         /*
3583          * Find all user-defined aggregates.  See comment in getFuncs() for the
3584          * rationale behind the filtering logic.
3585          */
3586
3587         if (fout->remoteVersion >= 80400)
3588         {
3589                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3590                                                   "pronamespace AS aggnamespace, "
3591                                                   "pronargs, proargtypes, "
3592                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS proiargs,"
3593                                                   "(%s proowner) AS rolname, "
3594                                                   "proacl AS aggacl "
3595                                                   "FROM pg_proc p "
3596                                                   "WHERE proisagg AND ("
3597                                                   "pronamespace != "
3598                                                   "(SELECT oid FROM pg_namespace "
3599                                                   "WHERE nspname = 'pg_catalog')",
3600                                                   username_subquery);
3601                 if (binary_upgrade && fout->remoteVersion >= 90100)
3602                         appendPQExpBuffer(query,
3603                                                           " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3604                                                           "classid = 'pg_proc'::regclass AND "
3605                                                           "objid = p.oid AND "
3606                                                           "refclassid = 'pg_extension'::regclass AND "
3607                                                           "deptype = 'e')");
3608                 appendPQExpBuffer(query, ")");
3609         }
3610         else if (fout->remoteVersion >= 80200)
3611         {
3612                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3613                                                   "pronamespace AS aggnamespace, "
3614                                                   "pronargs, proargtypes, "
3615                                                   "NULL::text AS proiargs,"
3616                                                   "(%s proowner) AS rolname, "
3617                                                   "proacl AS aggacl "
3618                                                   "FROM pg_proc p "
3619                                                   "WHERE proisagg AND ("
3620                                                   "pronamespace != "
3621                                                   "(SELECT oid FROM pg_namespace "
3622                                                   "WHERE nspname = 'pg_catalog'))",
3623                                                   username_subquery);
3624         }
3625         else if (fout->remoteVersion >= 70300)
3626         {
3627                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3628                                                   "pronamespace AS aggnamespace, "
3629                                                   "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3630                                                   "proargtypes, "
3631                                                   "NULL::text AS proiargs, "
3632                                                   "(%s proowner) AS rolname, "
3633                                                   "proacl AS aggacl "
3634                                                   "FROM pg_proc "
3635                                                   "WHERE proisagg "
3636                                                   "AND pronamespace != "
3637                            "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3638                                                   username_subquery);
3639         }
3640         else if (fout->remoteVersion >= 70100)
3641         {
3642                 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3643                                                   "0::oid AS aggnamespace, "
3644                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3645                                                   "aggbasetype AS proargtypes, "
3646                                                   "NULL::text AS proiargs, "
3647                                                   "(%s aggowner) AS rolname, "
3648                                                   "'{=X}' AS aggacl "
3649                                                   "FROM pg_aggregate "
3650                                                   "where oid > '%u'::oid",
3651                                                   username_subquery,
3652                                                   g_last_builtin_oid);
3653         }
3654         else
3655         {
3656                 appendPQExpBuffer(query, "SELECT "
3657                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3658                                                   "oid, aggname, "
3659                                                   "0::oid AS aggnamespace, "
3660                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3661                                                   "aggbasetype AS proargtypes, "
3662                                                   "NULL::text AS proiargs, "
3663                                                   "(%s aggowner) AS rolname, "
3664                                                   "'{=X}' AS aggacl "
3665                                                   "FROM pg_aggregate "
3666                                                   "where oid > '%u'::oid",
3667                                                   username_subquery,
3668                                                   g_last_builtin_oid);
3669         }
3670
3671         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3672
3673         ntups = PQntuples(res);
3674         *numAggs = ntups;
3675
3676         agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3677
3678         i_tableoid = PQfnumber(res, "tableoid");
3679         i_oid = PQfnumber(res, "oid");
3680         i_aggname = PQfnumber(res, "aggname");
3681         i_aggnamespace = PQfnumber(res, "aggnamespace");
3682         i_pronargs = PQfnumber(res, "pronargs");
3683         i_proargtypes = PQfnumber(res, "proargtypes");
3684         i_rolname = PQfnumber(res, "rolname");
3685         i_aggacl = PQfnumber(res, "aggacl");
3686         i_proiargs = PQfnumber(res, "proiargs");
3687
3688         for (i = 0; i < ntups; i++)
3689         {
3690                 agginfo[i].aggfn.dobj.objType = DO_AGG;
3691                 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3692                 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3693                 AssignDumpId(&agginfo[i].aggfn.dobj);
3694                 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3695                 agginfo[i].aggfn.dobj.namespace =
3696                         findNamespace(fout,
3697                                                   atooid(PQgetvalue(res, i, i_aggnamespace)),
3698                                                   agginfo[i].aggfn.dobj.catId.oid);
3699                 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3700                 if (strlen(agginfo[i].aggfn.rolname) == 0)
3701                         write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3702                                           agginfo[i].aggfn.dobj.name);
3703                 agginfo[i].aggfn.lang = InvalidOid;             /* not currently interesting */
3704                 agginfo[i].aggfn.prorettype = InvalidOid;               /* not saved */
3705                 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3706                 agginfo[i].aggfn.proiargs = pg_strdup(PQgetvalue(res, i, i_proiargs));
3707                 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3708                 if (agginfo[i].aggfn.nargs == 0)
3709                         agginfo[i].aggfn.argtypes = NULL;
3710                 else
3711                 {
3712                         agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3713                         if (fout->remoteVersion >= 70300)
3714                                 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3715                                                           agginfo[i].aggfn.argtypes,
3716                                                           agginfo[i].aggfn.nargs);
3717                         else
3718                                 /* it's just aggbasetype */
3719                                 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3720                 }
3721
3722                 /* Decide whether we want to dump it */
3723                 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3724         }
3725
3726         PQclear(res);
3727
3728         destroyPQExpBuffer(query);
3729
3730         return agginfo;
3731 }
3732
3733 /*
3734  * getFuncs:
3735  *        read all the user-defined functions in the system catalogs and
3736  * return them in the FuncInfo* structure
3737  *
3738  * numFuncs is set to the number of functions read in
3739  */
3740 FuncInfo *
3741 getFuncs(Archive *fout, int *numFuncs)
3742 {
3743         PGresult   *res;
3744         int                     ntups;
3745         int                     i;
3746         PQExpBuffer query = createPQExpBuffer();
3747         FuncInfo   *finfo;
3748         int                     i_tableoid;
3749         int                     i_oid;
3750         int                     i_proname;
3751         int                     i_pronamespace;
3752         int                     i_rolname;
3753         int                     i_prolang;
3754         int                     i_pronargs;
3755         int                     i_proargtypes;
3756         int                     i_prorettype;
3757         int                     i_proacl;
3758         int                     i_proiargs;
3759
3760         /* Make sure we are in proper schema */
3761         selectSourceSchema(fout, "pg_catalog");
3762
3763         /*
3764          * Find all user-defined functions.  Normally we can exclude functions in
3765          * pg_catalog, which is worth doing since there are several thousand of
3766          * 'em.  However, there are some extensions that create functions in
3767          * pg_catalog.  In normal dumps we can still ignore those --- but in
3768          * binary-upgrade mode, we must dump the member objects of the extension,
3769          * so be sure to fetch any such functions.
3770          *
3771          * Also, in 9.2 and up, exclude functions that are internally dependent on
3772          * something else, since presumably those will be created as a result of
3773          * creating the something else.  This currently only acts to suppress
3774          * constructor functions for range types.  Note that this is OK only
3775          * because the constructors don't have any dependencies the range type
3776          * doesn't have; otherwise we might not get creation ordering correct.
3777          */
3778
3779         if (fout->remoteVersion >= 80400)
3780         {
3781                 appendPQExpBuffer(query,
3782                                                   "SELECT tableoid, oid, proname, prolang, "
3783                                                   "pronargs, proargtypes, prorettype, proacl, "
3784                                                   "pronamespace, "
3785                                                   "pg_catalog.pg_get_function_identity_arguments(oid) AS proiargs,"
3786                                                   "(%s proowner) AS rolname "
3787                                                   "FROM pg_proc p "
3788                                                   "WHERE NOT proisagg AND ("
3789                                                   "pronamespace != "
3790                                                   "(SELECT oid FROM pg_namespace "
3791                                                   "WHERE nspname = 'pg_catalog')",
3792                                                   username_subquery);
3793                 if (fout->remoteVersion >= 90200)
3794                         appendPQExpBuffer(query,
3795                                                           "\n  AND NOT EXISTS (SELECT 1 FROM pg_depend "
3796                                                           "WHERE classid = 'pg_proc'::regclass AND "
3797                                                           "objid = p.oid AND deptype = 'i')");
3798                 if (binary_upgrade && fout->remoteVersion >= 90100)
3799                         appendPQExpBuffer(query,
3800                                                           "\n  OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3801                                                           "classid = 'pg_proc'::regclass AND "
3802                                                           "objid = p.oid AND "
3803                                                           "refclassid = 'pg_extension'::regclass AND "
3804                                                           "deptype = 'e')");
3805                 appendPQExpBuffer(query, ")");
3806         }
3807         else if (fout->remoteVersion >= 70300)
3808         {
3809                 appendPQExpBuffer(query,
3810                                                   "SELECT tableoid, oid, proname, prolang, "
3811                                                   "pronargs, proargtypes, prorettype, proacl, "
3812                                                   "pronamespace, "
3813                                                   "NULL::text AS proiargs,"
3814                                                   "(%s proowner) AS rolname "
3815                                                   "FROM pg_proc p "
3816                                                   "WHERE NOT proisagg AND ("
3817                                                   "pronamespace != "
3818                                                   "(SELECT oid FROM pg_namespace "
3819                                                   "WHERE nspname = 'pg_catalog'))",
3820                                                   username_subquery);
3821         }
3822         else if (fout->remoteVersion >= 70100)
3823         {
3824                 appendPQExpBuffer(query,
3825                                                   "SELECT tableoid, oid, proname, prolang, "
3826                                                   "pronargs, proargtypes, prorettype, "
3827                                                   "'{=X}' AS proacl, "
3828                                                   "0::oid AS pronamespace, "
3829                                                   "NULL::text AS proiargs,"
3830                                                   "(%s proowner) AS rolname "
3831                                                   "FROM pg_proc "
3832                                                   "WHERE pg_proc.oid > '%u'::oid",
3833                                                   username_subquery,
3834                                                   g_last_builtin_oid);
3835         }
3836         else
3837         {
3838                 appendPQExpBuffer(query,
3839                                                   "SELECT "
3840                                                   "(SELECT oid FROM pg_class "
3841                                                   " WHERE relname = 'pg_proc') AS tableoid, "
3842                                                   "oid, proname, prolang, "
3843                                                   "pronargs, proargtypes, prorettype, "
3844                                                   "'{=X}' AS proacl, "
3845                                                   "0::oid AS pronamespace, "
3846                                                   "NULL::text AS proiargs,"
3847                                                   "(%s proowner) AS rolname "
3848                                                   "FROM pg_proc "
3849                                                   "where pg_proc.oid > '%u'::oid",
3850                                                   username_subquery,
3851                                                   g_last_builtin_oid);
3852         }
3853
3854         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3855
3856         ntups = PQntuples(res);
3857
3858         *numFuncs = ntups;
3859
3860         finfo = (FuncInfo *) pg_malloc0(ntups * sizeof(FuncInfo));
3861
3862         i_tableoid = PQfnumber(res, "tableoid");
3863         i_oid = PQfnumber(res, "oid");
3864         i_proname = PQfnumber(res, "proname");
3865         i_pronamespace = PQfnumber(res, "pronamespace");
3866         i_rolname = PQfnumber(res, "rolname");
3867         i_prolang = PQfnumber(res, "prolang");
3868         i_pronargs = PQfnumber(res, "pronargs");
3869         i_proargtypes = PQfnumber(res, "proargtypes");
3870         i_prorettype = PQfnumber(res, "prorettype");
3871         i_proacl = PQfnumber(res, "proacl");
3872         i_proiargs = PQfnumber(res, "proiargs");
3873
3874         for (i = 0; i < ntups; i++)
3875         {
3876                 finfo[i].dobj.objType = DO_FUNC;
3877                 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3878                 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3879                 AssignDumpId(&finfo[i].dobj);
3880                 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
3881                 finfo[i].dobj.namespace =
3882                         findNamespace(fout,
3883                                                   atooid(PQgetvalue(res, i, i_pronamespace)),
3884                                                   finfo[i].dobj.catId.oid);
3885                 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3886                 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
3887                 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
3888                 finfo[i].proiargs = pg_strdup(PQgetvalue(res, i, i_proiargs));
3889                 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
3890                 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
3891                 if (finfo[i].nargs == 0)
3892                         finfo[i].argtypes = NULL;
3893                 else
3894                 {
3895                         finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
3896                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
3897                                                   finfo[i].argtypes, finfo[i].nargs);
3898                 }
3899
3900                 /* Decide whether we want to dump it */
3901                 selectDumpableObject(&(finfo[i].dobj));
3902
3903                 if (strlen(finfo[i].rolname) == 0)
3904                         write_msg(NULL,
3905                                  "WARNING: owner of function \"%s\" appears to be invalid\n",
3906                                           finfo[i].dobj.name);
3907         }
3908
3909         PQclear(res);
3910
3911         destroyPQExpBuffer(query);
3912
3913         return finfo;
3914 }
3915
3916 /*
3917  * getTables
3918  *        read all the user-defined tables (no indexes, no catalogs)
3919  * in the system catalogs return them in the TableInfo* structure
3920  *
3921  * numTables is set to the number of tables read in
3922  */
3923 TableInfo *
3924 getTables(Archive *fout, int *numTables)
3925 {
3926         PGresult   *res;
3927         int                     ntups;
3928         int                     i;
3929         PQExpBuffer query = createPQExpBuffer();
3930         TableInfo  *tblinfo;
3931         int                     i_reltableoid;
3932         int                     i_reloid;
3933         int                     i_relname;
3934         int                     i_relnamespace;
3935         int                     i_relkind;
3936         int                     i_relacl;
3937         int                     i_rolname;
3938         int                     i_relchecks;
3939         int                     i_relhastriggers;
3940         int                     i_relhasindex;
3941         int                     i_relhasrules;
3942         int                     i_relhasoids;
3943         int                     i_relfrozenxid;
3944         int                     i_toastoid;
3945         int                     i_toastfrozenxid;
3946         int                     i_relpersistence;
3947         int                     i_owning_tab;
3948         int                     i_owning_col;
3949         int                     i_reltablespace;
3950         int                     i_reloptions;
3951         int                     i_toastreloptions;
3952         int                     i_reloftype;
3953
3954         /* Make sure we are in proper schema */
3955         selectSourceSchema(fout, "pg_catalog");
3956
3957         /*
3958          * Find all the tables and table-like objects.
3959          *
3960          * We include system catalogs, so that we can work if a user table is
3961          * defined to inherit from a system catalog (pretty weird, but...)
3962          *
3963          * We ignore relations that are not ordinary tables, sequences, views,
3964          * composite types, or foreign tables.
3965          *
3966          * Composite-type table entries won't be dumped as such, but we have to
3967          * make a DumpableObject for them so that we can track dependencies of the
3968          * composite type (pg_depend entries for columns of the composite type
3969          * link to the pg_class entry not the pg_type entry).
3970          *
3971          * Note: in this phase we should collect only a minimal amount of
3972          * information about each table, basically just enough to decide if it is
3973          * interesting. We must fetch all tables in this phase because otherwise
3974          * we cannot correctly identify inherited columns, owned sequences, etc.
3975          */
3976
3977         if (fout->remoteVersion >= 90100)
3978         {
3979                 /*
3980                  * Left join to pick up dependency info linking sequences to their
3981                  * owning column, if any (note this dependency is AUTO as of 8.2)
3982                  */
3983                 appendPQExpBuffer(query,
3984                                                   "SELECT c.tableoid, c.oid, c.relname, "
3985                                                   "c.relacl, c.relkind, c.relnamespace, "
3986                                                   "(%s c.relowner) AS rolname, "
3987                                                   "c.relchecks, c.relhastriggers, "
3988                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3989                                                   "c.relfrozenxid, tc.oid AS toid, "
3990                                                   "tc.relfrozenxid AS tfrozenxid, "
3991                                                   "c.relpersistence, "
3992                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3993                                                   "d.refobjid AS owning_tab, "
3994                                                   "d.refobjsubid AS owning_col, "
3995                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3996                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3997                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3998                                                   "FROM pg_class c "
3999                                                   "LEFT JOIN pg_depend d ON "
4000                                                   "(c.relkind = '%c' AND "
4001                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4002                                                   "d.objsubid = 0 AND "
4003                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4004                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4005                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c') "
4006                                                   "ORDER BY c.oid",
4007                                                   username_subquery,
4008                                                   RELKIND_SEQUENCE,
4009                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4010                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
4011                                                   RELKIND_FOREIGN_TABLE);
4012         }
4013         else if (fout->remoteVersion >= 90000)
4014         {
4015                 /*
4016                  * Left join to pick up dependency info linking sequences to their
4017                  * owning column, if any (note this dependency is AUTO as of 8.2)
4018                  */
4019                 appendPQExpBuffer(query,
4020                                                   "SELECT c.tableoid, c.oid, c.relname, "
4021                                                   "c.relacl, c.relkind, c.relnamespace, "
4022                                                   "(%s c.relowner) AS rolname, "
4023                                                   "c.relchecks, c.relhastriggers, "
4024                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4025                                                   "c.relfrozenxid, tc.oid AS toid, "
4026                                                   "tc.relfrozenxid AS tfrozenxid, "
4027                                                   "'p' AS relpersistence, "
4028                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4029                                                   "d.refobjid AS owning_tab, "
4030                                                   "d.refobjsubid AS owning_col, "
4031                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4032                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4033                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4034                                                   "FROM pg_class c "
4035                                                   "LEFT JOIN pg_depend d ON "
4036                                                   "(c.relkind = '%c' AND "
4037                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4038                                                   "d.objsubid = 0 AND "
4039                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4040                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4041                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4042                                                   "ORDER BY c.oid",
4043                                                   username_subquery,
4044                                                   RELKIND_SEQUENCE,
4045                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4046                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4047         }
4048         else if (fout->remoteVersion >= 80400)
4049         {
4050                 /*
4051                  * Left join to pick up dependency info linking sequences to their
4052                  * owning column, if any (note this dependency is AUTO as of 8.2)
4053                  */
4054                 appendPQExpBuffer(query,
4055                                                   "SELECT c.tableoid, c.oid, c.relname, "
4056                                                   "c.relacl, c.relkind, c.relnamespace, "
4057                                                   "(%s c.relowner) AS rolname, "
4058                                                   "c.relchecks, c.relhastriggers, "
4059                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4060                                                   "c.relfrozenxid, tc.oid AS toid, "
4061                                                   "tc.relfrozenxid AS tfrozenxid, "
4062                                                   "'p' AS relpersistence, "
4063                                                   "NULL AS reloftype, "
4064                                                   "d.refobjid AS owning_tab, "
4065                                                   "d.refobjsubid AS owning_col, "
4066                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4067                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4068                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4069                                                   "FROM pg_class c "
4070                                                   "LEFT JOIN pg_depend d ON "
4071                                                   "(c.relkind = '%c' AND "
4072                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4073                                                   "d.objsubid = 0 AND "
4074                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4075                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4076                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4077                                                   "ORDER BY c.oid",
4078                                                   username_subquery,
4079                                                   RELKIND_SEQUENCE,
4080                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4081                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4082         }
4083         else if (fout->remoteVersion >= 80200)
4084         {
4085                 /*
4086                  * Left join to pick up dependency info linking sequences to their
4087                  * owning column, if any (note this dependency is AUTO as of 8.2)
4088                  */
4089                 appendPQExpBuffer(query,
4090                                                   "SELECT c.tableoid, c.oid, c.relname, "
4091                                                   "c.relacl, c.relkind, c.relnamespace, "
4092                                                   "(%s c.relowner) AS rolname, "
4093                                           "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
4094                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4095                                                   "c.relfrozenxid, tc.oid AS toid, "
4096                                                   "tc.relfrozenxid AS tfrozenxid, "
4097                                                   "'p' AS relpersistence, "
4098                                                   "NULL AS reloftype, "
4099                                                   "d.refobjid AS owning_tab, "
4100                                                   "d.refobjsubid AS owning_col, "
4101                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4102                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4103                                                   "NULL AS toast_reloptions "
4104                                                   "FROM pg_class c "
4105                                                   "LEFT JOIN pg_depend d ON "
4106                                                   "(c.relkind = '%c' AND "
4107                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4108                                                   "d.objsubid = 0 AND "
4109                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4110                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4111                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4112                                                   "ORDER BY c.oid",
4113                                                   username_subquery,
4114                                                   RELKIND_SEQUENCE,
4115                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4116                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4117         }
4118         else if (fout->remoteVersion >= 80000)
4119         {
4120                 /*
4121                  * Left join to pick up dependency info linking sequences to their
4122                  * owning column, if any
4123                  */
4124                 appendPQExpBuffer(query,
4125                                                   "SELECT c.tableoid, c.oid, relname, "
4126                                                   "relacl, relkind, relnamespace, "
4127                                                   "(%s relowner) AS rolname, "
4128                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4129                                                   "relhasindex, relhasrules, relhasoids, "
4130                                                   "0 AS relfrozenxid, "
4131                                                   "0 AS toid, "
4132                                                   "0 AS tfrozenxid, "
4133                                                   "'p' AS relpersistence, "
4134                                                   "NULL AS reloftype, "
4135                                                   "d.refobjid AS owning_tab, "
4136                                                   "d.refobjsubid AS owning_col, "
4137                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4138                                                   "NULL AS reloptions, "
4139                                                   "NULL AS toast_reloptions "
4140                                                   "FROM pg_class c "
4141                                                   "LEFT JOIN pg_depend d ON "
4142                                                   "(c.relkind = '%c' AND "
4143                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4144                                                   "d.objsubid = 0 AND "
4145                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4146                                                   "WHERE relkind in ('%c', '%c', '%c', '%c') "
4147                                                   "ORDER BY c.oid",
4148                                                   username_subquery,
4149                                                   RELKIND_SEQUENCE,
4150                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4151                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4152         }
4153         else if (fout->remoteVersion >= 70300)
4154         {
4155                 /*
4156                  * Left join to pick up dependency info linking sequences to their
4157                  * owning column, if any
4158                  */
4159                 appendPQExpBuffer(query,
4160                                                   "SELECT c.tableoid, c.oid, relname, "
4161                                                   "relacl, relkind, relnamespace, "
4162                                                   "(%s relowner) AS rolname, "
4163                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4164                                                   "relhasindex, relhasrules, relhasoids, "
4165                                                   "0 AS relfrozenxid, "
4166                                                   "0 AS toid, "
4167                                                   "0 AS tfrozenxid, "
4168                                                   "'p' AS relpersistence, "
4169                                                   "NULL AS reloftype, "
4170                                                   "d.refobjid AS owning_tab, "
4171                                                   "d.refobjsubid AS owning_col, "
4172                                                   "NULL AS reltablespace, "
4173                                                   "NULL AS reloptions, "
4174                                                   "NULL AS toast_reloptions "
4175                                                   "FROM pg_class c "
4176                                                   "LEFT JOIN pg_depend d ON "
4177                                                   "(c.relkind = '%c' AND "
4178                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4179                                                   "d.objsubid = 0 AND "
4180                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4181                                                   "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4182                                                   "ORDER BY c.oid",
4183                                                   username_subquery,
4184                                                   RELKIND_SEQUENCE,
4185                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4186                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4187         }
4188         else if (fout->remoteVersion >= 70200)
4189         {
4190                 appendPQExpBuffer(query,
4191                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4192                                                   "0::oid AS relnamespace, "
4193                                                   "(%s relowner) AS rolname, "
4194                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4195                                                   "relhasindex, relhasrules, relhasoids, "
4196                                                   "0 AS relfrozenxid, "
4197                                                   "0 AS toid, "
4198                                                   "0 AS tfrozenxid, "
4199                                                   "'p' AS relpersistence, "
4200                                                   "NULL AS reloftype, "
4201                                                   "NULL::oid AS owning_tab, "
4202                                                   "NULL::int4 AS owning_col, "
4203                                                   "NULL AS reltablespace, "
4204                                                   "NULL AS reloptions, "
4205                                                   "NULL AS toast_reloptions "
4206                                                   "FROM pg_class "
4207                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4208                                                   "ORDER BY oid",
4209                                                   username_subquery,
4210                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4211         }
4212         else if (fout->remoteVersion >= 70100)
4213         {
4214                 /* all tables have oids in 7.1 */
4215                 appendPQExpBuffer(query,
4216                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4217                                                   "0::oid AS relnamespace, "
4218                                                   "(%s relowner) AS rolname, "
4219                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4220                                                   "relhasindex, relhasrules, "
4221                                                   "'t'::bool AS relhasoids, "
4222                                                   "0 AS relfrozenxid, "
4223                                                   "0 AS toid, "
4224                                                   "0 AS tfrozenxid, "
4225                                                   "'p' AS relpersistence, "
4226                                                   "NULL AS reloftype, "
4227                                                   "NULL::oid AS owning_tab, "
4228                                                   "NULL::int4 AS owning_col, "
4229                                                   "NULL AS reltablespace, "
4230                                                   "NULL AS reloptions, "
4231                                                   "NULL AS toast_reloptions "
4232                                                   "FROM pg_class "
4233                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4234                                                   "ORDER BY oid",
4235                                                   username_subquery,
4236                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4237         }
4238         else
4239         {
4240                 /*
4241                  * Before 7.1, view relkind was not set to 'v', so we must check if we
4242                  * have a view by looking for a rule in pg_rewrite.
4243                  */
4244                 appendPQExpBuffer(query,
4245                                                   "SELECT "
4246                 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4247                                                   "oid, relname, relacl, "
4248                                                   "CASE WHEN relhasrules and relkind = 'r' "
4249                                           "  and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4250                                           "             r.ev_class = c.oid AND r.ev_type = '1') "
4251                                                   "THEN '%c'::\"char\" "
4252                                                   "ELSE relkind END AS relkind,"
4253                                                   "0::oid AS relnamespace, "
4254                                                   "(%s relowner) AS rolname, "
4255                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4256                                                   "relhasindex, relhasrules, "
4257                                                   "'t'::bool AS relhasoids, "
4258                                                   "0 as relfrozenxid, "
4259                                                   "0 AS toid, "
4260                                                   "0 AS tfrozenxid, "
4261                                                   "'p' AS relpersistence, "
4262                                                   "NULL AS reloftype, "
4263                                                   "NULL::oid AS owning_tab, "
4264                                                   "NULL::int4 AS owning_col, "
4265                                                   "NULL AS reltablespace, "
4266                                                   "NULL AS reloptions, "
4267                                                   "NULL AS toast_reloptions "
4268                                                   "FROM pg_class c "
4269                                                   "WHERE relkind IN ('%c', '%c') "
4270                                                   "ORDER BY oid",
4271                                                   RELKIND_VIEW,
4272                                                   username_subquery,
4273                                                   RELKIND_RELATION, RELKIND_SEQUENCE);
4274         }
4275
4276         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4277
4278         ntups = PQntuples(res);
4279
4280         *numTables = ntups;
4281
4282         /*
4283          * Extract data from result and lock dumpable tables.  We do the locking
4284          * before anything else, to minimize the window wherein a table could
4285          * disappear under us.
4286          *
4287          * Note that we have to save info about all tables here, even when dumping
4288          * only one, because we don't yet know which tables might be inheritance
4289          * ancestors of the target table.
4290          */
4291         tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
4292
4293         i_reltableoid = PQfnumber(res, "tableoid");
4294         i_reloid = PQfnumber(res, "oid");
4295         i_relname = PQfnumber(res, "relname");
4296         i_relnamespace = PQfnumber(res, "relnamespace");
4297         i_relacl = PQfnumber(res, "relacl");
4298         i_relkind = PQfnumber(res, "relkind");
4299         i_rolname = PQfnumber(res, "rolname");
4300         i_relchecks = PQfnumber(res, "relchecks");
4301         i_relhastriggers = PQfnumber(res, "relhastriggers");
4302         i_relhasindex = PQfnumber(res, "relhasindex");
4303         i_relhasrules = PQfnumber(res, "relhasrules");
4304         i_relhasoids = PQfnumber(res, "relhasoids");
4305         i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4306         i_toastoid = PQfnumber(res, "toid");
4307         i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4308         i_relpersistence = PQfnumber(res, "relpersistence");
4309         i_owning_tab = PQfnumber(res, "owning_tab");
4310         i_owning_col = PQfnumber(res, "owning_col");
4311         i_reltablespace = PQfnumber(res, "reltablespace");
4312         i_reloptions = PQfnumber(res, "reloptions");
4313         i_toastreloptions = PQfnumber(res, "toast_reloptions");
4314         i_reloftype = PQfnumber(res, "reloftype");
4315
4316         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4317         {
4318                 /*
4319                  * Arrange to fail instead of waiting forever for a table lock.
4320                  *
4321                  * NB: this coding assumes that the only queries issued within the
4322                  * following loop are LOCK TABLEs; else the timeout may be undesirably
4323                  * applied to other things too.
4324                  */
4325                 resetPQExpBuffer(query);
4326                 appendPQExpBuffer(query, "SET statement_timeout = ");
4327                 appendStringLiteralConn(query, lockWaitTimeout, GetConnection(fout));
4328                 ExecuteSqlStatement(fout, query->data);
4329         }
4330
4331         for (i = 0; i < ntups; i++)
4332         {
4333                 tblinfo[i].dobj.objType = DO_TABLE;
4334                 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4335                 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4336                 AssignDumpId(&tblinfo[i].dobj);
4337                 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4338                 tblinfo[i].dobj.namespace =
4339                         findNamespace(fout,
4340                                                   atooid(PQgetvalue(res, i, i_relnamespace)),
4341                                                   tblinfo[i].dobj.catId.oid);
4342                 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4343                 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4344                 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4345                 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4346                 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4347                 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4348                 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4349                 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4350                 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4351                 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4352                 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4353                 if (PQgetisnull(res, i, i_reloftype))
4354                         tblinfo[i].reloftype = NULL;
4355                 else
4356                         tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4357                 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4358                 if (PQgetisnull(res, i, i_owning_tab))
4359                 {
4360                         tblinfo[i].owning_tab = InvalidOid;
4361                         tblinfo[i].owning_col = 0;
4362                 }
4363                 else
4364                 {
4365                         tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4366                         tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4367                 }
4368                 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4369                 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4370                 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4371
4372                 /* other fields were zeroed above */
4373
4374                 /*
4375                  * Decide whether we want to dump this table.
4376                  */
4377                 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4378                         tblinfo[i].dobj.dump = false;
4379                 else
4380                         selectDumpableTable(&tblinfo[i]);
4381                 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4382
4383                 /*
4384                  * Read-lock target tables to make sure they aren't DROPPED or altered
4385                  * in schema before we get around to dumping them.
4386                  *
4387                  * Note that we don't explicitly lock parents of the target tables; we
4388                  * assume our lock on the child is enough to prevent schema
4389                  * alterations to parent tables.
4390                  *
4391                  * NOTE: it'd be kinda nice to lock other relations too, not only
4392                  * plain tables, but the backend doesn't presently allow that.
4393                  */
4394                 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4395                 {
4396                         resetPQExpBuffer(query);
4397                         appendPQExpBuffer(query,
4398                                                           "LOCK TABLE %s IN ACCESS SHARE MODE",
4399                                                           fmtQualifiedId(fout,
4400                                                                                 tblinfo[i].dobj.namespace->dobj.name,
4401                                                                                          tblinfo[i].dobj.name));
4402                         ExecuteSqlStatement(fout, query->data);
4403                 }
4404
4405                 /* Emit notice if join for owner failed */
4406                 if (strlen(tblinfo[i].rolname) == 0)
4407                         write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4408                                           tblinfo[i].dobj.name);
4409         }
4410
4411         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4412         {
4413                 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4414         }
4415
4416         PQclear(res);
4417
4418         destroyPQExpBuffer(query);
4419
4420         return tblinfo;
4421 }
4422
4423 /*
4424  * getOwnedSeqs
4425  *        identify owned sequences and mark them as dumpable if owning table is
4426  *
4427  * We used to do this in getTables(), but it's better to do it after the
4428  * index used by findTableByOid() has been set up.
4429  */
4430 void
4431 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
4432 {
4433         int                     i;
4434
4435         /*
4436          * Force sequences that are "owned" by table columns to be dumped whenever
4437          * their owning table is being dumped.
4438          */
4439         for (i = 0; i < numTables; i++)
4440         {
4441                 TableInfo  *seqinfo = &tblinfo[i];
4442                 TableInfo  *owning_tab;
4443
4444                 if (!OidIsValid(seqinfo->owning_tab))
4445                         continue;                       /* not an owned sequence */
4446                 if (seqinfo->dobj.dump)
4447                         continue;                       /* no need to search */
4448                 owning_tab = findTableByOid(seqinfo->owning_tab);
4449                 if (owning_tab && owning_tab->dobj.dump)
4450                 {
4451                         seqinfo->interesting = true;
4452                         seqinfo->dobj.dump = true;
4453                 }
4454         }
4455 }
4456
4457 /*
4458  * getInherits
4459  *        read all the inheritance information
4460  * from the system catalogs return them in the InhInfo* structure
4461  *
4462  * numInherits is set to the number of pairs read in
4463  */
4464 InhInfo *
4465 getInherits(Archive *fout, int *numInherits)
4466 {
4467         PGresult   *res;
4468         int                     ntups;
4469         int                     i;
4470         PQExpBuffer query = createPQExpBuffer();
4471         InhInfo    *inhinfo;
4472
4473         int                     i_inhrelid;
4474         int                     i_inhparent;
4475
4476         /* Make sure we are in proper schema */
4477         selectSourceSchema(fout, "pg_catalog");
4478
4479         /* find all the inheritance information */
4480
4481         appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4482
4483         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4484
4485         ntups = PQntuples(res);
4486
4487         *numInherits = ntups;
4488
4489         inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4490
4491         i_inhrelid = PQfnumber(res, "inhrelid");
4492         i_inhparent = PQfnumber(res, "inhparent");
4493
4494         for (i = 0; i < ntups; i++)
4495         {
4496                 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4497                 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4498         }
4499
4500         PQclear(res);
4501
4502         destroyPQExpBuffer(query);
4503
4504         return inhinfo;
4505 }
4506
4507 /*
4508  * getIndexes
4509  *        get information about every index on a dumpable table
4510  *
4511  * Note: index data is not returned directly to the caller, but it
4512  * does get entered into the DumpableObject tables.
4513  */
4514 void
4515 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4516 {
4517         int                     i,
4518                                 j;
4519         PQExpBuffer query = createPQExpBuffer();
4520         PGresult   *res;
4521         IndxInfo   *indxinfo;
4522         ConstraintInfo *constrinfo;
4523         int                     i_tableoid,
4524                                 i_oid,
4525                                 i_indexname,
4526                                 i_indexdef,
4527                                 i_indnkeys,
4528                                 i_indkey,
4529                                 i_indisclustered,
4530                                 i_contype,
4531                                 i_conname,
4532                                 i_condeferrable,
4533                                 i_condeferred,
4534                                 i_contableoid,
4535                                 i_conoid,
4536                                 i_condef,
4537                                 i_tablespace,
4538                                 i_options;
4539         int                     ntups;
4540
4541         for (i = 0; i < numTables; i++)
4542         {
4543                 TableInfo  *tbinfo = &tblinfo[i];
4544
4545                 /* Only plain tables have indexes */
4546                 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
4547                         continue;
4548
4549                 /* Ignore indexes of tables not to be dumped */
4550                 if (!tbinfo->dobj.dump)
4551                         continue;
4552
4553                 if (g_verbose)
4554                         write_msg(NULL, "reading indexes for table \"%s\"\n",
4555                                           tbinfo->dobj.name);
4556
4557                 /* Make sure we are in proper schema so indexdef is right */
4558                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4559
4560                 /*
4561                  * The point of the messy-looking outer join is to find a constraint
4562                  * that is related by an internal dependency link to the index. If we
4563                  * find one, create a CONSTRAINT entry linked to the INDEX entry.  We
4564                  * assume an index won't have more than one internal dependency.
4565                  *
4566                  * As of 9.0 we don't need to look at pg_depend but can check for a
4567                  * match to pg_constraint.conindid.  The check on conrelid is
4568                  * redundant but useful because that column is indexed while conindid
4569                  * is not.
4570                  */
4571                 resetPQExpBuffer(query);
4572                 if (fout->remoteVersion >= 90000)
4573                 {
4574                         appendPQExpBuffer(query,
4575                                                           "SELECT t.tableoid, t.oid, "
4576                                                           "t.relname AS indexname, "
4577                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4578                                                           "t.relnatts AS indnkeys, "
4579                                                           "i.indkey, i.indisclustered, "
4580                                                           "c.contype, c.conname, "
4581                                                           "c.condeferrable, c.condeferred, "
4582                                                           "c.tableoid AS contableoid, "
4583                                                           "c.oid AS conoid, "
4584                                   "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4585                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4586                                                         "array_to_string(t.reloptions, ', ') AS options "
4587                                                           "FROM pg_catalog.pg_index i "
4588                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4589                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4590                                                           "ON (i.indrelid = c.conrelid AND "
4591                                                           "i.indexrelid = c.conindid AND "
4592                                                           "c.contype IN ('p','u','x')) "
4593                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4594                                                           "ORDER BY indexname",
4595                                                           tbinfo->dobj.catId.oid);
4596                 }
4597                 else if (fout->remoteVersion >= 80200)
4598                 {
4599                         appendPQExpBuffer(query,
4600                                                           "SELECT t.tableoid, t.oid, "
4601                                                           "t.relname AS indexname, "
4602                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4603                                                           "t.relnatts AS indnkeys, "
4604                                                           "i.indkey, i.indisclustered, "
4605                                                           "c.contype, c.conname, "
4606                                                           "c.condeferrable, c.condeferred, "
4607                                                           "c.tableoid AS contableoid, "
4608                                                           "c.oid AS conoid, "
4609                                                           "null AS condef, "
4610                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4611                                                         "array_to_string(t.reloptions, ', ') AS options "
4612                                                           "FROM pg_catalog.pg_index i "
4613                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4614                                                           "LEFT JOIN pg_catalog.pg_depend d "
4615                                                           "ON (d.classid = t.tableoid "
4616                                                           "AND d.objid = t.oid "
4617                                                           "AND d.deptype = 'i') "
4618                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4619                                                           "ON (d.refclassid = c.tableoid "
4620                                                           "AND d.refobjid = c.oid) "
4621                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4622                                                           "ORDER BY indexname",
4623                                                           tbinfo->dobj.catId.oid);
4624                 }
4625                 else if (fout->remoteVersion >= 80000)
4626                 {
4627                         appendPQExpBuffer(query,
4628                                                           "SELECT t.tableoid, t.oid, "
4629                                                           "t.relname AS indexname, "
4630                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4631                                                           "t.relnatts AS indnkeys, "
4632                                                           "i.indkey, i.indisclustered, "
4633                                                           "c.contype, c.conname, "
4634                                                           "c.condeferrable, c.condeferred, "
4635                                                           "c.tableoid AS contableoid, "
4636                                                           "c.oid AS conoid, "
4637                                                           "null AS condef, "
4638                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4639                                                           "null AS options "
4640                                                           "FROM pg_catalog.pg_index i "
4641                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4642                                                           "LEFT JOIN pg_catalog.pg_depend d "
4643                                                           "ON (d.classid = t.tableoid "
4644                                                           "AND d.objid = t.oid "
4645                                                           "AND d.deptype = 'i') "
4646                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4647                                                           "ON (d.refclassid = c.tableoid "
4648                                                           "AND d.refobjid = c.oid) "
4649                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4650                                                           "ORDER BY indexname",
4651                                                           tbinfo->dobj.catId.oid);
4652                 }
4653                 else if (fout->remoteVersion >= 70300)
4654                 {
4655                         appendPQExpBuffer(query,
4656                                                           "SELECT t.tableoid, t.oid, "
4657                                                           "t.relname AS indexname, "
4658                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4659                                                           "t.relnatts AS indnkeys, "
4660                                                           "i.indkey, i.indisclustered, "
4661                                                           "c.contype, c.conname, "
4662                                                           "c.condeferrable, c.condeferred, "
4663                                                           "c.tableoid AS contableoid, "
4664                                                           "c.oid AS conoid, "
4665                                                           "null AS condef, "
4666                                                           "NULL AS tablespace, "
4667                                                           "null AS options "
4668                                                           "FROM pg_catalog.pg_index i "
4669                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4670                                                           "LEFT JOIN pg_catalog.pg_depend d "
4671                                                           "ON (d.classid = t.tableoid "
4672                                                           "AND d.objid = t.oid "
4673                                                           "AND d.deptype = 'i') "
4674                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4675                                                           "ON (d.refclassid = c.tableoid "
4676                                                           "AND d.refobjid = c.oid) "
4677                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4678                                                           "ORDER BY indexname",
4679                                                           tbinfo->dobj.catId.oid);
4680                 }
4681                 else if (fout->remoteVersion >= 70100)
4682                 {
4683                         appendPQExpBuffer(query,
4684                                                           "SELECT t.tableoid, t.oid, "
4685                                                           "t.relname AS indexname, "
4686                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
4687                                                           "t.relnatts AS indnkeys, "
4688                                                           "i.indkey, false AS indisclustered, "
4689                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
4690                                                           "ELSE '0'::char END AS contype, "
4691                                                           "t.relname AS conname, "
4692                                                           "false AS condeferrable, "
4693                                                           "false AS condeferred, "
4694                                                           "0::oid AS contableoid, "
4695                                                           "t.oid AS conoid, "
4696                                                           "null AS condef, "
4697                                                           "NULL AS tablespace, "
4698                                                           "null AS options "
4699                                                           "FROM pg_index i, pg_class t "
4700                                                           "WHERE t.oid = i.indexrelid "
4701                                                           "AND i.indrelid = '%u'::oid "
4702                                                           "ORDER BY indexname",
4703                                                           tbinfo->dobj.catId.oid);
4704                 }
4705                 else
4706                 {
4707                         appendPQExpBuffer(query,
4708                                                           "SELECT "
4709                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4710                                                           "t.oid, "
4711                                                           "t.relname AS indexname, "
4712                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
4713                                                           "t.relnatts AS indnkeys, "
4714                                                           "i.indkey, false AS indisclustered, "
4715                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
4716                                                           "ELSE '0'::char END AS contype, "
4717                                                           "t.relname AS conname, "
4718                                                           "false AS condeferrable, "
4719                                                           "false AS condeferred, "
4720                                                           "0::oid AS contableoid, "
4721                                                           "t.oid AS conoid, "
4722                                                           "null AS condef, "
4723                                                           "NULL AS tablespace, "
4724                                                           "null AS options "
4725                                                           "FROM pg_index i, pg_class t "
4726                                                           "WHERE t.oid = i.indexrelid "
4727                                                           "AND i.indrelid = '%u'::oid "
4728                                                           "ORDER BY indexname",
4729                                                           tbinfo->dobj.catId.oid);
4730                 }
4731
4732                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4733
4734                 ntups = PQntuples(res);
4735
4736                 i_tableoid = PQfnumber(res, "tableoid");
4737                 i_oid = PQfnumber(res, "oid");
4738                 i_indexname = PQfnumber(res, "indexname");
4739                 i_indexdef = PQfnumber(res, "indexdef");
4740                 i_indnkeys = PQfnumber(res, "indnkeys");
4741                 i_indkey = PQfnumber(res, "indkey");
4742                 i_indisclustered = PQfnumber(res, "indisclustered");
4743                 i_contype = PQfnumber(res, "contype");
4744                 i_conname = PQfnumber(res, "conname");
4745                 i_condeferrable = PQfnumber(res, "condeferrable");
4746                 i_condeferred = PQfnumber(res, "condeferred");
4747                 i_contableoid = PQfnumber(res, "contableoid");
4748                 i_conoid = PQfnumber(res, "conoid");
4749                 i_condef = PQfnumber(res, "condef");
4750                 i_tablespace = PQfnumber(res, "tablespace");
4751                 i_options = PQfnumber(res, "options");
4752
4753                 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
4754                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4755
4756                 for (j = 0; j < ntups; j++)
4757                 {
4758                         char            contype;
4759
4760                         indxinfo[j].dobj.objType = DO_INDEX;
4761                         indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4762                         indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4763                         AssignDumpId(&indxinfo[j].dobj);
4764                         indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
4765                         indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4766                         indxinfo[j].indextable = tbinfo;
4767                         indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
4768                         indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4769                         indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
4770                         indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
4771
4772                         /*
4773                          * In pre-7.4 releases, indkeys may contain more entries than
4774                          * indnkeys says (since indnkeys will be 1 for a functional
4775                          * index).      We don't actually care about this case since we don't
4776                          * examine indkeys except for indexes associated with PRIMARY and
4777                          * UNIQUE constraints, which are never functional indexes. But we
4778                          * have to allocate enough space to keep parseOidArray from
4779                          * complaining.
4780                          */
4781                         indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
4782                         parseOidArray(PQgetvalue(res, j, i_indkey),
4783                                                   indxinfo[j].indkeys, INDEX_MAX_KEYS);
4784                         indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4785                         contype = *(PQgetvalue(res, j, i_contype));
4786
4787                         if (contype == 'p' || contype == 'u' || contype == 'x')
4788                         {
4789                                 /*
4790                                  * If we found a constraint matching the index, create an
4791                                  * entry for it.
4792                                  *
4793                                  * In a pre-7.3 database, we take this path iff the index was
4794                                  * marked indisprimary.
4795                                  */
4796                                 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4797                                 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4798                                 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4799                                 AssignDumpId(&constrinfo[j].dobj);
4800                                 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4801                                 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4802                                 constrinfo[j].contable = tbinfo;
4803                                 constrinfo[j].condomain = NULL;
4804                                 constrinfo[j].contype = contype;
4805                                 if (contype == 'x')
4806                                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4807                                 else
4808                                         constrinfo[j].condef = NULL;
4809                                 constrinfo[j].confrelid = InvalidOid;
4810                                 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4811                                 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4812                                 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4813                                 constrinfo[j].conislocal = true;
4814                                 constrinfo[j].separate = true;
4815
4816                                 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4817
4818                                 /* If pre-7.3 DB, better make sure table comes first */
4819                                 addObjectDependency(&constrinfo[j].dobj,
4820                                                                         tbinfo->dobj.dumpId);
4821                         }
4822                         else
4823                         {
4824                                 /* Plain secondary index */
4825                                 indxinfo[j].indexconstraint = 0;
4826                         }
4827                 }
4828
4829                 PQclear(res);
4830         }
4831
4832         destroyPQExpBuffer(query);
4833 }
4834
4835 /*
4836  * getConstraints
4837  *
4838  * Get info about constraints on dumpable tables.
4839  *
4840  * Currently handles foreign keys only.
4841  * Unique and primary key constraints are handled with indexes,
4842  * while check constraints are processed in getTableAttrs().
4843  */
4844 void
4845 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
4846 {
4847         int                     i,
4848                                 j;
4849         ConstraintInfo *constrinfo;
4850         PQExpBuffer query;
4851         PGresult   *res;
4852         int                     i_contableoid,
4853                                 i_conoid,
4854                                 i_conname,
4855                                 i_confrelid,
4856                                 i_condef;
4857         int                     ntups;
4858
4859         /* pg_constraint was created in 7.3, so nothing to do if older */
4860         if (fout->remoteVersion < 70300)
4861                 return;
4862
4863         query = createPQExpBuffer();
4864
4865         for (i = 0; i < numTables; i++)
4866         {
4867                 TableInfo  *tbinfo = &tblinfo[i];
4868
4869                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4870                         continue;
4871
4872                 if (g_verbose)
4873                         write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
4874                                           tbinfo->dobj.name);
4875
4876                 /*
4877                  * select table schema to ensure constraint expr is qualified if
4878                  * needed
4879                  */
4880                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4881
4882                 resetPQExpBuffer(query);
4883                 appendPQExpBuffer(query,
4884                                                   "SELECT tableoid, oid, conname, confrelid, "
4885                                                   "pg_catalog.pg_get_constraintdef(oid) AS condef "
4886                                                   "FROM pg_catalog.pg_constraint "
4887                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
4888                                                   "AND contype = 'f'",
4889                                                   tbinfo->dobj.catId.oid);
4890                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4891
4892                 ntups = PQntuples(res);
4893
4894                 i_contableoid = PQfnumber(res, "tableoid");
4895                 i_conoid = PQfnumber(res, "oid");
4896                 i_conname = PQfnumber(res, "conname");
4897                 i_confrelid = PQfnumber(res, "confrelid");
4898                 i_condef = PQfnumber(res, "condef");
4899
4900                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4901
4902                 for (j = 0; j < ntups; j++)
4903                 {
4904                         constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
4905                         constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4906                         constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4907                         AssignDumpId(&constrinfo[j].dobj);
4908                         constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4909                         constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4910                         constrinfo[j].contable = tbinfo;
4911                         constrinfo[j].condomain = NULL;
4912                         constrinfo[j].contype = 'f';
4913                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4914                         constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
4915                         constrinfo[j].conindex = 0;
4916                         constrinfo[j].condeferrable = false;
4917                         constrinfo[j].condeferred = false;
4918                         constrinfo[j].conislocal = true;
4919                         constrinfo[j].separate = true;
4920                 }
4921
4922                 PQclear(res);
4923         }
4924
4925         destroyPQExpBuffer(query);
4926 }
4927
4928 /*
4929  * getDomainConstraints
4930  *
4931  * Get info about constraints on a domain.
4932  */
4933 static void
4934 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
4935 {
4936         int                     i;
4937         ConstraintInfo *constrinfo;
4938         PQExpBuffer query;
4939         PGresult   *res;
4940         int                     i_tableoid,
4941                                 i_oid,
4942                                 i_conname,
4943                                 i_consrc;
4944         int                     ntups;
4945
4946         /* pg_constraint was created in 7.3, so nothing to do if older */
4947         if (fout->remoteVersion < 70300)
4948                 return;
4949
4950         /*
4951          * select appropriate schema to ensure names in constraint are properly
4952          * qualified
4953          */
4954         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
4955
4956         query = createPQExpBuffer();
4957
4958         if (fout->remoteVersion >= 90100)
4959                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4960                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4961                                                   "convalidated "
4962                                                   "FROM pg_catalog.pg_constraint "
4963                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4964                                                   "ORDER BY conname",
4965                                                   tyinfo->dobj.catId.oid);
4966
4967         else if (fout->remoteVersion >= 70400)
4968                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4969                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4970                                                   "true as convalidated "
4971                                                   "FROM pg_catalog.pg_constraint "
4972                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4973                                                   "ORDER BY conname",
4974                                                   tyinfo->dobj.catId.oid);
4975         else
4976                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4977                                                   "'CHECK (' || consrc || ')' AS consrc, "
4978                                                   "true as convalidated "
4979                                                   "FROM pg_catalog.pg_constraint "
4980                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4981                                                   "ORDER BY conname",
4982                                                   tyinfo->dobj.catId.oid);
4983
4984         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4985
4986         ntups = PQntuples(res);
4987
4988         i_tableoid = PQfnumber(res, "tableoid");
4989         i_oid = PQfnumber(res, "oid");
4990         i_conname = PQfnumber(res, "conname");
4991         i_consrc = PQfnumber(res, "consrc");
4992
4993         constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4994
4995         tyinfo->nDomChecks = ntups;
4996         tyinfo->domChecks = constrinfo;
4997
4998         for (i = 0; i < ntups; i++)
4999         {
5000                 bool            validated = PQgetvalue(res, i, 4)[0] == 't';
5001
5002                 constrinfo[i].dobj.objType = DO_CONSTRAINT;
5003                 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5004                 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5005                 AssignDumpId(&constrinfo[i].dobj);
5006                 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5007                 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
5008                 constrinfo[i].contable = NULL;
5009                 constrinfo[i].condomain = tyinfo;
5010                 constrinfo[i].contype = 'c';
5011                 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
5012                 constrinfo[i].confrelid = InvalidOid;
5013                 constrinfo[i].conindex = 0;
5014                 constrinfo[i].condeferrable = false;
5015                 constrinfo[i].condeferred = false;
5016                 constrinfo[i].conislocal = true;
5017
5018                 constrinfo[i].separate = !validated;
5019
5020                 /*
5021                  * Make the domain depend on the constraint, ensuring it won't be
5022                  * output till any constraint dependencies are OK.      If the constraint
5023                  * has not been validated, it's going to be dumped after the domain
5024                  * anyway, so this doesn't matter.
5025                  */
5026                 if (validated)
5027                         addObjectDependency(&tyinfo->dobj,
5028                                                                 constrinfo[i].dobj.dumpId);
5029         }
5030
5031         PQclear(res);
5032
5033         destroyPQExpBuffer(query);
5034 }
5035
5036 /*
5037  * getRules
5038  *        get basic information about every rule in the system
5039  *
5040  * numRules is set to the number of rules read in
5041  */
5042 RuleInfo *
5043 getRules(Archive *fout, int *numRules)
5044 {
5045         PGresult   *res;
5046         int                     ntups;
5047         int                     i;
5048         PQExpBuffer query = createPQExpBuffer();
5049         RuleInfo   *ruleinfo;
5050         int                     i_tableoid;
5051         int                     i_oid;
5052         int                     i_rulename;
5053         int                     i_ruletable;
5054         int                     i_ev_type;
5055         int                     i_is_instead;
5056         int                     i_ev_enabled;
5057
5058         /* Make sure we are in proper schema */
5059         selectSourceSchema(fout, "pg_catalog");
5060
5061         if (fout->remoteVersion >= 80300)
5062         {
5063                 appendPQExpBuffer(query, "SELECT "
5064                                                   "tableoid, oid, rulename, "
5065                                                   "ev_class AS ruletable, ev_type, is_instead, "
5066                                                   "ev_enabled "
5067                                                   "FROM pg_rewrite "
5068                                                   "ORDER BY oid");
5069         }
5070         else if (fout->remoteVersion >= 70100)
5071         {
5072                 appendPQExpBuffer(query, "SELECT "
5073                                                   "tableoid, oid, rulename, "
5074                                                   "ev_class AS ruletable, ev_type, is_instead, "
5075                                                   "'O'::char AS ev_enabled "
5076                                                   "FROM pg_rewrite "
5077                                                   "ORDER BY oid");
5078         }
5079         else
5080         {
5081                 appendPQExpBuffer(query, "SELECT "
5082                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
5083                                                   "oid, rulename, "
5084                                                   "ev_class AS ruletable, ev_type, is_instead, "
5085                                                   "'O'::char AS ev_enabled "
5086                                                   "FROM pg_rewrite "
5087                                                   "ORDER BY oid");
5088         }
5089
5090         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5091
5092         ntups = PQntuples(res);
5093
5094         *numRules = ntups;
5095
5096         ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
5097
5098         i_tableoid = PQfnumber(res, "tableoid");
5099         i_oid = PQfnumber(res, "oid");
5100         i_rulename = PQfnumber(res, "rulename");
5101         i_ruletable = PQfnumber(res, "ruletable");
5102         i_ev_type = PQfnumber(res, "ev_type");
5103         i_is_instead = PQfnumber(res, "is_instead");
5104         i_ev_enabled = PQfnumber(res, "ev_enabled");
5105
5106         for (i = 0; i < ntups; i++)
5107         {
5108                 Oid                     ruletableoid;
5109
5110                 ruleinfo[i].dobj.objType = DO_RULE;
5111                 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5112                 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5113                 AssignDumpId(&ruleinfo[i].dobj);
5114                 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5115                 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5116                 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5117                 if (ruleinfo[i].ruletable == NULL)
5118                         exit_horribly(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5119                                                   ruletableoid, ruleinfo[i].dobj.catId.oid);
5120                 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5121                 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5122                 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5123                 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5124                 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5125                 if (ruleinfo[i].ruletable)
5126                 {
5127                         /*
5128                          * If the table is a view, force its ON SELECT rule to be sorted
5129                          * before the view itself --- this ensures that any dependencies
5130                          * for the rule affect the table's positioning. Other rules are
5131                          * forced to appear after their table.
5132                          */
5133                         if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
5134                                 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5135                         {
5136                                 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5137                                                                         ruleinfo[i].dobj.dumpId);
5138                                 /* We'll merge the rule into CREATE VIEW, if possible */
5139                                 ruleinfo[i].separate = false;
5140                         }
5141                         else
5142                         {
5143                                 addObjectDependency(&ruleinfo[i].dobj,
5144                                                                         ruleinfo[i].ruletable->dobj.dumpId);
5145                                 ruleinfo[i].separate = true;
5146                         }
5147                 }
5148                 else
5149                         ruleinfo[i].separate = true;
5150
5151                 /*
5152                  * If we're forced to break a dependency loop by dumping a view as a
5153                  * table and separate _RETURN rule, we'll move the view's reloptions
5154                  * to the rule.  (This is necessary because tables and views have
5155                  * different valid reloptions, so we can't apply the options until the
5156                  * backend knows it's a view.)  Otherwise the rule's reloptions stay
5157                  * NULL.
5158                  */
5159                 ruleinfo[i].reloptions = NULL;
5160         }
5161
5162         PQclear(res);
5163
5164         destroyPQExpBuffer(query);
5165
5166         return ruleinfo;
5167 }
5168
5169 /*
5170  * getTriggers
5171  *        get information about every trigger on a dumpable table
5172  *
5173  * Note: trigger data is not returned directly to the caller, but it
5174  * does get entered into the DumpableObject tables.
5175  */
5176 void
5177 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5178 {
5179         int                     i,
5180                                 j;
5181         PQExpBuffer query = createPQExpBuffer();
5182         PGresult   *res;
5183         TriggerInfo *tginfo;
5184         int                     i_tableoid,
5185                                 i_oid,
5186                                 i_tgname,
5187                                 i_tgfname,
5188                                 i_tgtype,
5189                                 i_tgnargs,
5190                                 i_tgargs,
5191                                 i_tgisconstraint,
5192                                 i_tgconstrname,
5193                                 i_tgconstrrelid,
5194                                 i_tgconstrrelname,
5195                                 i_tgenabled,
5196                                 i_tgdeferrable,
5197                                 i_tginitdeferred,
5198                                 i_tgdef;
5199         int                     ntups;
5200
5201         for (i = 0; i < numTables; i++)
5202         {
5203                 TableInfo  *tbinfo = &tblinfo[i];
5204
5205                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5206                         continue;
5207
5208                 if (g_verbose)
5209                         write_msg(NULL, "reading triggers for table \"%s\"\n",
5210                                           tbinfo->dobj.name);
5211
5212                 /*
5213                  * select table schema to ensure regproc name is qualified if needed
5214                  */
5215                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5216
5217                 resetPQExpBuffer(query);
5218                 if (fout->remoteVersion >= 90000)
5219                 {
5220                         /*
5221                          * NB: think not to use pretty=true in pg_get_triggerdef.  It
5222                          * could result in non-forward-compatible dumps of WHEN clauses
5223                          * due to under-parenthesization.
5224                          */
5225                         appendPQExpBuffer(query,
5226                                                           "SELECT tgname, "
5227                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5228                                                 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5229                                                           "tgenabled, tableoid, oid "
5230                                                           "FROM pg_catalog.pg_trigger t "
5231                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5232                                                           "AND NOT tgisinternal",
5233                                                           tbinfo->dobj.catId.oid);
5234                 }
5235                 else if (fout->remoteVersion >= 80300)
5236                 {
5237                         /*
5238                          * We ignore triggers that are tied to a foreign-key constraint
5239                          */
5240                         appendPQExpBuffer(query,
5241                                                           "SELECT tgname, "
5242                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5243                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5244                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5245                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5246                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5247                                                           "FROM pg_catalog.pg_trigger t "
5248                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5249                                                           "AND tgconstraint = 0",
5250                                                           tbinfo->dobj.catId.oid);
5251                 }
5252                 else if (fout->remoteVersion >= 70300)
5253                 {
5254                         /*
5255                          * We ignore triggers that are tied to a foreign-key constraint,
5256                          * but in these versions we have to grovel through pg_constraint
5257                          * to find out
5258                          */
5259                         appendPQExpBuffer(query,
5260                                                           "SELECT tgname, "
5261                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5262                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5263                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5264                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5265                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5266                                                           "FROM pg_catalog.pg_trigger t "
5267                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5268                                                           "AND (NOT tgisconstraint "
5269                                                           " OR NOT EXISTS"
5270                                                           "  (SELECT 1 FROM pg_catalog.pg_depend d "
5271                                                           "   JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5272                                                           "   WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5273                                                           tbinfo->dobj.catId.oid);
5274                 }
5275                 else if (fout->remoteVersion >= 70100)
5276                 {
5277                         appendPQExpBuffer(query,
5278                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5279                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5280                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5281                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5282                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5283                                                           "             AS tgconstrrelname "
5284                                                           "FROM pg_trigger "
5285                                                           "WHERE tgrelid = '%u'::oid",
5286                                                           tbinfo->dobj.catId.oid);
5287                 }
5288                 else
5289                 {
5290                         appendPQExpBuffer(query,
5291                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5292                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5293                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5294                                                           "tgconstrrelid, tginitdeferred, "
5295                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5296                                                           "oid, "
5297                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5298                                                           "             AS tgconstrrelname "
5299                                                           "FROM pg_trigger "
5300                                                           "WHERE tgrelid = '%u'::oid",
5301                                                           tbinfo->dobj.catId.oid);
5302                 }
5303                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5304
5305                 ntups = PQntuples(res);
5306
5307                 i_tableoid = PQfnumber(res, "tableoid");
5308                 i_oid = PQfnumber(res, "oid");
5309                 i_tgname = PQfnumber(res, "tgname");
5310                 i_tgfname = PQfnumber(res, "tgfname");
5311                 i_tgtype = PQfnumber(res, "tgtype");
5312                 i_tgnargs = PQfnumber(res, "tgnargs");
5313                 i_tgargs = PQfnumber(res, "tgargs");
5314                 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5315                 i_tgconstrname = PQfnumber(res, "tgconstrname");
5316                 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5317                 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5318                 i_tgenabled = PQfnumber(res, "tgenabled");
5319                 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5320                 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5321                 i_tgdef = PQfnumber(res, "tgdef");
5322
5323                 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5324
5325                 for (j = 0; j < ntups; j++)
5326                 {
5327                         tginfo[j].dobj.objType = DO_TRIGGER;
5328                         tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5329                         tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5330                         AssignDumpId(&tginfo[j].dobj);
5331                         tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5332                         tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5333                         tginfo[j].tgtable = tbinfo;
5334                         tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5335                         if (i_tgdef >= 0)
5336                         {
5337                                 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5338
5339                                 /* remaining fields are not valid if we have tgdef */
5340                                 tginfo[j].tgfname = NULL;
5341                                 tginfo[j].tgtype = 0;
5342                                 tginfo[j].tgnargs = 0;
5343                                 tginfo[j].tgargs = NULL;
5344                                 tginfo[j].tgisconstraint = false;
5345                                 tginfo[j].tgdeferrable = false;
5346                                 tginfo[j].tginitdeferred = false;
5347                                 tginfo[j].tgconstrname = NULL;
5348                                 tginfo[j].tgconstrrelid = InvalidOid;
5349                                 tginfo[j].tgconstrrelname = NULL;
5350                         }
5351                         else
5352                         {
5353                                 tginfo[j].tgdef = NULL;
5354
5355                                 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5356                                 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5357                                 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5358                                 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5359                                 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5360                                 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5361                                 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5362
5363                                 if (tginfo[j].tgisconstraint)
5364                                 {
5365                                         tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5366                                         tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5367                                         if (OidIsValid(tginfo[j].tgconstrrelid))
5368                                         {
5369                                                 if (PQgetisnull(res, j, i_tgconstrrelname))
5370                                                         exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5371                                                                                   tginfo[j].dobj.name,
5372                                                                                   tbinfo->dobj.name,
5373                                                                                   tginfo[j].tgconstrrelid);
5374                                                 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5375                                         }
5376                                         else
5377                                                 tginfo[j].tgconstrrelname = NULL;
5378                                 }
5379                                 else
5380                                 {
5381                                         tginfo[j].tgconstrname = NULL;
5382                                         tginfo[j].tgconstrrelid = InvalidOid;
5383                                         tginfo[j].tgconstrrelname = NULL;
5384                                 }
5385                         }
5386                 }
5387
5388                 PQclear(res);
5389         }
5390
5391         destroyPQExpBuffer(query);
5392 }
5393
5394 /*
5395  * getEventTriggers
5396  *        get information about event triggers
5397  */
5398 EventTriggerInfo *
5399 getEventTriggers(Archive *fout, int *numEventTriggers)
5400 {
5401         int                     i;
5402         PQExpBuffer query = createPQExpBuffer();
5403         PGresult   *res;
5404         EventTriggerInfo *evtinfo;
5405         int                     i_tableoid,
5406                                 i_oid,
5407                                 i_evtname,
5408                                 i_evtevent,
5409                                 i_evtowner,
5410                                 i_evttags,
5411                                 i_evtfname,
5412                                 i_evtenabled;
5413         int                     ntups;
5414
5415         /* Before 9.3, there are no event triggers */
5416         if (fout->remoteVersion < 90300)
5417         {
5418                 *numEventTriggers = 0;
5419                 return NULL;
5420         }
5421
5422         /* Make sure we are in proper schema */
5423         selectSourceSchema(fout, "pg_catalog");
5424
5425         appendPQExpBuffer(query,
5426                                           "SELECT e.tableoid, e.oid, evtname, evtenabled, "
5427                                           "evtevent, (%s evtowner) AS evtowner, "
5428                                           "array_to_string(array("
5429                                           "select quote_literal(x) "
5430                                           " from unnest(evttags) as t(x)), ', ') as evttags, "
5431                                           "e.evtfoid::regproc as evtfname "
5432                                           "FROM pg_event_trigger e "
5433                                           "ORDER BY e.oid",
5434                                           username_subquery);
5435
5436         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5437
5438         ntups = PQntuples(res);
5439
5440         *numEventTriggers = ntups;
5441
5442         evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
5443
5444         i_tableoid = PQfnumber(res, "tableoid");
5445         i_oid = PQfnumber(res, "oid");
5446         i_evtname = PQfnumber(res, "evtname");
5447         i_evtevent = PQfnumber(res, "evtevent");
5448         i_evtowner = PQfnumber(res, "evtowner");
5449         i_evttags = PQfnumber(res, "evttags");
5450         i_evtfname = PQfnumber(res, "evtfname");
5451         i_evtenabled = PQfnumber(res, "evtenabled");
5452
5453         for (i = 0; i < ntups; i++)
5454         {
5455                 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
5456                 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5457                 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5458                 AssignDumpId(&evtinfo[i].dobj);
5459                 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
5460                 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
5461                 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
5462                 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
5463                 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
5464                 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
5465                 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
5466         }
5467
5468         PQclear(res);
5469
5470         destroyPQExpBuffer(query);
5471
5472         return evtinfo;
5473 }
5474
5475 /*
5476  * getProcLangs
5477  *        get basic information about every procedural language in the system
5478  *
5479  * numProcLangs is set to the number of langs read in
5480  *
5481  * NB: this must run after getFuncs() because we assume we can do
5482  * findFuncByOid().
5483  */
5484 ProcLangInfo *
5485 getProcLangs(Archive *fout, int *numProcLangs)
5486 {
5487         PGresult   *res;
5488         int                     ntups;
5489         int                     i;
5490         PQExpBuffer query = createPQExpBuffer();
5491         ProcLangInfo *planginfo;
5492         int                     i_tableoid;
5493         int                     i_oid;
5494         int                     i_lanname;
5495         int                     i_lanpltrusted;
5496         int                     i_lanplcallfoid;
5497         int                     i_laninline;
5498         int                     i_lanvalidator;
5499         int                     i_lanacl;
5500         int                     i_lanowner;
5501
5502         /* Make sure we are in proper schema */
5503         selectSourceSchema(fout, "pg_catalog");
5504
5505         if (fout->remoteVersion >= 90000)
5506         {
5507                 /* pg_language has a laninline column */
5508                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5509                                                   "lanname, lanpltrusted, lanplcallfoid, "
5510                                                   "laninline, lanvalidator,  lanacl, "
5511                                                   "(%s lanowner) AS lanowner "
5512                                                   "FROM pg_language "
5513                                                   "WHERE lanispl "
5514                                                   "ORDER BY oid",
5515                                                   username_subquery);
5516         }
5517         else if (fout->remoteVersion >= 80300)
5518         {
5519                 /* pg_language has a lanowner column */
5520                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5521                                                   "lanname, lanpltrusted, lanplcallfoid, "
5522                                                   "lanvalidator,  lanacl, "
5523                                                   "(%s lanowner) AS lanowner "
5524                                                   "FROM pg_language "
5525                                                   "WHERE lanispl "
5526                                                   "ORDER BY oid",
5527                                                   username_subquery);
5528         }
5529         else if (fout->remoteVersion >= 80100)
5530         {
5531                 /* Languages are owned by the bootstrap superuser, OID 10 */
5532                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5533                                                   "(%s '10') AS lanowner "
5534                                                   "FROM pg_language "
5535                                                   "WHERE lanispl "
5536                                                   "ORDER BY oid",
5537                                                   username_subquery);
5538         }
5539         else if (fout->remoteVersion >= 70400)
5540         {
5541                 /* Languages are owned by the bootstrap superuser, sysid 1 */
5542                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5543                                                   "(%s '1') AS lanowner "
5544                                                   "FROM pg_language "
5545                                                   "WHERE lanispl "
5546                                                   "ORDER BY oid",
5547                                                   username_subquery);
5548         }
5549         else if (fout->remoteVersion >= 70100)
5550         {
5551                 /* No clear notion of an owner at all before 7.4 ... */
5552                 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5553                                                   "WHERE lanispl "
5554                                                   "ORDER BY oid");
5555         }
5556         else
5557         {
5558                 appendPQExpBuffer(query, "SELECT "
5559                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5560                                                   "oid, * FROM pg_language "
5561                                                   "WHERE lanispl "
5562                                                   "ORDER BY oid");
5563         }
5564
5565         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5566
5567         ntups = PQntuples(res);
5568
5569         *numProcLangs = ntups;
5570
5571         planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5572
5573         i_tableoid = PQfnumber(res, "tableoid");
5574         i_oid = PQfnumber(res, "oid");
5575         i_lanname = PQfnumber(res, "lanname");
5576         i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5577         i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5578         /* these may fail and return -1: */
5579         i_laninline = PQfnumber(res, "laninline");
5580         i_lanvalidator = PQfnumber(res, "lanvalidator");
5581         i_lanacl = PQfnumber(res, "lanacl");
5582         i_lanowner = PQfnumber(res, "lanowner");
5583
5584         for (i = 0; i < ntups; i++)
5585         {
5586                 planginfo[i].dobj.objType = DO_PROCLANG;
5587                 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5588                 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5589                 AssignDumpId(&planginfo[i].dobj);
5590
5591                 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5592                 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5593                 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5594                 if (i_laninline >= 0)
5595                         planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5596                 else
5597                         planginfo[i].laninline = InvalidOid;
5598                 if (i_lanvalidator >= 0)
5599                         planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5600                 else
5601                         planginfo[i].lanvalidator = InvalidOid;
5602                 if (i_lanacl >= 0)
5603                         planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5604                 else
5605                         planginfo[i].lanacl = pg_strdup("{=U}");
5606                 if (i_lanowner >= 0)
5607                         planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5608                 else
5609                         planginfo[i].lanowner = pg_strdup("");
5610
5611                 if (fout->remoteVersion < 70300)
5612                 {
5613                         /*
5614                          * We need to make a dependency to ensure the function will be
5615                          * dumped first.  (In 7.3 and later the regular dependency
5616                          * mechanism will handle this for us.)
5617                          */
5618                         FuncInfo   *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5619
5620                         if (funcInfo)
5621                                 addObjectDependency(&planginfo[i].dobj,
5622                                                                         funcInfo->dobj.dumpId);
5623                 }
5624         }
5625
5626         PQclear(res);
5627
5628         destroyPQExpBuffer(query);
5629
5630         return planginfo;
5631 }
5632
5633 /*
5634  * getCasts
5635  *        get basic information about every cast in the system
5636  *
5637  * numCasts is set to the number of casts read in
5638  */
5639 CastInfo *
5640 getCasts(Archive *fout, int *numCasts)
5641 {
5642         PGresult   *res;
5643         int                     ntups;
5644         int                     i;
5645         PQExpBuffer query = createPQExpBuffer();
5646         CastInfo   *castinfo;
5647         int                     i_tableoid;
5648         int                     i_oid;
5649         int                     i_castsource;
5650         int                     i_casttarget;
5651         int                     i_castfunc;
5652         int                     i_castcontext;
5653         int                     i_castmethod;
5654
5655         /* Make sure we are in proper schema */
5656         selectSourceSchema(fout, "pg_catalog");
5657
5658         if (fout->remoteVersion >= 80400)
5659         {
5660                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5661                                                   "castsource, casttarget, castfunc, castcontext, "
5662                                                   "castmethod "
5663                                                   "FROM pg_cast ORDER BY 3,4");
5664         }
5665         else if (fout->remoteVersion >= 70300)
5666         {
5667                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5668                                                   "castsource, casttarget, castfunc, castcontext, "
5669                                 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
5670                                                   "FROM pg_cast ORDER BY 3,4");
5671         }
5672         else
5673         {
5674                 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
5675                                                   "t1.oid AS castsource, t2.oid AS casttarget, "
5676                                                   "p.oid AS castfunc, 'e' AS castcontext, "
5677                                                   "'f' AS castmethod "
5678                                                   "FROM pg_type t1, pg_type t2, pg_proc p "
5679                                                   "WHERE p.pronargs = 1 AND "
5680                                                   "p.proargtypes[0] = t1.oid AND "
5681                                                   "p.prorettype = t2.oid AND p.proname = t2.typname "
5682                                                   "ORDER BY 3,4");
5683         }
5684
5685         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5686
5687         ntups = PQntuples(res);
5688
5689         *numCasts = ntups;
5690
5691         castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
5692
5693         i_tableoid = PQfnumber(res, "tableoid");
5694         i_oid = PQfnumber(res, "oid");
5695         i_castsource = PQfnumber(res, "castsource");
5696         i_casttarget = PQfnumber(res, "casttarget");
5697         i_castfunc = PQfnumber(res, "castfunc");
5698         i_castcontext = PQfnumber(res, "castcontext");
5699         i_castmethod = PQfnumber(res, "castmethod");
5700
5701         for (i = 0; i < ntups; i++)
5702         {
5703                 PQExpBufferData namebuf;
5704                 TypeInfo   *sTypeInfo;
5705                 TypeInfo   *tTypeInfo;
5706
5707                 castinfo[i].dobj.objType = DO_CAST;
5708                 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5709                 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5710                 AssignDumpId(&castinfo[i].dobj);
5711                 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5712                 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5713                 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5714                 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5715                 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5716
5717                 /*
5718                  * Try to name cast as concatenation of typnames.  This is only used
5719                  * for purposes of sorting.  If we fail to find either type, the name
5720                  * will be an empty string.
5721                  */
5722                 initPQExpBuffer(&namebuf);
5723                 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5724                 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5725                 if (sTypeInfo && tTypeInfo)
5726                         appendPQExpBuffer(&namebuf, "%s %s",
5727                                                           sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5728                 castinfo[i].dobj.name = namebuf.data;
5729
5730                 if (OidIsValid(castinfo[i].castfunc))
5731                 {
5732                         /*
5733                          * We need to make a dependency to ensure the function will be
5734                          * dumped first.  (In 7.3 and later the regular dependency
5735                          * mechanism will handle this for us.)
5736                          */
5737                         FuncInfo   *funcInfo;
5738
5739                         funcInfo = findFuncByOid(castinfo[i].castfunc);
5740                         if (funcInfo)
5741                                 addObjectDependency(&castinfo[i].dobj,
5742                                                                         funcInfo->dobj.dumpId);
5743                 }
5744         }
5745
5746         PQclear(res);
5747
5748         destroyPQExpBuffer(query);
5749
5750         return castinfo;
5751 }
5752
5753 /*
5754  * getTableAttrs -
5755  *        for each interesting table, read info about its attributes
5756  *        (names, types, default values, CHECK constraints, etc)
5757  *
5758  * This is implemented in a very inefficient way right now, looping
5759  * through the tblinfo and doing a join per table to find the attrs and their
5760  * types.  However, because we want type names and so forth to be named
5761  * relative to the schema of each table, we couldn't do it in just one
5762  * query.  (Maybe one query per schema?)
5763  *
5764  *      modifies tblinfo
5765  */
5766 void
5767 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
5768 {
5769         int                     i,
5770                                 j;
5771         PQExpBuffer q = createPQExpBuffer();
5772         int                     i_attnum;
5773         int                     i_attname;
5774         int                     i_atttypname;
5775         int                     i_atttypmod;
5776         int                     i_attstattarget;
5777         int                     i_attstorage;
5778         int                     i_typstorage;
5779         int                     i_attnotnull;
5780         int                     i_atthasdef;
5781         int                     i_attisdropped;
5782         int                     i_attlen;
5783         int                     i_attalign;
5784         int                     i_attislocal;
5785         int                     i_attoptions;
5786         int                     i_attcollation;
5787         int                     i_attfdwoptions;
5788         PGresult   *res;
5789         int                     ntups;
5790         bool            hasdefaults;
5791
5792         for (i = 0; i < numTables; i++)
5793         {
5794                 TableInfo  *tbinfo = &tblinfo[i];
5795
5796                 /* Don't bother to collect info for sequences */
5797                 if (tbinfo->relkind == RELKIND_SEQUENCE)
5798                         continue;
5799
5800                 /* Don't bother with uninteresting tables, either */
5801                 if (!tbinfo->interesting)
5802                         continue;
5803
5804                 /*
5805                  * Make sure we are in proper schema for this table; this allows
5806                  * correct retrieval of formatted type names and default exprs
5807                  */
5808                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5809
5810                 /* find all the user attributes and their types */
5811
5812                 /*
5813                  * we must read the attribute names in attribute number order! because
5814                  * we will use the attnum to index into the attnames array later.  We
5815                  * actually ask to order by "attrelid, attnum" because (at least up to
5816                  * 7.3) the planner is not smart enough to realize it needn't re-sort
5817                  * the output of an indexscan on pg_attribute_relid_attnum_index.
5818                  */
5819                 if (g_verbose)
5820                         write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5821                                           tbinfo->dobj.name);
5822
5823                 resetPQExpBuffer(q);
5824
5825                 if (fout->remoteVersion >= 90200)
5826                 {
5827                         /*
5828                          * attfdwoptions is new in 9.2.
5829                          */
5830                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5831                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5832                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5833                                                           "a.attlen, a.attalign, a.attislocal, "
5834                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5835                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5836                                                           "CASE WHEN a.attcollation <> t.typcollation "
5837                                                    "THEN a.attcollation ELSE 0 END AS attcollation, "
5838                                                           "pg_catalog.array_to_string(ARRAY("
5839                                                           "SELECT pg_catalog.quote_ident(option_name) || "
5840                                                           "' ' || pg_catalog.quote_literal(option_value) "
5841                                                 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
5842                                                           "ORDER BY option_name"
5843                                                           "), E',\n    ') AS attfdwoptions "
5844                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5845                                                           "ON a.atttypid = t.oid "
5846                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5847                                                           "AND a.attnum > 0::pg_catalog.int2 "
5848                                                           "ORDER BY a.attrelid, a.attnum",
5849                                                           tbinfo->dobj.catId.oid);
5850                 }
5851                 else if (fout->remoteVersion >= 90100)
5852                 {
5853                         /*
5854                          * attcollation is new in 9.1.  Since we only want to dump COLLATE
5855                          * clauses for attributes whose collation is different from their
5856                          * type's default, we use a CASE here to suppress uninteresting
5857                          * attcollations cheaply.
5858                          */
5859                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5860                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5861                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5862                                                           "a.attlen, a.attalign, a.attislocal, "
5863                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5864                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5865                                                           "CASE WHEN a.attcollation <> t.typcollation "
5866                                                    "THEN a.attcollation ELSE 0 END AS attcollation, "
5867                                                           "NULL AS attfdwoptions "
5868                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5869                                                           "ON a.atttypid = t.oid "
5870                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5871                                                           "AND a.attnum > 0::pg_catalog.int2 "
5872                                                           "ORDER BY a.attrelid, a.attnum",
5873                                                           tbinfo->dobj.catId.oid);
5874                 }
5875                 else if (fout->remoteVersion >= 90000)
5876                 {
5877                         /* attoptions is new in 9.0 */
5878                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5879                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5880                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5881                                                           "a.attlen, a.attalign, a.attislocal, "
5882                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5883                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5884                                                           "0 AS attcollation, "
5885                                                           "NULL AS attfdwoptions "
5886                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5887                                                           "ON a.atttypid = t.oid "
5888                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5889                                                           "AND a.attnum > 0::pg_catalog.int2 "
5890                                                           "ORDER BY a.attrelid, a.attnum",
5891                                                           tbinfo->dobj.catId.oid);
5892                 }
5893                 else if (fout->remoteVersion >= 70300)
5894                 {
5895                         /* need left join here to not fail on dropped columns ... */
5896                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5897                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5898                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5899                                                           "a.attlen, a.attalign, a.attislocal, "
5900                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5901                                                           "'' AS attoptions, 0 AS attcollation, "
5902                                                           "NULL AS attfdwoptions "
5903                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5904                                                           "ON a.atttypid = t.oid "
5905                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5906                                                           "AND a.attnum > 0::pg_catalog.int2 "
5907                                                           "ORDER BY a.attrelid, a.attnum",
5908                                                           tbinfo->dobj.catId.oid);
5909                 }
5910                 else if (fout->remoteVersion >= 70100)
5911                 {
5912                         /*
5913                          * attstattarget doesn't exist in 7.1.  It does exist in 7.2, but
5914                          * we don't dump it because we can't tell whether it's been
5915                          * explicitly set or was just a default.
5916                          *
5917                          * attislocal doesn't exist before 7.3, either; in older databases
5918                          * we assume it's TRUE, else we'd fail to dump non-inherited atts.
5919                          */
5920                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5921                                                           "-1 AS attstattarget, a.attstorage, "
5922                                                           "t.typstorage, a.attnotnull, a.atthasdef, "
5923                                                           "false AS attisdropped, a.attlen, "
5924                                                           "a.attalign, true AS attislocal, "
5925                                                           "format_type(t.oid,a.atttypmod) AS atttypname, "
5926                                                           "'' AS attoptions, 0 AS attcollation, "
5927                                                           "NULL AS attfdwoptions "
5928                                                           "FROM pg_attribute a LEFT JOIN pg_type t "
5929                                                           "ON a.atttypid = t.oid "
5930                                                           "WHERE a.attrelid = '%u'::oid "
5931                                                           "AND a.attnum > 0::int2 "
5932                                                           "ORDER BY a.attrelid, a.attnum",
5933                                                           tbinfo->dobj.catId.oid);
5934                 }
5935                 else
5936                 {
5937                         /* format_type not available before 7.1 */
5938                         appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
5939                                                           "-1 AS attstattarget, "
5940                                                           "attstorage, attstorage AS typstorage, "
5941                                                           "attnotnull, atthasdef, false AS attisdropped, "
5942                                                           "attlen, attalign, "
5943                                                           "true AS attislocal, "
5944                                                           "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
5945                                                           "'' AS attoptions, 0 AS attcollation, "
5946                                                           "NULL AS attfdwoptions "
5947                                                           "FROM pg_attribute a "
5948                                                           "WHERE attrelid = '%u'::oid "
5949                                                           "AND attnum > 0::int2 "
5950                                                           "ORDER BY attrelid, attnum",
5951                                                           tbinfo->dobj.catId.oid);
5952                 }
5953
5954                 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5955
5956                 ntups = PQntuples(res);
5957
5958                 i_attnum = PQfnumber(res, "attnum");
5959                 i_attname = PQfnumber(res, "attname");
5960                 i_atttypname = PQfnumber(res, "atttypname");
5961                 i_atttypmod = PQfnumber(res, "atttypmod");
5962                 i_attstattarget = PQfnumber(res, "attstattarget");
5963                 i_attstorage = PQfnumber(res, "attstorage");
5964                 i_typstorage = PQfnumber(res, "typstorage");
5965                 i_attnotnull = PQfnumber(res, "attnotnull");
5966                 i_atthasdef = PQfnumber(res, "atthasdef");
5967                 i_attisdropped = PQfnumber(res, "attisdropped");
5968                 i_attlen = PQfnumber(res, "attlen");
5969                 i_attalign = PQfnumber(res, "attalign");
5970                 i_attislocal = PQfnumber(res, "attislocal");
5971                 i_attoptions = PQfnumber(res, "attoptions");
5972                 i_attcollation = PQfnumber(res, "attcollation");
5973                 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
5974
5975                 tbinfo->numatts = ntups;
5976                 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
5977                 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
5978                 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
5979                 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
5980                 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
5981                 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
5982                 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
5983                 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
5984                 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
5985                 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
5986                 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
5987                 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
5988                 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
5989                 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
5990                 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
5991                 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
5992                 hasdefaults = false;
5993
5994                 for (j = 0; j < ntups; j++)
5995                 {
5996                         if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
5997                                 exit_horribly(NULL,
5998                                                           "invalid column numbering in table \"%s\"\n",
5999                                                           tbinfo->dobj.name);
6000                         tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
6001                         tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
6002                         tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
6003                         tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
6004                         tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
6005                         tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
6006                         tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
6007                         tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
6008                         tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
6009                         tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
6010                         tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
6011                         tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
6012                         tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
6013                         tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
6014                         tbinfo->attrdefs[j] = NULL; /* fix below */
6015                         if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
6016                                 hasdefaults = true;
6017                         /* these flags will be set in flagInhAttrs() */
6018                         tbinfo->inhNotNull[j] = false;
6019                 }
6020
6021                 PQclear(res);
6022
6023                 /*
6024                  * Get info about column defaults
6025                  */
6026                 if (hasdefaults)
6027                 {
6028                         AttrDefInfo *attrdefs;
6029                         int                     numDefaults;
6030
6031                         if (g_verbose)
6032                                 write_msg(NULL, "finding default expressions of table \"%s\"\n",
6033                                                   tbinfo->dobj.name);
6034
6035                         resetPQExpBuffer(q);
6036                         if (fout->remoteVersion >= 70300)
6037                         {
6038                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
6039                                                    "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
6040                                                                   "FROM pg_catalog.pg_attrdef "
6041                                                                   "WHERE adrelid = '%u'::pg_catalog.oid",
6042                                                                   tbinfo->dobj.catId.oid);
6043                         }
6044                         else if (fout->remoteVersion >= 70200)
6045                         {
6046                                 /* 7.2 did not have OIDs in pg_attrdef */
6047                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
6048                                                                   "pg_get_expr(adbin, adrelid) AS adsrc "
6049                                                                   "FROM pg_attrdef "
6050                                                                   "WHERE adrelid = '%u'::oid",
6051                                                                   tbinfo->dobj.catId.oid);
6052                         }
6053                         else if (fout->remoteVersion >= 70100)
6054                         {
6055                                 /* no pg_get_expr, so must rely on adsrc */
6056                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
6057                                                                   "FROM pg_attrdef "
6058                                                                   "WHERE adrelid = '%u'::oid",
6059                                                                   tbinfo->dobj.catId.oid);
6060                         }
6061                         else
6062                         {
6063                                 /* no pg_get_expr, no tableoid either */
6064                                 appendPQExpBuffer(q, "SELECT "
6065                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
6066                                                                   "oid, adnum, adsrc "
6067                                                                   "FROM pg_attrdef "
6068                                                                   "WHERE adrelid = '%u'::oid",
6069                                                                   tbinfo->dobj.catId.oid);
6070                         }
6071                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6072
6073                         numDefaults = PQntuples(res);
6074                         attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
6075
6076                         for (j = 0; j < numDefaults; j++)
6077                         {
6078                                 int                     adnum;
6079
6080                                 adnum = atoi(PQgetvalue(res, j, 2));
6081
6082                                 if (adnum <= 0 || adnum > ntups)
6083                                         exit_horribly(NULL,
6084                                                                   "invalid adnum value %d for table \"%s\"\n",
6085                                                                   adnum, tbinfo->dobj.name);
6086
6087                                 /*
6088                                  * dropped columns shouldn't have defaults, but just in case,
6089                                  * ignore 'em
6090                                  */
6091                                 if (tbinfo->attisdropped[adnum - 1])
6092                                         continue;
6093
6094                                 attrdefs[j].dobj.objType = DO_ATTRDEF;
6095                                 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6096                                 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6097                                 AssignDumpId(&attrdefs[j].dobj);
6098                                 attrdefs[j].adtable = tbinfo;
6099                                 attrdefs[j].adnum = adnum;
6100                                 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
6101
6102                                 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
6103                                 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
6104
6105                                 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
6106
6107                                 /*
6108                                  * Defaults on a VIEW must always be dumped as separate ALTER
6109                                  * TABLE commands.      Defaults on regular tables are dumped as
6110                                  * part of the CREATE TABLE if possible, which it won't be if
6111                                  * the column is not going to be emitted explicitly.
6112                                  */
6113                                 if (tbinfo->relkind == RELKIND_VIEW)
6114                                 {
6115                                         attrdefs[j].separate = true;
6116                                         /* needed in case pre-7.3 DB: */
6117                                         addObjectDependency(&attrdefs[j].dobj,
6118                                                                                 tbinfo->dobj.dumpId);
6119                                 }
6120                                 else if (!shouldPrintColumn(tbinfo, adnum - 1))
6121                                 {
6122                                         /* column will be suppressed, print default separately */
6123                                         attrdefs[j].separate = true;
6124                                         /* needed in case pre-7.3 DB: */
6125                                         addObjectDependency(&attrdefs[j].dobj,
6126                                                                                 tbinfo->dobj.dumpId);
6127                                 }
6128                                 else
6129                                 {
6130                                         attrdefs[j].separate = false;
6131
6132                                         /*
6133                                          * Mark the default as needing to appear before the table,
6134                                          * so that any dependencies it has must be emitted before
6135                                          * the CREATE TABLE.  If this is not possible, we'll
6136                                          * change to "separate" mode while sorting dependencies.
6137                                          */
6138                                         addObjectDependency(&tbinfo->dobj,
6139                                                                                 attrdefs[j].dobj.dumpId);
6140                                 }
6141
6142                                 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
6143                         }
6144                         PQclear(res);
6145                 }
6146
6147                 /*
6148                  * Get info about table CHECK constraints
6149                  */
6150                 if (tbinfo->ncheck > 0)
6151                 {
6152                         ConstraintInfo *constrs;
6153                         int                     numConstrs;
6154
6155                         if (g_verbose)
6156                                 write_msg(NULL, "finding check constraints for table \"%s\"\n",
6157                                                   tbinfo->dobj.name);
6158
6159                         resetPQExpBuffer(q);
6160                         if (fout->remoteVersion >= 90200)
6161                         {
6162                                 /*
6163                                  * convalidated is new in 9.2 (actually, it is there in 9.1,
6164                                  * but it wasn't ever false for check constraints until 9.2).
6165                                  */
6166                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6167                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6168                                                                   "conislocal, convalidated "
6169                                                                   "FROM pg_catalog.pg_constraint "
6170                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6171                                                                   "   AND contype = 'c' "
6172                                                                   "ORDER BY conname",
6173                                                                   tbinfo->dobj.catId.oid);
6174                         }
6175                         else if (fout->remoteVersion >= 80400)
6176                         {
6177                                 /* conislocal is new in 8.4 */
6178                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6179                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6180                                                                   "conislocal, true AS convalidated "
6181                                                                   "FROM pg_catalog.pg_constraint "
6182                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6183                                                                   "   AND contype = 'c' "
6184                                                                   "ORDER BY conname",
6185                                                                   tbinfo->dobj.catId.oid);
6186                         }
6187                         else if (fout->remoteVersion >= 70400)
6188                         {
6189                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6190                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6191                                                                   "true AS conislocal, true AS convalidated "
6192                                                                   "FROM pg_catalog.pg_constraint "
6193                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6194                                                                   "   AND contype = 'c' "
6195                                                                   "ORDER BY conname",
6196                                                                   tbinfo->dobj.catId.oid);
6197                         }
6198                         else if (fout->remoteVersion >= 70300)
6199                         {
6200                                 /* no pg_get_constraintdef, must use consrc */
6201                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6202                                                                   "'CHECK (' || consrc || ')' AS consrc, "
6203                                                                   "true AS conislocal, true AS convalidated "
6204                                                                   "FROM pg_catalog.pg_constraint "
6205                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6206                                                                   "   AND contype = 'c' "
6207                                                                   "ORDER BY conname",
6208                                                                   tbinfo->dobj.catId.oid);
6209                         }
6210                         else if (fout->remoteVersion >= 70200)
6211                         {
6212                                 /* 7.2 did not have OIDs in pg_relcheck */
6213                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6214                                                                   "rcname AS conname, "
6215                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6216                                                                   "true AS conislocal, true AS convalidated "
6217                                                                   "FROM pg_relcheck "
6218                                                                   "WHERE rcrelid = '%u'::oid "
6219                                                                   "ORDER BY rcname",
6220                                                                   tbinfo->dobj.catId.oid);
6221                         }
6222                         else if (fout->remoteVersion >= 70100)
6223                         {
6224                                 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6225                                                                   "rcname AS conname, "
6226                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6227                                                                   "true AS conislocal, true AS convalidated "
6228                                                                   "FROM pg_relcheck "
6229                                                                   "WHERE rcrelid = '%u'::oid "
6230                                                                   "ORDER BY rcname",
6231                                                                   tbinfo->dobj.catId.oid);
6232                         }
6233                         else
6234                         {
6235                                 /* no tableoid in 7.0 */
6236                                 appendPQExpBuffer(q, "SELECT "
6237                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6238                                                                   "oid, rcname AS conname, "
6239                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6240                                                                   "true AS conislocal, true AS convalidated "
6241                                                                   "FROM pg_relcheck "
6242                                                                   "WHERE rcrelid = '%u'::oid "
6243                                                                   "ORDER BY rcname",
6244                                                                   tbinfo->dobj.catId.oid);
6245                         }
6246                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6247
6248                         numConstrs = PQntuples(res);
6249                         if (numConstrs != tbinfo->ncheck)
6250                         {
6251                                 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6252                                                                                  "expected %d check constraints on table \"%s\" but found %d\n",
6253                                                                                  tbinfo->ncheck),
6254                                                   tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6255                                 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6256                                 exit_nicely(1);
6257                         }
6258
6259                         constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6260                         tbinfo->checkexprs = constrs;
6261
6262                         for (j = 0; j < numConstrs; j++)
6263                         {
6264                                 bool            validated = PQgetvalue(res, j, 5)[0] == 't';
6265
6266                                 constrs[j].dobj.objType = DO_CONSTRAINT;
6267                                 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6268                                 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6269                                 AssignDumpId(&constrs[j].dobj);
6270                                 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6271                                 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6272                                 constrs[j].contable = tbinfo;
6273                                 constrs[j].condomain = NULL;
6274                                 constrs[j].contype = 'c';
6275                                 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6276                                 constrs[j].confrelid = InvalidOid;
6277                                 constrs[j].conindex = 0;
6278                                 constrs[j].condeferrable = false;
6279                                 constrs[j].condeferred = false;
6280                                 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6281
6282                                 /*
6283                                  * An unvalidated constraint needs to be dumped separately, so
6284                                  * that potentially-violating existing data is loaded before
6285                                  * the constraint.
6286                                  */
6287                                 constrs[j].separate = !validated;
6288
6289                                 constrs[j].dobj.dump = tbinfo->dobj.dump;
6290
6291                                 /*
6292                                  * Mark the constraint as needing to appear before the table
6293                                  * --- this is so that any other dependencies of the
6294                                  * constraint will be emitted before we try to create the
6295                                  * table.  If the constraint is to be dumped separately, it
6296                                  * will be dumped after data is loaded anyway, so don't do it.
6297                                  * (There's an automatic dependency in the opposite direction
6298                                  * anyway, so don't need to add one manually here.)
6299                                  */
6300                                 if (!constrs[j].separate)
6301                                         addObjectDependency(&tbinfo->dobj,
6302                                                                                 constrs[j].dobj.dumpId);
6303
6304                                 /*
6305                                  * If the constraint is inherited, this will be detected later
6306                                  * (in pre-8.4 databases).      We also detect later if the
6307                                  * constraint must be split out from the table definition.
6308                                  */
6309                         }
6310                         PQclear(res);
6311                 }
6312         }
6313
6314         destroyPQExpBuffer(q);
6315 }
6316
6317 /*
6318  * Test whether a column should be printed as part of table's CREATE TABLE.
6319  * Column number is zero-based.
6320  *
6321  * Normally this is always true, but it's false for dropped columns, as well
6322  * as those that were inherited without any local definition.  (If we print
6323  * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6324  * However, in binary_upgrade mode, we must print all such columns anyway and
6325  * fix the attislocal/attisdropped state later, so as to keep control of the
6326  * physical column order.
6327  *
6328  * This function exists because there are scattered nonobvious places that
6329  * must be kept in sync with this decision.
6330  */
6331 bool
6332 shouldPrintColumn(TableInfo *tbinfo, int colno)
6333 {
6334         if (binary_upgrade)
6335                 return true;
6336         return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6337 }
6338
6339
6340 /*
6341  * getTSParsers:
6342  *        read all text search parsers in the system catalogs and return them
6343  *        in the TSParserInfo* structure
6344  *
6345  *      numTSParsers is set to the number of parsers read in
6346  */
6347 TSParserInfo *
6348 getTSParsers(Archive *fout, int *numTSParsers)
6349 {
6350         PGresult   *res;
6351         int                     ntups;
6352         int                     i;
6353         PQExpBuffer query;
6354         TSParserInfo *prsinfo;
6355         int                     i_tableoid;
6356         int                     i_oid;
6357         int                     i_prsname;
6358         int                     i_prsnamespace;
6359         int                     i_prsstart;
6360         int                     i_prstoken;
6361         int                     i_prsend;
6362         int                     i_prsheadline;
6363         int                     i_prslextype;
6364
6365         /* Before 8.3, there is no built-in text search support */
6366         if (fout->remoteVersion < 80300)
6367         {
6368                 *numTSParsers = 0;
6369                 return NULL;
6370         }
6371
6372         query = createPQExpBuffer();
6373
6374         /*
6375          * find all text search objects, including builtin ones; we filter out
6376          * system-defined objects at dump-out time.
6377          */
6378
6379         /* Make sure we are in proper schema */
6380         selectSourceSchema(fout, "pg_catalog");
6381
6382         appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6383                                           "prsstart::oid, prstoken::oid, "
6384                                           "prsend::oid, prsheadline::oid, prslextype::oid "
6385                                           "FROM pg_ts_parser");
6386
6387         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6388
6389         ntups = PQntuples(res);
6390         *numTSParsers = ntups;
6391
6392         prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6393
6394         i_tableoid = PQfnumber(res, "tableoid");
6395         i_oid = PQfnumber(res, "oid");
6396         i_prsname = PQfnumber(res, "prsname");
6397         i_prsnamespace = PQfnumber(res, "prsnamespace");
6398         i_prsstart = PQfnumber(res, "prsstart");
6399         i_prstoken = PQfnumber(res, "prstoken");
6400         i_prsend = PQfnumber(res, "prsend");
6401         i_prsheadline = PQfnumber(res, "prsheadline");
6402         i_prslextype = PQfnumber(res, "prslextype");
6403
6404         for (i = 0; i < ntups; i++)
6405         {
6406                 prsinfo[i].dobj.objType = DO_TSPARSER;
6407                 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6408                 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6409                 AssignDumpId(&prsinfo[i].dobj);
6410                 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6411                 prsinfo[i].dobj.namespace =
6412                         findNamespace(fout,
6413                                                   atooid(PQgetvalue(res, i, i_prsnamespace)),
6414                                                   prsinfo[i].dobj.catId.oid);
6415                 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6416                 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6417                 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6418                 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6419                 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6420
6421                 /* Decide whether we want to dump it */
6422                 selectDumpableObject(&(prsinfo[i].dobj));
6423         }
6424
6425         PQclear(res);
6426
6427         destroyPQExpBuffer(query);
6428
6429         return prsinfo;
6430 }
6431
6432 /*
6433  * getTSDictionaries:
6434  *        read all text search dictionaries in the system catalogs and return them
6435  *        in the TSDictInfo* structure
6436  *
6437  *      numTSDicts is set to the number of dictionaries read in
6438  */
6439 TSDictInfo *
6440 getTSDictionaries(Archive *fout, int *numTSDicts)
6441 {
6442         PGresult   *res;
6443         int                     ntups;
6444         int                     i;
6445         PQExpBuffer query;
6446         TSDictInfo *dictinfo;
6447         int                     i_tableoid;
6448         int                     i_oid;
6449         int                     i_dictname;
6450         int                     i_dictnamespace;
6451         int                     i_rolname;
6452         int                     i_dicttemplate;
6453         int                     i_dictinitoption;
6454
6455         /* Before 8.3, there is no built-in text search support */
6456         if (fout->remoteVersion < 80300)
6457         {
6458                 *numTSDicts = 0;
6459                 return NULL;
6460         }
6461
6462         query = createPQExpBuffer();
6463
6464         /* Make sure we are in proper schema */
6465         selectSourceSchema(fout, "pg_catalog");
6466
6467         appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6468                                           "dictnamespace, (%s dictowner) AS rolname, "
6469                                           "dicttemplate, dictinitoption "
6470                                           "FROM pg_ts_dict",
6471                                           username_subquery);
6472
6473         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6474
6475         ntups = PQntuples(res);
6476         *numTSDicts = ntups;
6477
6478         dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6479
6480         i_tableoid = PQfnumber(res, "tableoid");
6481         i_oid = PQfnumber(res, "oid");
6482         i_dictname = PQfnumber(res, "dictname");
6483         i_dictnamespace = PQfnumber(res, "dictnamespace");
6484         i_rolname = PQfnumber(res, "rolname");
6485         i_dictinitoption = PQfnumber(res, "dictinitoption");
6486         i_dicttemplate = PQfnumber(res, "dicttemplate");
6487
6488         for (i = 0; i < ntups; i++)
6489         {
6490                 dictinfo[i].dobj.objType = DO_TSDICT;
6491                 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6492                 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6493                 AssignDumpId(&dictinfo[i].dobj);
6494                 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6495                 dictinfo[i].dobj.namespace =
6496                         findNamespace(fout,
6497                                                   atooid(PQgetvalue(res, i, i_dictnamespace)),
6498                                                   dictinfo[i].dobj.catId.oid);
6499                 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6500                 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6501                 if (PQgetisnull(res, i, i_dictinitoption))
6502                         dictinfo[i].dictinitoption = NULL;
6503                 else
6504                         dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6505
6506                 /* Decide whether we want to dump it */
6507                 selectDumpableObject(&(dictinfo[i].dobj));
6508         }
6509
6510         PQclear(res);
6511
6512         destroyPQExpBuffer(query);
6513
6514         return dictinfo;
6515 }
6516
6517 /*
6518  * getTSTemplates:
6519  *        read all text search templates in the system catalogs and return them
6520  *        in the TSTemplateInfo* structure
6521  *
6522  *      numTSTemplates is set to the number of templates read in
6523  */
6524 TSTemplateInfo *
6525 getTSTemplates(Archive *fout, int *numTSTemplates)
6526 {
6527         PGresult   *res;
6528         int                     ntups;
6529         int                     i;
6530         PQExpBuffer query;
6531         TSTemplateInfo *tmplinfo;
6532         int                     i_tableoid;
6533         int                     i_oid;
6534         int                     i_tmplname;
6535         int                     i_tmplnamespace;
6536         int                     i_tmplinit;
6537         int                     i_tmpllexize;
6538
6539         /* Before 8.3, there is no built-in text search support */
6540         if (fout->remoteVersion < 80300)
6541         {
6542                 *numTSTemplates = 0;
6543                 return NULL;
6544         }
6545
6546         query = createPQExpBuffer();
6547
6548         /* Make sure we are in proper schema */
6549         selectSourceSchema(fout, "pg_catalog");
6550
6551         appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6552                                           "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6553                                           "FROM pg_ts_template");
6554
6555         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6556
6557         ntups = PQntuples(res);
6558         *numTSTemplates = ntups;
6559
6560         tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6561
6562         i_tableoid = PQfnumber(res, "tableoid");
6563         i_oid = PQfnumber(res, "oid");
6564         i_tmplname = PQfnumber(res, "tmplname");
6565         i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6566         i_tmplinit = PQfnumber(res, "tmplinit");
6567         i_tmpllexize = PQfnumber(res, "tmpllexize");
6568
6569         for (i = 0; i < ntups; i++)
6570         {
6571                 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6572                 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6573                 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6574                 AssignDumpId(&tmplinfo[i].dobj);
6575                 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6576                 tmplinfo[i].dobj.namespace =
6577                         findNamespace(fout,
6578                                                   atooid(PQgetvalue(res, i, i_tmplnamespace)),
6579                                                   tmplinfo[i].dobj.catId.oid);
6580                 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6581                 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6582
6583                 /* Decide whether we want to dump it */
6584                 selectDumpableObject(&(tmplinfo[i].dobj));
6585         }
6586
6587         PQclear(res);
6588
6589         destroyPQExpBuffer(query);
6590
6591         return tmplinfo;
6592 }
6593
6594 /*
6595  * getTSConfigurations:
6596  *        read all text search configurations in the system catalogs and return
6597  *        them in the TSConfigInfo* structure
6598  *
6599  *      numTSConfigs is set to the number of configurations read in
6600  */
6601 TSConfigInfo *
6602 getTSConfigurations(Archive *fout, int *numTSConfigs)
6603 {
6604         PGresult   *res;
6605         int                     ntups;
6606         int                     i;
6607         PQExpBuffer query;
6608         TSConfigInfo *cfginfo;
6609         int                     i_tableoid;
6610         int                     i_oid;
6611         int                     i_cfgname;
6612         int                     i_cfgnamespace;
6613         int                     i_rolname;
6614         int                     i_cfgparser;
6615
6616         /* Before 8.3, there is no built-in text search support */
6617         if (fout->remoteVersion < 80300)
6618         {
6619                 *numTSConfigs = 0;
6620                 return NULL;
6621         }
6622
6623         query = createPQExpBuffer();
6624
6625         /* Make sure we are in proper schema */
6626         selectSourceSchema(fout, "pg_catalog");
6627
6628         appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6629                                           "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6630                                           "FROM pg_ts_config",
6631                                           username_subquery);
6632
6633         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6634
6635         ntups = PQntuples(res);
6636         *numTSConfigs = ntups;
6637
6638         cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6639
6640         i_tableoid = PQfnumber(res, "tableoid");
6641         i_oid = PQfnumber(res, "oid");
6642         i_cfgname = PQfnumber(res, "cfgname");
6643         i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6644         i_rolname = PQfnumber(res, "rolname");
6645         i_cfgparser = PQfnumber(res, "cfgparser");
6646
6647         for (i = 0; i < ntups; i++)
6648         {
6649                 cfginfo[i].dobj.objType = DO_TSCONFIG;
6650                 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6651                 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6652                 AssignDumpId(&cfginfo[i].dobj);
6653                 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6654                 cfginfo[i].dobj.namespace =
6655                         findNamespace(fout,
6656                                                   atooid(PQgetvalue(res, i, i_cfgnamespace)),
6657                                                   cfginfo[i].dobj.catId.oid);
6658                 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6659                 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6660
6661                 /* Decide whether we want to dump it */
6662                 selectDumpableObject(&(cfginfo[i].dobj));
6663         }
6664
6665         PQclear(res);
6666
6667         destroyPQExpBuffer(query);
6668
6669         return cfginfo;
6670 }
6671
6672 /*
6673  * getForeignDataWrappers:
6674  *        read all foreign-data wrappers in the system catalogs and return
6675  *        them in the FdwInfo* structure
6676  *
6677  *      numForeignDataWrappers is set to the number of fdws read in
6678  */
6679 FdwInfo *
6680 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
6681 {
6682         PGresult   *res;
6683         int                     ntups;
6684         int                     i;
6685         PQExpBuffer query = createPQExpBuffer();
6686         FdwInfo    *fdwinfo;
6687         int                     i_tableoid;
6688         int                     i_oid;
6689         int                     i_fdwname;
6690         int                     i_rolname;
6691         int                     i_fdwhandler;
6692         int                     i_fdwvalidator;
6693         int                     i_fdwacl;
6694         int                     i_fdwoptions;
6695
6696         /* Before 8.4, there are no foreign-data wrappers */
6697         if (fout->remoteVersion < 80400)
6698         {
6699                 *numForeignDataWrappers = 0;
6700                 return NULL;
6701         }
6702
6703         /* Make sure we are in proper schema */
6704         selectSourceSchema(fout, "pg_catalog");
6705
6706         if (fout->remoteVersion >= 90100)
6707         {
6708                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6709                                                   "(%s fdwowner) AS rolname, "
6710                                                   "fdwhandler::pg_catalog.regproc, "
6711                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
6712                                                   "array_to_string(ARRAY("
6713                                                   "SELECT quote_ident(option_name) || ' ' || "
6714                                                   "quote_literal(option_value) "
6715                                                   "FROM pg_options_to_table(fdwoptions) "
6716                                                   "ORDER BY option_name"
6717                                                   "), E',\n    ') AS fdwoptions "
6718                                                   "FROM pg_foreign_data_wrapper",
6719                                                   username_subquery);
6720         }
6721         else
6722         {
6723                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6724                                                   "(%s fdwowner) AS rolname, "
6725                                                   "'-' AS fdwhandler, "
6726                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
6727                                                   "array_to_string(ARRAY("
6728                                                   "SELECT quote_ident(option_name) || ' ' || "
6729                                                   "quote_literal(option_value) "
6730                                                   "FROM pg_options_to_table(fdwoptions) "
6731                                                   "ORDER BY option_name"
6732                                                   "), E',\n    ') AS fdwoptions "
6733                                                   "FROM pg_foreign_data_wrapper",
6734                                                   username_subquery);
6735         }
6736
6737         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6738
6739         ntups = PQntuples(res);
6740         *numForeignDataWrappers = ntups;
6741
6742         fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6743
6744         i_tableoid = PQfnumber(res, "tableoid");
6745         i_oid = PQfnumber(res, "oid");
6746         i_fdwname = PQfnumber(res, "fdwname");
6747         i_rolname = PQfnumber(res, "rolname");
6748         i_fdwhandler = PQfnumber(res, "fdwhandler");
6749         i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6750         i_fdwacl = PQfnumber(res, "fdwacl");
6751         i_fdwoptions = PQfnumber(res, "fdwoptions");
6752
6753         for (i = 0; i < ntups; i++)
6754         {
6755                 fdwinfo[i].dobj.objType = DO_FDW;
6756                 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6757                 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6758                 AssignDumpId(&fdwinfo[i].dobj);
6759                 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6760                 fdwinfo[i].dobj.namespace = NULL;
6761                 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6762                 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6763                 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6764                 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6765                 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6766
6767                 /* Decide whether we want to dump it */
6768                 selectDumpableObject(&(fdwinfo[i].dobj));
6769         }
6770
6771         PQclear(res);
6772
6773         destroyPQExpBuffer(query);
6774
6775         return fdwinfo;
6776 }
6777
6778 /*
6779  * getForeignServers:
6780  *        read all foreign servers in the system catalogs and return
6781  *        them in the ForeignServerInfo * structure
6782  *
6783  *      numForeignServers is set to the number of servers read in
6784  */
6785 ForeignServerInfo *
6786 getForeignServers(Archive *fout, int *numForeignServers)
6787 {
6788         PGresult   *res;
6789         int                     ntups;
6790         int                     i;
6791         PQExpBuffer query = createPQExpBuffer();
6792         ForeignServerInfo *srvinfo;
6793         int                     i_tableoid;
6794         int                     i_oid;
6795         int                     i_srvname;
6796         int                     i_rolname;
6797         int                     i_srvfdw;
6798         int                     i_srvtype;
6799         int                     i_srvversion;
6800         int                     i_srvacl;
6801         int                     i_srvoptions;
6802
6803         /* Before 8.4, there are no foreign servers */
6804         if (fout->remoteVersion < 80400)
6805         {
6806                 *numForeignServers = 0;
6807                 return NULL;
6808         }
6809
6810         /* Make sure we are in proper schema */
6811         selectSourceSchema(fout, "pg_catalog");
6812
6813         appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6814                                           "(%s srvowner) AS rolname, "
6815                                           "srvfdw, srvtype, srvversion, srvacl,"
6816                                           "array_to_string(ARRAY("
6817                                           "SELECT quote_ident(option_name) || ' ' || "
6818                                           "quote_literal(option_value) "
6819                                           "FROM pg_options_to_table(srvoptions) "
6820                                           "ORDER BY option_name"
6821                                           "), E',\n    ') AS srvoptions "
6822                                           "FROM pg_foreign_server",
6823                                           username_subquery);
6824
6825         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6826
6827         ntups = PQntuples(res);
6828         *numForeignServers = ntups;
6829
6830         srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
6831
6832         i_tableoid = PQfnumber(res, "tableoid");
6833         i_oid = PQfnumber(res, "oid");
6834         i_srvname = PQfnumber(res, "srvname");
6835         i_rolname = PQfnumber(res, "rolname");
6836         i_srvfdw = PQfnumber(res, "srvfdw");
6837         i_srvtype = PQfnumber(res, "srvtype");
6838         i_srvversion = PQfnumber(res, "srvversion");
6839         i_srvacl = PQfnumber(res, "srvacl");
6840         i_srvoptions = PQfnumber(res, "srvoptions");
6841
6842         for (i = 0; i < ntups; i++)
6843         {
6844                 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
6845                 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6846                 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6847                 AssignDumpId(&srvinfo[i].dobj);
6848                 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
6849                 srvinfo[i].dobj.namespace = NULL;
6850                 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6851                 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
6852                 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
6853                 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
6854                 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
6855                 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
6856
6857                 /* Decide whether we want to dump it */
6858                 selectDumpableObject(&(srvinfo[i].dobj));
6859         }
6860
6861         PQclear(res);
6862
6863         destroyPQExpBuffer(query);
6864
6865         return srvinfo;
6866 }
6867
6868 /*
6869  * getDefaultACLs:
6870  *        read all default ACL information in the system catalogs and return
6871  *        them in the DefaultACLInfo structure
6872  *
6873  *      numDefaultACLs is set to the number of ACLs read in
6874  */
6875 DefaultACLInfo *
6876 getDefaultACLs(Archive *fout, int *numDefaultACLs)
6877 {
6878         DefaultACLInfo *daclinfo;
6879         PQExpBuffer query;
6880         PGresult   *res;
6881         int                     i_oid;
6882         int                     i_tableoid;
6883         int                     i_defaclrole;
6884         int                     i_defaclnamespace;
6885         int                     i_defaclobjtype;
6886         int                     i_defaclacl;
6887         int                     i,
6888                                 ntups;
6889
6890         if (fout->remoteVersion < 90000)
6891         {
6892                 *numDefaultACLs = 0;
6893                 return NULL;
6894         }
6895
6896         query = createPQExpBuffer();
6897
6898         /* Make sure we are in proper schema */
6899         selectSourceSchema(fout, "pg_catalog");
6900
6901         appendPQExpBuffer(query, "SELECT oid, tableoid, "
6902                                           "(%s defaclrole) AS defaclrole, "
6903                                           "defaclnamespace, "
6904                                           "defaclobjtype, "
6905                                           "defaclacl "
6906                                           "FROM pg_default_acl",
6907                                           username_subquery);
6908
6909         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6910
6911         ntups = PQntuples(res);
6912         *numDefaultACLs = ntups;
6913
6914         daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
6915
6916         i_oid = PQfnumber(res, "oid");
6917         i_tableoid = PQfnumber(res, "tableoid");
6918         i_defaclrole = PQfnumber(res, "defaclrole");
6919         i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6920         i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6921         i_defaclacl = PQfnumber(res, "defaclacl");
6922
6923         for (i = 0; i < ntups; i++)
6924         {
6925                 Oid                     nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6926
6927                 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6928                 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6929                 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6930                 AssignDumpId(&daclinfo[i].dobj);
6931                 /* cheesy ... is it worth coming up with a better object name? */
6932                 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
6933
6934                 if (nspid != InvalidOid)
6935                         daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
6936                                                                                                  daclinfo[i].dobj.catId.oid);
6937                 else
6938                         daclinfo[i].dobj.namespace = NULL;
6939
6940                 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
6941                 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6942                 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
6943
6944                 /* Decide whether we want to dump it */
6945                 selectDumpableDefaultACL(&(daclinfo[i]));
6946         }
6947
6948         PQclear(res);
6949
6950         destroyPQExpBuffer(query);
6951
6952         return daclinfo;
6953 }
6954
6955 /*
6956  * dumpComment --
6957  *
6958  * This routine is used to dump any comments associated with the
6959  * object handed to this routine. The routine takes a constant character
6960  * string for the target part of the comment-creation command, plus
6961  * the namespace and owner of the object (for labeling the ArchiveEntry),
6962  * plus catalog ID and subid which are the lookup key for pg_description,
6963  * plus the dump ID for the object (for setting a dependency).
6964  * If a matching pg_description entry is found, it is dumped.
6965  *
6966  * Note: although this routine takes a dumpId for dependency purposes,
6967  * that purpose is just to mark the dependency in the emitted dump file
6968  * for possible future use by pg_restore.  We do NOT use it for determining
6969  * ordering of the comment in the dump file, because this routine is called
6970  * after dependency sorting occurs.  This routine should be called just after
6971  * calling ArchiveEntry() for the specified object.
6972  */
6973 static void
6974 dumpComment(Archive *fout, const char *target,
6975                         const char *namespace, const char *owner,
6976                         CatalogId catalogId, int subid, DumpId dumpId)
6977 {
6978         CommentItem *comments;
6979         int                     ncomments;
6980
6981         /* Comments are schema not data ... except blob comments are data */
6982         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6983         {
6984                 if (dataOnly)
6985                         return;
6986         }
6987         else
6988         {
6989                 if (schemaOnly)
6990                         return;
6991         }
6992
6993         /* Search for comments associated with catalogId, using table */
6994         ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6995                                                          &comments);
6996
6997         /* Is there one matching the subid? */
6998         while (ncomments > 0)
6999         {
7000                 if (comments->objsubid == subid)
7001                         break;
7002                 comments++;
7003                 ncomments--;
7004         }
7005
7006         /* If a comment exists, build COMMENT ON statement */
7007         if (ncomments > 0)
7008         {
7009                 PQExpBuffer query = createPQExpBuffer();
7010
7011                 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
7012                 appendStringLiteralAH(query, comments->descr, fout);
7013                 appendPQExpBuffer(query, ";\n");
7014
7015                 /*
7016                  * We mark comments as SECTION_NONE because they really belong in the
7017                  * same section as their parent, whether that is pre-data or
7018                  * post-data.
7019                  */
7020                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7021                                          target, namespace, NULL, owner,
7022                                          false, "COMMENT", SECTION_NONE,
7023                                          query->data, "", NULL,
7024                                          &(dumpId), 1,
7025                                          NULL, NULL);
7026
7027                 destroyPQExpBuffer(query);
7028         }
7029 }
7030
7031 /*
7032  * dumpTableComment --
7033  *
7034  * As above, but dump comments for both the specified table (or view)
7035  * and its columns.
7036  */
7037 static void
7038 dumpTableComment(Archive *fout, TableInfo *tbinfo,
7039                                  const char *reltypename)
7040 {
7041         CommentItem *comments;
7042         int                     ncomments;
7043         PQExpBuffer query;
7044         PQExpBuffer target;
7045
7046         /* Comments are SCHEMA not data */
7047         if (dataOnly)
7048                 return;
7049
7050         /* Search for comments associated with relation, using table */
7051         ncomments = findComments(fout,
7052                                                          tbinfo->dobj.catId.tableoid,
7053                                                          tbinfo->dobj.catId.oid,
7054                                                          &comments);
7055
7056         /* If comments exist, build COMMENT ON statements */
7057         if (ncomments <= 0)
7058                 return;
7059
7060         query = createPQExpBuffer();
7061         target = createPQExpBuffer();
7062
7063         while (ncomments > 0)
7064         {
7065                 const char *descr = comments->descr;
7066                 int                     objsubid = comments->objsubid;
7067
7068                 if (objsubid == 0)
7069                 {
7070                         resetPQExpBuffer(target);
7071                         appendPQExpBuffer(target, "%s %s", reltypename,
7072                                                           fmtId(tbinfo->dobj.name));
7073
7074                         resetPQExpBuffer(query);
7075                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7076                         appendStringLiteralAH(query, descr, fout);
7077                         appendPQExpBuffer(query, ";\n");
7078
7079                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
7080                                                  target->data,
7081                                                  tbinfo->dobj.namespace->dobj.name,
7082                                                  NULL, tbinfo->rolname,
7083                                                  false, "COMMENT", SECTION_NONE,
7084                                                  query->data, "", NULL,
7085                                                  &(tbinfo->dobj.dumpId), 1,
7086                                                  NULL, NULL);
7087                 }
7088                 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
7089                 {
7090                         resetPQExpBuffer(target);
7091                         appendPQExpBuffer(target, "COLUMN %s.",
7092                                                           fmtId(tbinfo->dobj.name));
7093                         appendPQExpBuffer(target, "%s",
7094                                                           fmtId(tbinfo->attnames[objsubid - 1]));
7095
7096                         resetPQExpBuffer(query);
7097                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7098                         appendStringLiteralAH(query, descr, fout);
7099                         appendPQExpBuffer(query, ";\n");
7100
7101                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
7102                                                  target->data,
7103                                                  tbinfo->dobj.namespace->dobj.name,
7104                                                  NULL, tbinfo->rolname,
7105                                                  false, "COMMENT", SECTION_NONE,
7106                                                  query->data, "", NULL,
7107                                                  &(tbinfo->dobj.dumpId), 1,
7108                                                  NULL, NULL);
7109                 }
7110
7111                 comments++;
7112                 ncomments--;
7113         }
7114
7115         destroyPQExpBuffer(query);
7116         destroyPQExpBuffer(target);
7117 }
7118
7119 /*
7120  * findComments --
7121  *
7122  * Find the comment(s), if any, associated with the given object.  All the
7123  * objsubid values associated with the given classoid/objoid are found with
7124  * one search.
7125  */
7126 static int
7127 findComments(Archive *fout, Oid classoid, Oid objoid,
7128                          CommentItem **items)
7129 {
7130         /* static storage for table of comments */
7131         static CommentItem *comments = NULL;
7132         static int      ncomments = -1;
7133
7134         CommentItem *middle = NULL;
7135         CommentItem *low;
7136         CommentItem *high;
7137         int                     nmatch;
7138
7139         /* Get comments if we didn't already */
7140         if (ncomments < 0)
7141                 ncomments = collectComments(fout, &comments);
7142
7143         /*
7144          * Pre-7.2, pg_description does not contain classoid, so collectComments
7145          * just stores a zero.  If there's a collision on object OID, well, you
7146          * get duplicate comments.
7147          */
7148         if (fout->remoteVersion < 70200)
7149                 classoid = 0;
7150
7151         /*
7152          * Do binary search to find some item matching the object.
7153          */
7154         low = &comments[0];
7155         high = &comments[ncomments - 1];
7156         while (low <= high)
7157         {
7158                 middle = low + (high - low) / 2;
7159
7160                 if (classoid < middle->classoid)
7161                         high = middle - 1;
7162                 else if (classoid > middle->classoid)
7163                         low = middle + 1;
7164                 else if (objoid < middle->objoid)
7165                         high = middle - 1;
7166                 else if (objoid > middle->objoid)
7167                         low = middle + 1;
7168                 else
7169                         break;                          /* found a match */
7170         }
7171
7172         if (low > high)                         /* no matches */
7173         {
7174                 *items = NULL;
7175                 return 0;
7176         }
7177
7178         /*
7179          * Now determine how many items match the object.  The search loop
7180          * invariant still holds: only items between low and high inclusive could
7181          * match.
7182          */
7183         nmatch = 1;
7184         while (middle > low)
7185         {
7186                 if (classoid != middle[-1].classoid ||
7187                         objoid != middle[-1].objoid)
7188                         break;
7189                 middle--;
7190                 nmatch++;
7191         }
7192
7193         *items = middle;
7194
7195         middle += nmatch;
7196         while (middle <= high)
7197         {
7198                 if (classoid != middle->classoid ||
7199                         objoid != middle->objoid)
7200                         break;
7201                 middle++;
7202                 nmatch++;
7203         }
7204
7205         return nmatch;
7206 }
7207
7208 /*
7209  * collectComments --
7210  *
7211  * Construct a table of all comments available for database objects.
7212  * We used to do per-object queries for the comments, but it's much faster
7213  * to pull them all over at once, and on most databases the memory cost
7214  * isn't high.
7215  *
7216  * The table is sorted by classoid/objid/objsubid for speed in lookup.
7217  */
7218 static int
7219 collectComments(Archive *fout, CommentItem **items)
7220 {
7221         PGresult   *res;
7222         PQExpBuffer query;
7223         int                     i_description;
7224         int                     i_classoid;
7225         int                     i_objoid;
7226         int                     i_objsubid;
7227         int                     ntups;
7228         int                     i;
7229         CommentItem *comments;
7230
7231         /*
7232          * Note we do NOT change source schema here; preserve the caller's
7233          * setting, instead.
7234          */
7235
7236         query = createPQExpBuffer();
7237
7238         if (fout->remoteVersion >= 70300)
7239         {
7240                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7241                                                   "FROM pg_catalog.pg_description "
7242                                                   "ORDER BY classoid, objoid, objsubid");
7243         }
7244         else if (fout->remoteVersion >= 70200)
7245         {
7246                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7247                                                   "FROM pg_description "
7248                                                   "ORDER BY classoid, objoid, objsubid");
7249         }
7250         else
7251         {
7252                 /* Note: this will fail to find attribute comments in pre-7.2... */
7253                 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7254                                                   "FROM pg_description "
7255                                                   "ORDER BY objoid");
7256         }
7257
7258         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7259
7260         /* Construct lookup table containing OIDs in numeric form */
7261
7262         i_description = PQfnumber(res, "description");
7263         i_classoid = PQfnumber(res, "classoid");
7264         i_objoid = PQfnumber(res, "objoid");
7265         i_objsubid = PQfnumber(res, "objsubid");
7266
7267         ntups = PQntuples(res);
7268
7269         comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7270
7271         for (i = 0; i < ntups; i++)
7272         {
7273                 comments[i].descr = PQgetvalue(res, i, i_description);
7274                 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7275                 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7276                 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7277         }
7278
7279         /* Do NOT free the PGresult since we are keeping pointers into it */
7280         destroyPQExpBuffer(query);
7281
7282         *items = comments;
7283         return ntups;
7284 }
7285
7286 /*
7287  * dumpDumpableObject
7288  *
7289  * This routine and its subsidiaries are responsible for creating
7290  * ArchiveEntries (TOC objects) for each object to be dumped.
7291  */
7292 static void
7293 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7294 {
7295         switch (dobj->objType)
7296         {
7297                 case DO_NAMESPACE:
7298                         dumpNamespace(fout, (NamespaceInfo *) dobj);
7299                         break;
7300                 case DO_EXTENSION:
7301                         dumpExtension(fout, (ExtensionInfo *) dobj);
7302                         break;
7303                 case DO_TYPE:
7304                         dumpType(fout, (TypeInfo *) dobj);
7305                         break;
7306                 case DO_SHELL_TYPE:
7307                         dumpShellType(fout, (ShellTypeInfo *) dobj);
7308                         break;
7309                 case DO_FUNC:
7310                         dumpFunc(fout, (FuncInfo *) dobj);
7311                         break;
7312                 case DO_AGG:
7313                         dumpAgg(fout, (AggInfo *) dobj);
7314                         break;
7315                 case DO_OPERATOR:
7316                         dumpOpr(fout, (OprInfo *) dobj);
7317                         break;
7318                 case DO_OPCLASS:
7319                         dumpOpclass(fout, (OpclassInfo *) dobj);
7320                         break;
7321                 case DO_OPFAMILY:
7322                         dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7323                         break;
7324                 case DO_COLLATION:
7325                         dumpCollation(fout, (CollInfo *) dobj);
7326                         break;
7327                 case DO_CONVERSION:
7328                         dumpConversion(fout, (ConvInfo *) dobj);
7329                         break;
7330                 case DO_TABLE:
7331                         dumpTable(fout, (TableInfo *) dobj);
7332                         break;
7333                 case DO_ATTRDEF:
7334                         dumpAttrDef(fout, (AttrDefInfo *) dobj);
7335                         break;
7336                 case DO_INDEX:
7337                         dumpIndex(fout, (IndxInfo *) dobj);
7338                         break;
7339                 case DO_RULE:
7340                         dumpRule(fout, (RuleInfo *) dobj);
7341                         break;
7342                 case DO_TRIGGER:
7343                         dumpTrigger(fout, (TriggerInfo *) dobj);
7344                         break;
7345                 case DO_EVENT_TRIGGER:
7346                         dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
7347                         break;
7348                 case DO_CONSTRAINT:
7349                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7350                         break;
7351                 case DO_FK_CONSTRAINT:
7352                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7353                         break;
7354                 case DO_PROCLANG:
7355                         dumpProcLang(fout, (ProcLangInfo *) dobj);
7356                         break;
7357                 case DO_CAST:
7358                         dumpCast(fout, (CastInfo *) dobj);
7359                         break;
7360                 case DO_TABLE_DATA:
7361                         if (((TableDataInfo *) dobj)->tdtable->relkind == RELKIND_SEQUENCE)
7362                                 dumpSequenceData(fout, (TableDataInfo *) dobj);
7363                         else
7364                                 dumpTableData(fout, (TableDataInfo *) dobj);
7365                         break;
7366                 case DO_DUMMY_TYPE:
7367                         /* table rowtypes and array types are never dumped separately */
7368                         break;
7369                 case DO_TSPARSER:
7370                         dumpTSParser(fout, (TSParserInfo *) dobj);
7371                         break;
7372                 case DO_TSDICT:
7373                         dumpTSDictionary(fout, (TSDictInfo *) dobj);
7374                         break;
7375                 case DO_TSTEMPLATE:
7376                         dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7377                         break;
7378                 case DO_TSCONFIG:
7379                         dumpTSConfig(fout, (TSConfigInfo *) dobj);
7380                         break;
7381                 case DO_FDW:
7382                         dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7383                         break;
7384                 case DO_FOREIGN_SERVER:
7385                         dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7386                         break;
7387                 case DO_DEFAULT_ACL:
7388                         dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7389                         break;
7390                 case DO_BLOB:
7391                         dumpBlob(fout, (BlobInfo *) dobj);
7392                         break;
7393                 case DO_BLOB_DATA:
7394                         ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7395                                                  dobj->name, NULL, NULL, "",
7396                                                  false, "BLOBS", SECTION_DATA,
7397                                                  "", "", NULL,
7398                                                  NULL, 0,
7399                                                  dumpBlobs, NULL);
7400                         break;
7401                 case DO_PRE_DATA_BOUNDARY:
7402                 case DO_POST_DATA_BOUNDARY:
7403                         /* never dumped, nothing to do */
7404                         break;
7405         }
7406 }
7407
7408 /*
7409  * dumpNamespace
7410  *        writes out to fout the queries to recreate a user-defined namespace
7411  */
7412 static void
7413 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7414 {
7415         PQExpBuffer q;
7416         PQExpBuffer delq;
7417         PQExpBuffer labelq;
7418         char       *qnspname;
7419
7420         /* Skip if not to be dumped */
7421         if (!nspinfo->dobj.dump || dataOnly)
7422                 return;
7423
7424         /* don't dump dummy namespace from pre-7.3 source */
7425         if (strlen(nspinfo->dobj.name) == 0)
7426                 return;
7427
7428         q = createPQExpBuffer();
7429         delq = createPQExpBuffer();
7430         labelq = createPQExpBuffer();
7431
7432         qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7433
7434         appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7435
7436         appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7437
7438         appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7439
7440         if (binary_upgrade)
7441                 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7442
7443         ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7444                                  nspinfo->dobj.name,
7445                                  NULL, NULL,
7446                                  nspinfo->rolname,
7447                                  false, "SCHEMA", SECTION_PRE_DATA,
7448                                  q->data, delq->data, NULL,
7449                                  NULL, 0,
7450                                  NULL, NULL);
7451
7452         /* Dump Schema Comments and Security Labels */
7453         dumpComment(fout, labelq->data,
7454                                 NULL, nspinfo->rolname,
7455                                 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7456         dumpSecLabel(fout, labelq->data,
7457                                  NULL, nspinfo->rolname,
7458                                  nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7459
7460         dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7461                         qnspname, NULL, nspinfo->dobj.name, NULL,
7462                         nspinfo->rolname, nspinfo->nspacl);
7463
7464         free(qnspname);
7465
7466         destroyPQExpBuffer(q);
7467         destroyPQExpBuffer(delq);
7468         destroyPQExpBuffer(labelq);
7469 }
7470
7471 /*
7472  * dumpExtension
7473  *        writes out to fout the queries to recreate an extension
7474  */
7475 static void
7476 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7477 {
7478         PQExpBuffer q;
7479         PQExpBuffer delq;
7480         PQExpBuffer labelq;
7481         char       *qextname;
7482
7483         /* Skip if not to be dumped */
7484         if (!extinfo->dobj.dump || dataOnly)
7485                 return;
7486
7487         q = createPQExpBuffer();
7488         delq = createPQExpBuffer();
7489         labelq = createPQExpBuffer();
7490
7491         qextname = pg_strdup(fmtId(extinfo->dobj.name));
7492
7493         appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7494
7495         if (!binary_upgrade)
7496         {
7497                 /*
7498                  * In a regular dump, we use IF NOT EXISTS so that there isn't a
7499                  * problem if the extension already exists in the target database;
7500                  * this is essential for installed-by-default extensions such as
7501                  * plpgsql.
7502                  *
7503                  * In binary-upgrade mode, that doesn't work well, so instead we skip
7504                  * built-in extensions based on their OIDs; see
7505                  * selectDumpableExtension.
7506                  */
7507                 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7508                                                   qextname, fmtId(extinfo->namespace));
7509         }
7510         else
7511         {
7512                 int                     i;
7513                 int                     n;
7514
7515                 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7516
7517                 /*
7518                  *      We unconditionally create the extension, so we must drop it if it
7519                  *      exists.  This could happen if the user deleted 'plpgsql' and then
7520                  *      readded it, causing its oid to be greater than FirstNormalObjectId.
7521                  *      The FirstNormalObjectId test was kept to avoid repeatedly dropping
7522                  *      and recreating extensions like 'plpgsql'.
7523                  */
7524                 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
7525
7526                 appendPQExpBuffer(q,
7527                                                   "SELECT binary_upgrade.create_empty_extension(");
7528                 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7529                 appendPQExpBuffer(q, ", ");
7530                 appendStringLiteralAH(q, extinfo->namespace, fout);
7531                 appendPQExpBuffer(q, ", ");
7532                 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7533                 appendStringLiteralAH(q, extinfo->extversion, fout);
7534                 appendPQExpBuffer(q, ", ");
7535
7536                 /*
7537                  * Note that we're pushing extconfig (an OID array) back into
7538                  * pg_extension exactly as-is.  This is OK because pg_class OIDs are
7539                  * preserved in binary upgrade.
7540                  */
7541                 if (strlen(extinfo->extconfig) > 2)
7542                         appendStringLiteralAH(q, extinfo->extconfig, fout);
7543                 else
7544                         appendPQExpBuffer(q, "NULL");
7545                 appendPQExpBuffer(q, ", ");
7546                 if (strlen(extinfo->extcondition) > 2)
7547                         appendStringLiteralAH(q, extinfo->extcondition, fout);
7548                 else
7549                         appendPQExpBuffer(q, "NULL");
7550                 appendPQExpBuffer(q, ", ");
7551                 appendPQExpBuffer(q, "ARRAY[");
7552                 n = 0;
7553                 for (i = 0; i < extinfo->dobj.nDeps; i++)
7554                 {
7555                         DumpableObject *extobj;
7556
7557                         extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7558                         if (extobj && extobj->objType == DO_EXTENSION)
7559                         {
7560                                 if (n++ > 0)
7561                                         appendPQExpBuffer(q, ",");
7562                                 appendStringLiteralAH(q, extobj->name, fout);
7563                         }
7564                 }
7565                 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7566                 appendPQExpBuffer(q, ");\n");
7567         }
7568
7569         appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7570
7571         ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7572                                  extinfo->dobj.name,
7573                                  NULL, NULL,
7574                                  "",
7575                                  false, "EXTENSION", SECTION_PRE_DATA,
7576                                  q->data, delq->data, NULL,
7577                                  NULL, 0,
7578                                  NULL, NULL);
7579
7580         /* Dump Extension Comments and Security Labels */
7581         dumpComment(fout, labelq->data,
7582                                 NULL, "",
7583                                 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7584         dumpSecLabel(fout, labelq->data,
7585                                  NULL, "",
7586                                  extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7587
7588         free(qextname);
7589
7590         destroyPQExpBuffer(q);
7591         destroyPQExpBuffer(delq);
7592         destroyPQExpBuffer(labelq);
7593 }
7594
7595 /*
7596  * dumpType
7597  *        writes out to fout the queries to recreate a user-defined type
7598  */
7599 static void
7600 dumpType(Archive *fout, TypeInfo *tyinfo)
7601 {
7602         /* Skip if not to be dumped */
7603         if (!tyinfo->dobj.dump || dataOnly)
7604                 return;
7605
7606         /* Dump out in proper style */
7607         if (tyinfo->typtype == TYPTYPE_BASE)
7608                 dumpBaseType(fout, tyinfo);
7609         else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7610                 dumpDomain(fout, tyinfo);
7611         else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7612                 dumpCompositeType(fout, tyinfo);
7613         else if (tyinfo->typtype == TYPTYPE_ENUM)
7614                 dumpEnumType(fout, tyinfo);
7615         else if (tyinfo->typtype == TYPTYPE_RANGE)
7616                 dumpRangeType(fout, tyinfo);
7617         else
7618                 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7619                                   tyinfo->dobj.name);
7620 }
7621
7622 /*
7623  * dumpEnumType
7624  *        writes out to fout the queries to recreate a user-defined enum type
7625  */
7626 static void
7627 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7628 {
7629         PQExpBuffer q = createPQExpBuffer();
7630         PQExpBuffer delq = createPQExpBuffer();
7631         PQExpBuffer labelq = createPQExpBuffer();
7632         PQExpBuffer query = createPQExpBuffer();
7633         PGresult   *res;
7634         int                     num,
7635                                 i;
7636         Oid                     enum_oid;
7637         char       *qtypname;
7638         char       *label;
7639
7640         /* Set proper schema search path */
7641         selectSourceSchema(fout, "pg_catalog");
7642
7643         if (fout->remoteVersion >= 90100)
7644                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7645                                                   "FROM pg_catalog.pg_enum "
7646                                                   "WHERE enumtypid = '%u'"
7647                                                   "ORDER BY enumsortorder",
7648                                                   tyinfo->dobj.catId.oid);
7649         else
7650                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7651                                                   "FROM pg_catalog.pg_enum "
7652                                                   "WHERE enumtypid = '%u'"
7653                                                   "ORDER BY oid",
7654                                                   tyinfo->dobj.catId.oid);
7655
7656         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7657
7658         num = PQntuples(res);
7659
7660         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
7661
7662         /*
7663          * DROP must be fully qualified in case same name appears in pg_catalog.
7664          * CASCADE shouldn't be required here as for normal types since the I/O
7665          * functions are generic and do not get dropped.
7666          */
7667         appendPQExpBuffer(delq, "DROP TYPE %s.",
7668                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7669         appendPQExpBuffer(delq, "%s;\n",
7670                                           qtypname);
7671
7672         if (binary_upgrade)
7673                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7674                                                                                                  tyinfo->dobj.catId.oid);
7675
7676         appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7677                                           qtypname);
7678
7679         if (!binary_upgrade)
7680         {
7681                 /* Labels with server-assigned oids */
7682                 for (i = 0; i < num; i++)
7683                 {
7684                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7685                         if (i > 0)
7686                                 appendPQExpBuffer(q, ",");
7687                         appendPQExpBuffer(q, "\n    ");
7688                         appendStringLiteralAH(q, label, fout);
7689                 }
7690         }
7691
7692         appendPQExpBuffer(q, "\n);\n");
7693
7694         if (binary_upgrade)
7695         {
7696                 /* Labels with dump-assigned (preserved) oids */
7697                 for (i = 0; i < num; i++)
7698                 {
7699                         enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7700                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7701
7702                         if (i == 0)
7703                                 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7704                         appendPQExpBuffer(q,
7705                                                           "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7706                                                           enum_oid);
7707                         appendPQExpBuffer(q, "ALTER TYPE %s.",
7708                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7709                         appendPQExpBuffer(q, "%s ADD VALUE ",
7710                                                           qtypname);
7711                         appendStringLiteralAH(q, label, fout);
7712                         appendPQExpBuffer(q, ";\n\n");
7713                 }
7714         }
7715
7716         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
7717
7718         if (binary_upgrade)
7719                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7720
7721         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7722                                  tyinfo->dobj.name,
7723                                  tyinfo->dobj.namespace->dobj.name,
7724                                  NULL,
7725                                  tyinfo->rolname, false,
7726                                  "TYPE", SECTION_PRE_DATA,
7727                                  q->data, delq->data, NULL,
7728                                  NULL, 0,
7729                                  NULL, NULL);
7730
7731         /* Dump Type Comments and Security Labels */
7732         dumpComment(fout, labelq->data,
7733                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7734                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7735         dumpSecLabel(fout, labelq->data,
7736                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7737                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7738
7739         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
7740                         qtypname, NULL, tyinfo->dobj.name,
7741                         tyinfo->dobj.namespace->dobj.name,
7742                         tyinfo->rolname, tyinfo->typacl);
7743
7744         PQclear(res);
7745         destroyPQExpBuffer(q);
7746         destroyPQExpBuffer(delq);
7747         destroyPQExpBuffer(labelq);
7748         destroyPQExpBuffer(query);
7749 }
7750
7751 /*
7752  * dumpRangeType
7753  *        writes out to fout the queries to recreate a user-defined range type
7754  */
7755 static void
7756 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7757 {
7758         PQExpBuffer q = createPQExpBuffer();
7759         PQExpBuffer delq = createPQExpBuffer();
7760         PQExpBuffer labelq = createPQExpBuffer();
7761         PQExpBuffer query = createPQExpBuffer();
7762         PGresult   *res;
7763         Oid                     collationOid;
7764         char       *qtypname;
7765         char       *procname;
7766
7767         /*
7768          * select appropriate schema to ensure names in CREATE are properly
7769          * qualified
7770          */
7771         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7772
7773         appendPQExpBuffer(query,
7774                         "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7775                                           "opc.opcname AS opcname, "
7776                                           "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7777                                           "  WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7778                                           "opc.opcdefault, "
7779                                           "CASE WHEN rngcollation = st.typcollation THEN 0 "
7780                                           "     ELSE rngcollation END AS collation, "
7781                                           "rngcanonical, rngsubdiff "
7782                                           "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7783                                           "     pg_catalog.pg_opclass opc "
7784                                           "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7785                                           "rngtypid = '%u'",
7786                                           tyinfo->dobj.catId.oid);
7787
7788         res = ExecuteSqlQueryForSingleRow(fout, query->data);
7789
7790         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
7791
7792         /*
7793          * DROP must be fully qualified in case same name appears in pg_catalog.
7794          * CASCADE shouldn't be required here as for normal types since the I/O
7795          * functions are generic and do not get dropped.
7796          */
7797         appendPQExpBuffer(delq, "DROP TYPE %s.",
7798                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7799         appendPQExpBuffer(delq, "%s;\n",
7800                                           qtypname);
7801
7802         if (binary_upgrade)
7803                 binary_upgrade_set_type_oids_by_type_oid(fout,
7804                                                                                                  q, tyinfo->dobj.catId.oid);
7805
7806         appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7807                                           qtypname);
7808
7809         appendPQExpBuffer(q, "\n    subtype = %s",
7810                                           PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7811
7812         /* print subtype_opclass only if not default for subtype */
7813         if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7814         {
7815                 char       *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7816                 char       *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7817
7818                 /* always schema-qualify, don't try to be smart */
7819                 appendPQExpBuffer(q, ",\n    subtype_opclass = %s.",
7820                                                   fmtId(nspname));
7821                 appendPQExpBuffer(q, "%s", fmtId(opcname));
7822         }
7823
7824         collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
7825         if (OidIsValid(collationOid))
7826         {
7827                 CollInfo   *coll = findCollationByOid(collationOid);
7828
7829                 if (coll)
7830                 {
7831                         /* always schema-qualify, don't try to be smart */
7832                         appendPQExpBuffer(q, ",\n    collation = %s.",
7833                                                           fmtId(coll->dobj.namespace->dobj.name));
7834                         appendPQExpBuffer(q, "%s",
7835                                                           fmtId(coll->dobj.name));
7836                 }
7837         }
7838
7839         procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
7840         if (strcmp(procname, "-") != 0)
7841                 appendPQExpBuffer(q, ",\n    canonical = %s", procname);
7842
7843         procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
7844         if (strcmp(procname, "-") != 0)
7845                 appendPQExpBuffer(q, ",\n    subtype_diff = %s", procname);
7846
7847         appendPQExpBuffer(q, "\n);\n");
7848
7849         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
7850
7851         if (binary_upgrade)
7852                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7853
7854         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7855                                  tyinfo->dobj.name,
7856                                  tyinfo->dobj.namespace->dobj.name,
7857                                  NULL,
7858                                  tyinfo->rolname, false,
7859                                  "TYPE", SECTION_PRE_DATA,
7860                                  q->data, delq->data, NULL,
7861                                  NULL, 0,
7862                                  NULL, NULL);
7863
7864         /* Dump Type Comments and Security Labels */
7865         dumpComment(fout, labelq->data,
7866                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7867                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7868         dumpSecLabel(fout, labelq->data,
7869                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7870                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7871
7872         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
7873                         qtypname, NULL, tyinfo->dobj.name,
7874                         tyinfo->dobj.namespace->dobj.name,
7875                         tyinfo->rolname, tyinfo->typacl);
7876
7877         PQclear(res);
7878         destroyPQExpBuffer(q);
7879         destroyPQExpBuffer(delq);
7880         destroyPQExpBuffer(labelq);
7881         destroyPQExpBuffer(query);
7882 }
7883
7884 /*
7885  * dumpBaseType
7886  *        writes out to fout the queries to recreate a user-defined base type
7887  */
7888 static void
7889 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
7890 {
7891         PQExpBuffer q = createPQExpBuffer();
7892         PQExpBuffer delq = createPQExpBuffer();
7893         PQExpBuffer labelq = createPQExpBuffer();
7894         PQExpBuffer query = createPQExpBuffer();
7895         PGresult   *res;
7896         char       *qtypname;
7897         char       *typlen;
7898         char       *typinput;
7899         char       *typoutput;
7900         char       *typreceive;
7901         char       *typsend;
7902         char       *typmodin;
7903         char       *typmodout;
7904         char       *typanalyze;
7905         Oid                     typreceiveoid;
7906         Oid                     typsendoid;
7907         Oid                     typmodinoid;
7908         Oid                     typmodoutoid;
7909         Oid                     typanalyzeoid;
7910         char       *typcategory;
7911         char       *typispreferred;
7912         char       *typdelim;
7913         char       *typbyval;
7914         char       *typalign;
7915         char       *typstorage;
7916         char       *typcollatable;
7917         char       *typdefault;
7918         bool            typdefault_is_literal = false;
7919
7920         /* Set proper schema search path so regproc references list correctly */
7921         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7922
7923         /* Fetch type-specific details */
7924         if (fout->remoteVersion >= 90100)
7925         {
7926                 appendPQExpBuffer(query, "SELECT typlen, "
7927                                                   "typinput, typoutput, typreceive, typsend, "
7928                                                   "typmodin, typmodout, typanalyze, "
7929                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7930                                                   "typsend::pg_catalog.oid AS typsendoid, "
7931                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7932                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7933                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7934                                                   "typcategory, typispreferred, "
7935                                                   "typdelim, typbyval, typalign, typstorage, "
7936                                                   "(typcollation <> 0) AS typcollatable, "
7937                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7938                                                   "FROM pg_catalog.pg_type "
7939                                                   "WHERE oid = '%u'::pg_catalog.oid",
7940                                                   tyinfo->dobj.catId.oid);
7941         }
7942         else if (fout->remoteVersion >= 80400)
7943         {
7944                 appendPQExpBuffer(query, "SELECT typlen, "
7945                                                   "typinput, typoutput, typreceive, typsend, "
7946                                                   "typmodin, typmodout, typanalyze, "
7947                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7948                                                   "typsend::pg_catalog.oid AS typsendoid, "
7949                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7950                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7951                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7952                                                   "typcategory, typispreferred, "
7953                                                   "typdelim, typbyval, typalign, typstorage, "
7954                                                   "false AS typcollatable, "
7955                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7956                                                   "FROM pg_catalog.pg_type "
7957                                                   "WHERE oid = '%u'::pg_catalog.oid",
7958                                                   tyinfo->dobj.catId.oid);
7959         }
7960         else if (fout->remoteVersion >= 80300)
7961         {
7962                 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
7963                 appendPQExpBuffer(query, "SELECT typlen, "
7964                                                   "typinput, typoutput, typreceive, typsend, "
7965                                                   "typmodin, typmodout, typanalyze, "
7966                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7967                                                   "typsend::pg_catalog.oid AS typsendoid, "
7968                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7969                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7970                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7971                                                   "'U' AS typcategory, false AS typispreferred, "
7972                                                   "typdelim, typbyval, typalign, typstorage, "
7973                                                   "false AS typcollatable, "
7974                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7975                                                   "FROM pg_catalog.pg_type "
7976                                                   "WHERE oid = '%u'::pg_catalog.oid",
7977                                                   tyinfo->dobj.catId.oid);
7978         }
7979         else if (fout->remoteVersion >= 80000)
7980         {
7981                 appendPQExpBuffer(query, "SELECT typlen, "
7982                                                   "typinput, typoutput, typreceive, typsend, "
7983                                                   "'-' AS typmodin, '-' AS typmodout, "
7984                                                   "typanalyze, "
7985                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7986                                                   "typsend::pg_catalog.oid AS typsendoid, "
7987                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7988                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7989                                                   "'U' AS typcategory, false AS typispreferred, "
7990                                                   "typdelim, typbyval, typalign, typstorage, "
7991                                                   "false AS typcollatable, "
7992                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7993                                                   "FROM pg_catalog.pg_type "
7994                                                   "WHERE oid = '%u'::pg_catalog.oid",
7995                                                   tyinfo->dobj.catId.oid);
7996         }
7997         else if (fout->remoteVersion >= 70400)
7998         {
7999                 appendPQExpBuffer(query, "SELECT typlen, "
8000                                                   "typinput, typoutput, typreceive, typsend, "
8001                                                   "'-' AS typmodin, '-' AS typmodout, "
8002                                                   "'-' AS typanalyze, "
8003                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
8004                                                   "typsend::pg_catalog.oid AS typsendoid, "
8005                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8006                                                   "0 AS typanalyzeoid, "
8007                                                   "'U' AS typcategory, false AS typispreferred, "
8008                                                   "typdelim, typbyval, typalign, typstorage, "
8009                                                   "false AS typcollatable, "
8010                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8011                                                   "FROM pg_catalog.pg_type "
8012                                                   "WHERE oid = '%u'::pg_catalog.oid",
8013                                                   tyinfo->dobj.catId.oid);
8014         }
8015         else if (fout->remoteVersion >= 70300)
8016         {
8017                 appendPQExpBuffer(query, "SELECT typlen, "
8018                                                   "typinput, typoutput, "
8019                                                   "'-' AS typreceive, '-' AS typsend, "
8020                                                   "'-' AS typmodin, '-' AS typmodout, "
8021                                                   "'-' AS typanalyze, "
8022                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
8023                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8024                                                   "0 AS typanalyzeoid, "
8025                                                   "'U' AS typcategory, false AS typispreferred, "
8026                                                   "typdelim, typbyval, typalign, typstorage, "
8027                                                   "false AS typcollatable, "
8028                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8029                                                   "FROM pg_catalog.pg_type "
8030                                                   "WHERE oid = '%u'::pg_catalog.oid",
8031                                                   tyinfo->dobj.catId.oid);
8032         }
8033         else if (fout->remoteVersion >= 70200)
8034         {
8035                 /*
8036                  * Note: although pre-7.3 catalogs contain typreceive and typsend,
8037                  * ignore them because they are not right.
8038                  */
8039                 appendPQExpBuffer(query, "SELECT typlen, "
8040                                                   "typinput, typoutput, "
8041                                                   "'-' AS typreceive, '-' AS typsend, "
8042                                                   "'-' AS typmodin, '-' AS typmodout, "
8043                                                   "'-' AS typanalyze, "
8044                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
8045                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8046                                                   "0 AS typanalyzeoid, "
8047                                                   "'U' AS typcategory, false AS typispreferred, "
8048                                                   "typdelim, typbyval, typalign, typstorage, "
8049                                                   "false AS typcollatable, "
8050                                                   "NULL AS typdefaultbin, typdefault "
8051                                                   "FROM pg_type "
8052                                                   "WHERE oid = '%u'::oid",
8053                                                   tyinfo->dobj.catId.oid);
8054         }
8055         else if (fout->remoteVersion >= 70100)
8056         {
8057                 /*
8058                  * Ignore pre-7.2 typdefault; the field exists but has an unusable
8059                  * representation.
8060                  */
8061                 appendPQExpBuffer(query, "SELECT typlen, "
8062                                                   "typinput, typoutput, "
8063                                                   "'-' AS typreceive, '-' AS typsend, "
8064                                                   "'-' AS typmodin, '-' AS typmodout, "
8065                                                   "'-' AS typanalyze, "
8066                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
8067                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8068                                                   "0 AS typanalyzeoid, "
8069                                                   "'U' AS typcategory, false AS typispreferred, "
8070                                                   "typdelim, typbyval, typalign, typstorage, "
8071                                                   "false AS typcollatable, "
8072                                                   "NULL AS typdefaultbin, NULL AS typdefault "
8073                                                   "FROM pg_type "
8074                                                   "WHERE oid = '%u'::oid",
8075                                                   tyinfo->dobj.catId.oid);
8076         }
8077         else
8078         {
8079                 appendPQExpBuffer(query, "SELECT typlen, "
8080                                                   "typinput, typoutput, "
8081                                                   "'-' AS typreceive, '-' AS typsend, "
8082                                                   "'-' AS typmodin, '-' AS typmodout, "
8083                                                   "'-' AS typanalyze, "
8084                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
8085                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
8086                                                   "0 AS typanalyzeoid, "
8087                                                   "'U' AS typcategory, false AS typispreferred, "
8088                                                   "typdelim, typbyval, typalign, "
8089                                                   "'p'::char AS typstorage, "
8090                                                   "false AS typcollatable, "
8091                                                   "NULL AS typdefaultbin, NULL AS typdefault "
8092                                                   "FROM pg_type "
8093                                                   "WHERE oid = '%u'::oid",
8094                                                   tyinfo->dobj.catId.oid);
8095         }
8096
8097         res = ExecuteSqlQueryForSingleRow(fout, query->data);
8098
8099         typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
8100         typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
8101         typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
8102         typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
8103         typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
8104         typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
8105         typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
8106         typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
8107         typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
8108         typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
8109         typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
8110         typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
8111         typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
8112         typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
8113         typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
8114         typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
8115         typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
8116         typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
8117         typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
8118         typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
8119         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8120                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8121         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8122         {
8123                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8124                 typdefault_is_literal = true;   /* it needs quotes */
8125         }
8126         else
8127                 typdefault = NULL;
8128
8129         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8130
8131         /*
8132          * DROP must be fully qualified in case same name appears in pg_catalog.
8133          * The reason we include CASCADE is that the circular dependency between
8134          * the type and its I/O functions makes it impossible to drop the type any
8135          * other way.
8136          */
8137         appendPQExpBuffer(delq, "DROP TYPE %s.",
8138                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8139         appendPQExpBuffer(delq, "%s CASCADE;\n",
8140                                           qtypname);
8141
8142         /* We might already have a shell type, but setting pg_type_oid is harmless */
8143         if (binary_upgrade)
8144                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8145                                                                                                  tyinfo->dobj.catId.oid);
8146
8147         appendPQExpBuffer(q,
8148                                           "CREATE TYPE %s (\n"
8149                                           "    INTERNALLENGTH = %s",
8150                                           qtypname,
8151                                           (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
8152
8153         if (fout->remoteVersion >= 70300)
8154         {
8155                 /* regproc result is correctly quoted as of 7.3 */
8156                 appendPQExpBuffer(q, ",\n    INPUT = %s", typinput);
8157                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", typoutput);
8158                 if (OidIsValid(typreceiveoid))
8159                         appendPQExpBuffer(q, ",\n    RECEIVE = %s", typreceive);
8160                 if (OidIsValid(typsendoid))
8161                         appendPQExpBuffer(q, ",\n    SEND = %s", typsend);
8162                 if (OidIsValid(typmodinoid))
8163                         appendPQExpBuffer(q, ",\n    TYPMOD_IN = %s", typmodin);
8164                 if (OidIsValid(typmodoutoid))
8165                         appendPQExpBuffer(q, ",\n    TYPMOD_OUT = %s", typmodout);
8166                 if (OidIsValid(typanalyzeoid))
8167                         appendPQExpBuffer(q, ",\n    ANALYZE = %s", typanalyze);
8168         }
8169         else
8170         {
8171                 /* regproc delivers an unquoted name before 7.3 */
8172                 /* cannot combine these because fmtId uses static result area */
8173                 appendPQExpBuffer(q, ",\n    INPUT = %s", fmtId(typinput));
8174                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", fmtId(typoutput));
8175                 /* receive/send/typmodin/typmodout/analyze need not be printed */
8176         }
8177
8178         if (strcmp(typcollatable, "t") == 0)
8179                 appendPQExpBuffer(q, ",\n    COLLATABLE = true");
8180
8181         if (typdefault != NULL)
8182         {
8183                 appendPQExpBuffer(q, ",\n    DEFAULT = ");
8184                 if (typdefault_is_literal)
8185                         appendStringLiteralAH(q, typdefault, fout);
8186                 else
8187                         appendPQExpBufferStr(q, typdefault);
8188         }
8189
8190         if (OidIsValid(tyinfo->typelem))
8191         {
8192                 char       *elemType;
8193
8194                 /* reselect schema in case changed by function dump */
8195                 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8196                 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
8197                 appendPQExpBuffer(q, ",\n    ELEMENT = %s", elemType);
8198                 free(elemType);
8199         }
8200
8201         if (strcmp(typcategory, "U") != 0)
8202         {
8203                 appendPQExpBuffer(q, ",\n    CATEGORY = ");
8204                 appendStringLiteralAH(q, typcategory, fout);
8205         }
8206
8207         if (strcmp(typispreferred, "t") == 0)
8208                 appendPQExpBuffer(q, ",\n    PREFERRED = true");
8209
8210         if (typdelim && strcmp(typdelim, ",") != 0)
8211         {
8212                 appendPQExpBuffer(q, ",\n    DELIMITER = ");
8213                 appendStringLiteralAH(q, typdelim, fout);
8214         }
8215
8216         if (strcmp(typalign, "c") == 0)
8217                 appendPQExpBuffer(q, ",\n    ALIGNMENT = char");
8218         else if (strcmp(typalign, "s") == 0)
8219                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int2");
8220         else if (strcmp(typalign, "i") == 0)
8221                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int4");
8222         else if (strcmp(typalign, "d") == 0)
8223                 appendPQExpBuffer(q, ",\n    ALIGNMENT = double");
8224
8225         if (strcmp(typstorage, "p") == 0)
8226                 appendPQExpBuffer(q, ",\n    STORAGE = plain");
8227         else if (strcmp(typstorage, "e") == 0)
8228                 appendPQExpBuffer(q, ",\n    STORAGE = external");
8229         else if (strcmp(typstorage, "x") == 0)
8230                 appendPQExpBuffer(q, ",\n    STORAGE = extended");
8231         else if (strcmp(typstorage, "m") == 0)
8232                 appendPQExpBuffer(q, ",\n    STORAGE = main");
8233
8234         if (strcmp(typbyval, "t") == 0)
8235                 appendPQExpBuffer(q, ",\n    PASSEDBYVALUE");
8236
8237         appendPQExpBuffer(q, "\n);\n");
8238
8239         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8240
8241         if (binary_upgrade)
8242                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8243
8244         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8245                                  tyinfo->dobj.name,
8246                                  tyinfo->dobj.namespace->dobj.name,
8247                                  NULL,
8248                                  tyinfo->rolname, false,
8249                                  "TYPE", SECTION_PRE_DATA,
8250                                  q->data, delq->data, NULL,
8251                                  NULL, 0,
8252                                  NULL, NULL);
8253
8254         /* Dump Type Comments and Security Labels */
8255         dumpComment(fout, labelq->data,
8256                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8257                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8258         dumpSecLabel(fout, labelq->data,
8259                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8260                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8261
8262         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8263                         qtypname, NULL, tyinfo->dobj.name,
8264                         tyinfo->dobj.namespace->dobj.name,
8265                         tyinfo->rolname, tyinfo->typacl);
8266
8267         PQclear(res);
8268         destroyPQExpBuffer(q);
8269         destroyPQExpBuffer(delq);
8270         destroyPQExpBuffer(labelq);
8271         destroyPQExpBuffer(query);
8272 }
8273
8274 /*
8275  * dumpDomain
8276  *        writes out to fout the queries to recreate a user-defined domain
8277  */
8278 static void
8279 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8280 {
8281         PQExpBuffer q = createPQExpBuffer();
8282         PQExpBuffer delq = createPQExpBuffer();
8283         PQExpBuffer labelq = createPQExpBuffer();
8284         PQExpBuffer query = createPQExpBuffer();
8285         PGresult   *res;
8286         int                     i;
8287         char       *qtypname;
8288         char       *typnotnull;
8289         char       *typdefn;
8290         char       *typdefault;
8291         Oid                     typcollation;
8292         bool            typdefault_is_literal = false;
8293
8294         /* Set proper schema search path so type references list correctly */
8295         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8296
8297         /* Fetch domain specific details */
8298         if (fout->remoteVersion >= 90100)
8299         {
8300                 /* typcollation is new in 9.1 */
8301                 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8302                         "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8303                                                   "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8304                                                   "t.typdefault, "
8305                                                   "CASE WHEN t.typcollation <> u.typcollation "
8306                                                   "THEN t.typcollation ELSE 0 END AS typcollation "
8307                                                   "FROM pg_catalog.pg_type t "
8308                                  "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8309                                                   "WHERE t.oid = '%u'::pg_catalog.oid",
8310                                                   tyinfo->dobj.catId.oid);
8311         }
8312         else
8313         {
8314                 /* We assume here that remoteVersion must be at least 70300 */
8315                 appendPQExpBuffer(query, "SELECT typnotnull, "
8316                                 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8317                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8318                                                   "typdefault, 0 AS typcollation "
8319                                                   "FROM pg_catalog.pg_type "
8320                                                   "WHERE oid = '%u'::pg_catalog.oid",
8321                                                   tyinfo->dobj.catId.oid);
8322         }
8323
8324         res = ExecuteSqlQueryForSingleRow(fout, query->data);
8325
8326         typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8327         typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8328         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8329                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8330         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8331         {
8332                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8333                 typdefault_is_literal = true;   /* it needs quotes */
8334         }
8335         else
8336                 typdefault = NULL;
8337         typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8338
8339         if (binary_upgrade)
8340                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8341                                                                                                  tyinfo->dobj.catId.oid);
8342
8343         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8344
8345         appendPQExpBuffer(q,
8346                                           "CREATE DOMAIN %s AS %s",
8347                                           qtypname,
8348                                           typdefn);
8349
8350         /* Print collation only if different from base type's collation */
8351         if (OidIsValid(typcollation))
8352         {
8353                 CollInfo   *coll;
8354
8355                 coll = findCollationByOid(typcollation);
8356                 if (coll)
8357                 {
8358                         /* always schema-qualify, don't try to be smart */
8359                         appendPQExpBuffer(q, " COLLATE %s.",
8360                                                           fmtId(coll->dobj.namespace->dobj.name));
8361                         appendPQExpBuffer(q, "%s",
8362                                                           fmtId(coll->dobj.name));
8363                 }
8364         }
8365
8366         if (typnotnull[0] == 't')
8367                 appendPQExpBuffer(q, " NOT NULL");
8368
8369         if (typdefault != NULL)
8370         {
8371                 appendPQExpBuffer(q, " DEFAULT ");
8372                 if (typdefault_is_literal)
8373                         appendStringLiteralAH(q, typdefault, fout);
8374                 else
8375                         appendPQExpBufferStr(q, typdefault);
8376         }
8377
8378         PQclear(res);
8379
8380         /*
8381          * Add any CHECK constraints for the domain
8382          */
8383         for (i = 0; i < tyinfo->nDomChecks; i++)
8384         {
8385                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8386
8387                 if (!domcheck->separate)
8388                         appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8389                                                           fmtId(domcheck->dobj.name), domcheck->condef);
8390         }
8391
8392         appendPQExpBuffer(q, ";\n");
8393
8394         /*
8395          * DROP must be fully qualified in case same name appears in pg_catalog
8396          */
8397         appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8398                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8399         appendPQExpBuffer(delq, "%s;\n",
8400                                           qtypname);
8401
8402         appendPQExpBuffer(labelq, "DOMAIN %s", qtypname);
8403
8404         if (binary_upgrade)
8405                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8406
8407         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8408                                  tyinfo->dobj.name,
8409                                  tyinfo->dobj.namespace->dobj.name,
8410                                  NULL,
8411                                  tyinfo->rolname, false,
8412                                  "DOMAIN", SECTION_PRE_DATA,
8413                                  q->data, delq->data, NULL,
8414                                  NULL, 0,
8415                                  NULL, NULL);
8416
8417         /* Dump Domain Comments and Security Labels */
8418         dumpComment(fout, labelq->data,
8419                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8420                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8421         dumpSecLabel(fout, labelq->data,
8422                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8423                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8424
8425         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8426                         qtypname, NULL, tyinfo->dobj.name,
8427                         tyinfo->dobj.namespace->dobj.name,
8428                         tyinfo->rolname, tyinfo->typacl);
8429
8430         destroyPQExpBuffer(q);
8431         destroyPQExpBuffer(delq);
8432         destroyPQExpBuffer(labelq);
8433         destroyPQExpBuffer(query);
8434 }
8435
8436 /*
8437  * dumpCompositeType
8438  *        writes out to fout the queries to recreate a user-defined stand-alone
8439  *        composite type
8440  */
8441 static void
8442 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8443 {
8444         PQExpBuffer q = createPQExpBuffer();
8445         PQExpBuffer dropped = createPQExpBuffer();
8446         PQExpBuffer delq = createPQExpBuffer();
8447         PQExpBuffer labelq = createPQExpBuffer();
8448         PQExpBuffer query = createPQExpBuffer();
8449         PGresult   *res;
8450         char       *qtypname;
8451         int                     ntups;
8452         int                     i_attname;
8453         int                     i_atttypdefn;
8454         int                     i_attlen;
8455         int                     i_attalign;
8456         int                     i_attisdropped;
8457         int                     i_attcollation;
8458         int                     i_typrelid;
8459         int                     i;
8460         int                     actual_atts;
8461
8462         /* Set proper schema search path so type references list correctly */
8463         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8464
8465         /* Fetch type specific details */
8466         if (fout->remoteVersion >= 90100)
8467         {
8468                 /*
8469                  * attcollation is new in 9.1.  Since we only want to dump COLLATE
8470                  * clauses for attributes whose collation is different from their
8471                  * type's default, we use a CASE here to suppress uninteresting
8472                  * attcollations cheaply.  atttypid will be 0 for dropped columns;
8473                  * collation does not matter for those.
8474                  */
8475                 appendPQExpBuffer(query, "SELECT a.attname, "
8476                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8477                                                   "a.attlen, a.attalign, a.attisdropped, "
8478                                                   "CASE WHEN a.attcollation <> at.typcollation "
8479                                                   "THEN a.attcollation ELSE 0 END AS attcollation, "
8480                                                   "ct.typrelid "
8481                                                   "FROM pg_catalog.pg_type ct "
8482                                 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8483                                         "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8484                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8485                                                   "ORDER BY a.attnum ",
8486                                                   tyinfo->dobj.catId.oid);
8487         }
8488         else
8489         {
8490                 /*
8491                  * We assume here that remoteVersion must be at least 70300.  Since
8492                  * ALTER TYPE could not drop columns until 9.1, attisdropped should
8493                  * always be false.
8494                  */
8495                 appendPQExpBuffer(query, "SELECT a.attname, "
8496                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8497                                                   "a.attlen, a.attalign, a.attisdropped, "
8498                                                   "0 AS attcollation, "
8499                                                   "ct.typrelid "
8500                                          "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8501                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8502                                                   "AND a.attrelid = ct.typrelid "
8503                                                   "ORDER BY a.attnum ",
8504                                                   tyinfo->dobj.catId.oid);
8505         }
8506
8507         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8508
8509         ntups = PQntuples(res);
8510
8511         i_attname = PQfnumber(res, "attname");
8512         i_atttypdefn = PQfnumber(res, "atttypdefn");
8513         i_attlen = PQfnumber(res, "attlen");
8514         i_attalign = PQfnumber(res, "attalign");
8515         i_attisdropped = PQfnumber(res, "attisdropped");
8516         i_attcollation = PQfnumber(res, "attcollation");
8517         i_typrelid = PQfnumber(res, "typrelid");
8518
8519         if (binary_upgrade)
8520         {
8521                 Oid                     typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8522
8523                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8524                                                                                                  tyinfo->dobj.catId.oid);
8525                 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8526         }
8527
8528         qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8529
8530         appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8531                                           qtypname);
8532
8533         actual_atts = 0;
8534         for (i = 0; i < ntups; i++)
8535         {
8536                 char       *attname;
8537                 char       *atttypdefn;
8538                 char       *attlen;
8539                 char       *attalign;
8540                 bool            attisdropped;
8541                 Oid                     attcollation;
8542
8543                 attname = PQgetvalue(res, i, i_attname);
8544                 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8545                 attlen = PQgetvalue(res, i, i_attlen);
8546                 attalign = PQgetvalue(res, i, i_attalign);
8547                 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8548                 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8549
8550                 if (attisdropped && !binary_upgrade)
8551                         continue;
8552
8553                 /* Format properly if not first attr */
8554                 if (actual_atts++ > 0)
8555                         appendPQExpBuffer(q, ",");
8556                 appendPQExpBuffer(q, "\n\t");
8557
8558                 if (!attisdropped)
8559                 {
8560                         appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8561
8562                         /* Add collation if not default for the column type */
8563                         if (OidIsValid(attcollation))
8564                         {
8565                                 CollInfo   *coll;
8566
8567                                 coll = findCollationByOid(attcollation);
8568                                 if (coll)
8569                                 {
8570                                         /* always schema-qualify, don't try to be smart */
8571                                         appendPQExpBuffer(q, " COLLATE %s.",
8572                                                                           fmtId(coll->dobj.namespace->dobj.name));
8573                                         appendPQExpBuffer(q, "%s",
8574                                                                           fmtId(coll->dobj.name));
8575                                 }
8576                         }
8577                 }
8578                 else
8579                 {
8580                         /*
8581                          * This is a dropped attribute and we're in binary_upgrade mode.
8582                          * Insert a placeholder for it in the CREATE TYPE command, and set
8583                          * length and alignment with direct UPDATE to the catalogs
8584                          * afterwards. See similar code in dumpTableSchema().
8585                          */
8586                         appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8587
8588                         /* stash separately for insertion after the CREATE TYPE */
8589                         appendPQExpBuffer(dropped,
8590                                           "\n-- For binary upgrade, recreate dropped column.\n");
8591                         appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8592                                                           "SET attlen = %s, "
8593                                                           "attalign = '%s', attbyval = false\n"
8594                                                           "WHERE attname = ", attlen, attalign);
8595                         appendStringLiteralAH(dropped, attname, fout);
8596                         appendPQExpBuffer(dropped, "\n  AND attrelid = ");
8597                         appendStringLiteralAH(dropped, qtypname, fout);
8598                         appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8599
8600                         appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8601                                                           qtypname);
8602                         appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8603                                                           fmtId(attname));
8604                 }
8605         }
8606         appendPQExpBuffer(q, "\n);\n");
8607         appendPQExpBufferStr(q, dropped->data);
8608
8609         /*
8610          * DROP must be fully qualified in case same name appears in pg_catalog
8611          */
8612         appendPQExpBuffer(delq, "DROP TYPE %s.",
8613                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8614         appendPQExpBuffer(delq, "%s;\n",
8615                                           qtypname);
8616
8617         appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8618
8619         if (binary_upgrade)
8620                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8621
8622         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8623                                  tyinfo->dobj.name,
8624                                  tyinfo->dobj.namespace->dobj.name,
8625                                  NULL,
8626                                  tyinfo->rolname, false,
8627                                  "TYPE", SECTION_PRE_DATA,
8628                                  q->data, delq->data, NULL,
8629                                  NULL, 0,
8630                                  NULL, NULL);
8631
8632
8633         /* Dump Type Comments and Security Labels */
8634         dumpComment(fout, labelq->data,
8635                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8636                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8637         dumpSecLabel(fout, labelq->data,
8638                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8639                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8640
8641         dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8642                         qtypname, NULL, tyinfo->dobj.name,
8643                         tyinfo->dobj.namespace->dobj.name,
8644                         tyinfo->rolname, tyinfo->typacl);
8645
8646         PQclear(res);
8647         destroyPQExpBuffer(q);
8648         destroyPQExpBuffer(dropped);
8649         destroyPQExpBuffer(delq);
8650         destroyPQExpBuffer(labelq);
8651         destroyPQExpBuffer(query);
8652
8653         /* Dump any per-column comments */
8654         dumpCompositeTypeColComments(fout, tyinfo);
8655 }
8656
8657 /*
8658  * dumpCompositeTypeColComments
8659  *        writes out to fout the queries to recreate comments on the columns of
8660  *        a user-defined stand-alone composite type
8661  */
8662 static void
8663 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8664 {
8665         CommentItem *comments;
8666         int                     ncomments;
8667         PGresult   *res;
8668         PQExpBuffer query;
8669         PQExpBuffer target;
8670         Oid                     pgClassOid;
8671         int                     i;
8672         int                     ntups;
8673         int                     i_attname;
8674         int                     i_attnum;
8675
8676         query = createPQExpBuffer();
8677
8678         /* We assume here that remoteVersion must be at least 70300 */
8679         appendPQExpBuffer(query,
8680                                           "SELECT c.tableoid, a.attname, a.attnum "
8681                                           "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8682                                           "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8683                                           "  AND NOT a.attisdropped "
8684                                           "ORDER BY a.attnum ",
8685                                           tyinfo->typrelid);
8686
8687         /* Fetch column attnames */
8688         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8689
8690         ntups = PQntuples(res);
8691         if (ntups < 1)
8692         {
8693                 PQclear(res);
8694                 destroyPQExpBuffer(query);
8695                 return;
8696         }
8697
8698         pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8699
8700         /* Search for comments associated with type's pg_class OID */
8701         ncomments = findComments(fout,
8702                                                          pgClassOid,
8703                                                          tyinfo->typrelid,
8704                                                          &comments);
8705
8706         /* If no comments exist, we're done */
8707         if (ncomments <= 0)
8708         {
8709                 PQclear(res);
8710                 destroyPQExpBuffer(query);
8711                 return;
8712         }
8713
8714         /* Build COMMENT ON statements */
8715         target = createPQExpBuffer();
8716
8717         i_attnum = PQfnumber(res, "attnum");
8718         i_attname = PQfnumber(res, "attname");
8719         while (ncomments > 0)
8720         {
8721                 const char *attname;
8722
8723                 attname = NULL;
8724                 for (i = 0; i < ntups; i++)
8725                 {
8726                         if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8727                         {
8728                                 attname = PQgetvalue(res, i, i_attname);
8729                                 break;
8730                         }
8731                 }
8732                 if (attname)                    /* just in case we don't find it */
8733                 {
8734                         const char *descr = comments->descr;
8735
8736                         resetPQExpBuffer(target);
8737                         appendPQExpBuffer(target, "COLUMN %s.",
8738                                                           fmtId(tyinfo->dobj.name));
8739                         appendPQExpBuffer(target, "%s",
8740                                                           fmtId(attname));
8741
8742                         resetPQExpBuffer(query);
8743                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8744                         appendStringLiteralAH(query, descr, fout);
8745                         appendPQExpBuffer(query, ";\n");
8746
8747                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
8748                                                  target->data,
8749                                                  tyinfo->dobj.namespace->dobj.name,
8750                                                  NULL, tyinfo->rolname,
8751                                                  false, "COMMENT", SECTION_NONE,
8752                                                  query->data, "", NULL,
8753                                                  &(tyinfo->dobj.dumpId), 1,
8754                                                  NULL, NULL);
8755                 }
8756
8757                 comments++;
8758                 ncomments--;
8759         }
8760
8761         PQclear(res);
8762         destroyPQExpBuffer(query);
8763         destroyPQExpBuffer(target);
8764 }
8765
8766 /*
8767  * dumpShellType
8768  *        writes out to fout the queries to create a shell type
8769  *
8770  * We dump a shell definition in advance of the I/O functions for the type.
8771  */
8772 static void
8773 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8774 {
8775         PQExpBuffer q;
8776
8777         /* Skip if not to be dumped */
8778         if (!stinfo->dobj.dump || dataOnly)
8779                 return;
8780
8781         q = createPQExpBuffer();
8782
8783         /*
8784          * Note the lack of a DROP command for the shell type; any required DROP
8785          * is driven off the base type entry, instead.  This interacts with
8786          * _printTocEntry()'s use of the presence of a DROP command to decide
8787          * whether an entry needs an ALTER OWNER command.  We don't want to alter
8788          * the shell type's owner immediately on creation; that should happen only
8789          * after it's filled in, otherwise the backend complains.
8790          */
8791
8792         if (binary_upgrade)
8793                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8794                                                                                    stinfo->baseType->dobj.catId.oid);
8795
8796         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8797                                           fmtId(stinfo->dobj.name));
8798
8799         ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8800                                  stinfo->dobj.name,
8801                                  stinfo->dobj.namespace->dobj.name,
8802                                  NULL,
8803                                  stinfo->baseType->rolname, false,
8804                                  "SHELL TYPE", SECTION_PRE_DATA,
8805                                  q->data, "", NULL,
8806                                  NULL, 0,
8807                                  NULL, NULL);
8808
8809         destroyPQExpBuffer(q);
8810 }
8811
8812 /*
8813  * Determine whether we want to dump definitions for procedural languages.
8814  * Since the languages themselves don't have schemas, we can't rely on
8815  * the normal schema-based selection mechanism.  We choose to dump them
8816  * whenever neither --schema nor --table was given.  (Before 8.1, we used
8817  * the dump flag of the PL's call handler function, but in 8.1 this will
8818  * probably always be false since call handlers are created in pg_catalog.)
8819  *
8820  * For some backwards compatibility with the older behavior, we forcibly
8821  * dump a PL if its handler function (and validator if any) are in a
8822  * dumpable namespace.  That case is not checked here.
8823  *
8824  * Also, if the PL belongs to an extension, we do not use this heuristic.
8825  * That case isn't checked here either.
8826  */
8827 static bool
8828 shouldDumpProcLangs(void)
8829 {
8830         if (!include_everything)
8831                 return false;
8832         /* And they're schema not data */
8833         if (dataOnly)
8834                 return false;
8835         return true;
8836 }
8837
8838 /*
8839  * dumpProcLang
8840  *                writes out to fout the queries to recreate a user-defined
8841  *                procedural language
8842  */
8843 static void
8844 dumpProcLang(Archive *fout, ProcLangInfo *plang)
8845 {
8846         PQExpBuffer defqry;
8847         PQExpBuffer delqry;
8848         PQExpBuffer labelq;
8849         bool            useParams;
8850         char       *qlanname;
8851         char       *lanschema;
8852         FuncInfo   *funcInfo;
8853         FuncInfo   *inlineInfo = NULL;
8854         FuncInfo   *validatorInfo = NULL;
8855
8856         /* Skip if not to be dumped */
8857         if (!plang->dobj.dump || dataOnly)
8858                 return;
8859
8860         /*
8861          * Try to find the support function(s).  It is not an error if we don't
8862          * find them --- if the functions are in the pg_catalog schema, as is
8863          * standard in 8.1 and up, then we won't have loaded them. (In this case
8864          * we will emit a parameterless CREATE LANGUAGE command, which will
8865          * require PL template knowledge in the backend to reload.)
8866          */
8867
8868         funcInfo = findFuncByOid(plang->lanplcallfoid);
8869         if (funcInfo != NULL && !funcInfo->dobj.dump)
8870                 funcInfo = NULL;                /* treat not-dumped same as not-found */
8871
8872         if (OidIsValid(plang->laninline))
8873         {
8874                 inlineInfo = findFuncByOid(plang->laninline);
8875                 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
8876                         inlineInfo = NULL;
8877         }
8878
8879         if (OidIsValid(plang->lanvalidator))
8880         {
8881                 validatorInfo = findFuncByOid(plang->lanvalidator);
8882                 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
8883                         validatorInfo = NULL;
8884         }
8885
8886         /*
8887          * If the functions are dumpable then emit a traditional CREATE LANGUAGE
8888          * with parameters.  Otherwise, dump only if shouldDumpProcLangs() says to
8889          * dump it.
8890          *
8891          * However, for a language that belongs to an extension, we must not use
8892          * the shouldDumpProcLangs heuristic, but just dump the language iff we're
8893          * told to (via dobj.dump).  Generally the support functions will belong
8894          * to the same extension and so have the same dump flags ... if they
8895          * don't, this might not work terribly nicely.
8896          */
8897         useParams = (funcInfo != NULL &&
8898                                  (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
8899                                  (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
8900
8901         if (!plang->dobj.ext_member)
8902         {
8903                 if (!useParams && !shouldDumpProcLangs())
8904                         return;
8905         }
8906
8907         defqry = createPQExpBuffer();
8908         delqry = createPQExpBuffer();
8909         labelq = createPQExpBuffer();
8910
8911         qlanname = pg_strdup(fmtId(plang->dobj.name));
8912
8913         /*
8914          * If dumping a HANDLER clause, treat the language as being in the handler
8915          * function's schema; this avoids cluttering the HANDLER clause. Otherwise
8916          * it doesn't really have a schema.
8917          */
8918         if (useParams)
8919                 lanschema = funcInfo->dobj.namespace->dobj.name;
8920         else
8921                 lanschema = NULL;
8922
8923         appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
8924                                           qlanname);
8925
8926         if (useParams)
8927         {
8928                 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
8929                                                   plang->lanpltrusted ? "TRUSTED " : "",
8930                                                   qlanname);
8931                 appendPQExpBuffer(defqry, " HANDLER %s",
8932                                                   fmtId(funcInfo->dobj.name));
8933                 if (OidIsValid(plang->laninline))
8934                 {
8935                         appendPQExpBuffer(defqry, " INLINE ");
8936                         /* Cope with possibility that inline is in different schema */
8937                         if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
8938                                 appendPQExpBuffer(defqry, "%s.",
8939                                                            fmtId(inlineInfo->dobj.namespace->dobj.name));
8940                         appendPQExpBuffer(defqry, "%s",
8941                                                           fmtId(inlineInfo->dobj.name));
8942                 }
8943                 if (OidIsValid(plang->lanvalidator))
8944                 {
8945                         appendPQExpBuffer(defqry, " VALIDATOR ");
8946                         /* Cope with possibility that validator is in different schema */
8947                         if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
8948                                 appendPQExpBuffer(defqry, "%s.",
8949                                                         fmtId(validatorInfo->dobj.namespace->dobj.name));
8950                         appendPQExpBuffer(defqry, "%s",
8951                                                           fmtId(validatorInfo->dobj.name));
8952                 }
8953         }
8954         else
8955         {
8956                 /*
8957                  * If not dumping parameters, then use CREATE OR REPLACE so that the
8958                  * command will not fail if the language is preinstalled in the target
8959                  * database.  We restrict the use of REPLACE to this case so as to
8960                  * eliminate the risk of replacing a language with incompatible
8961                  * parameter settings: this command will only succeed at all if there
8962                  * is a pg_pltemplate entry, and if there is one, the existing entry
8963                  * must match it too.
8964                  */
8965                 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
8966                                                   qlanname);
8967         }
8968         appendPQExpBuffer(defqry, ";\n");
8969
8970         appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
8971
8972         if (binary_upgrade)
8973                 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
8974
8975         ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
8976                                  plang->dobj.name,
8977                                  lanschema, NULL, plang->lanowner,
8978                                  false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
8979                                  defqry->data, delqry->data, NULL,
8980                                  NULL, 0,
8981                                  NULL, NULL);
8982
8983         /* Dump Proc Lang Comments and Security Labels */
8984         dumpComment(fout, labelq->data,
8985                                 NULL, "",
8986                                 plang->dobj.catId, 0, plang->dobj.dumpId);
8987         dumpSecLabel(fout, labelq->data,
8988                                  NULL, "",
8989                                  plang->dobj.catId, 0, plang->dobj.dumpId);
8990
8991         if (plang->lanpltrusted)
8992                 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
8993                                 qlanname, NULL, plang->dobj.name,
8994                                 lanschema,
8995                                 plang->lanowner, plang->lanacl);
8996
8997         free(qlanname);
8998
8999         destroyPQExpBuffer(defqry);
9000         destroyPQExpBuffer(delqry);
9001         destroyPQExpBuffer(labelq);
9002 }
9003
9004 /*
9005  * format_function_arguments: generate function name and argument list
9006  *
9007  * This is used when we can rely on pg_get_function_arguments to format
9008  * the argument list.
9009  */
9010 static char *
9011 format_function_arguments(FuncInfo *finfo, char *funcargs)
9012 {
9013         PQExpBufferData fn;
9014
9015         initPQExpBuffer(&fn);
9016         appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
9017         return fn.data;
9018 }
9019
9020 /*
9021  * format_function_arguments_old: generate function name and argument list
9022  *
9023  * The argument type names are qualified if needed.  The function name
9024  * is never qualified.
9025  *
9026  * This is used only with pre-8.4 servers, so we aren't expecting to see
9027  * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
9028  *
9029  * Any or all of allargtypes, argmodes, argnames may be NULL.
9030  */
9031 static char *
9032 format_function_arguments_old(Archive *fout,
9033                                                           FuncInfo *finfo, int nallargs,
9034                                                           char **allargtypes,
9035                                                           char **argmodes,
9036                                                           char **argnames)
9037 {
9038         PQExpBufferData fn;
9039         int                     j;
9040
9041         initPQExpBuffer(&fn);
9042         appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
9043         for (j = 0; j < nallargs; j++)
9044         {
9045                 Oid                     typid;
9046                 char       *typname;
9047                 const char *argmode;
9048                 const char *argname;
9049
9050                 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
9051                 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
9052
9053                 if (argmodes)
9054                 {
9055                         switch (argmodes[j][0])
9056                         {
9057                                 case PROARGMODE_IN:
9058                                         argmode = "";
9059                                         break;
9060                                 case PROARGMODE_OUT:
9061                                         argmode = "OUT ";
9062                                         break;
9063                                 case PROARGMODE_INOUT:
9064                                         argmode = "INOUT ";
9065                                         break;
9066                                 default:
9067                                         write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
9068                                         argmode = "";
9069                                         break;
9070                         }
9071                 }
9072                 else
9073                         argmode = "";
9074
9075                 argname = argnames ? argnames[j] : (char *) NULL;
9076                 if (argname && argname[0] == '\0')
9077                         argname = NULL;
9078
9079                 appendPQExpBuffer(&fn, "%s%s%s%s%s",
9080                                                   (j > 0) ? ", " : "",
9081                                                   argmode,
9082                                                   argname ? fmtId(argname) : "",
9083                                                   argname ? " " : "",
9084                                                   typname);
9085                 free(typname);
9086         }
9087         appendPQExpBuffer(&fn, ")");
9088         return fn.data;
9089 }
9090
9091 /*
9092  * format_function_signature: generate function name and argument list
9093  *
9094  * This is like format_function_arguments_old except that only a minimal
9095  * list of input argument types is generated; this is sufficient to
9096  * reference the function, but not to define it.
9097  *
9098  * If honor_quotes is false then the function name is never quoted.
9099  * This is appropriate for use in TOC tags, but not in SQL commands.
9100  */
9101 static char *
9102 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
9103 {
9104         PQExpBufferData fn;
9105         int                     j;
9106
9107         initPQExpBuffer(&fn);
9108         if (honor_quotes)
9109                 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
9110         else
9111                 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
9112         for (j = 0; j < finfo->nargs; j++)
9113         {
9114                 char       *typname;
9115
9116                 typname = getFormattedTypeName(fout, finfo->argtypes[j],
9117                                                                            zeroAsOpaque);
9118
9119                 appendPQExpBuffer(&fn, "%s%s",
9120                                                   (j > 0) ? ", " : "",
9121                                                   typname);
9122                 free(typname);
9123         }
9124         appendPQExpBuffer(&fn, ")");
9125         return fn.data;
9126 }
9127
9128
9129 /*
9130  * dumpFunc:
9131  *        dump out one function
9132  */
9133 static void
9134 dumpFunc(Archive *fout, FuncInfo *finfo)
9135 {
9136         PQExpBuffer query;
9137         PQExpBuffer q;
9138         PQExpBuffer delqry;
9139         PQExpBuffer labelq;
9140         PQExpBuffer asPart;
9141         PGresult   *res;
9142         char       *funcsig;            /* identity signature */
9143         char       *funcfullsig;        /* full signature */
9144         char       *funcsig_tag;
9145         char       *proretset;
9146         char       *prosrc;
9147         char       *probin;
9148         char       *funcargs;
9149         char       *funciargs;
9150         char       *funcresult;
9151         char       *proallargtypes;
9152         char       *proargmodes;
9153         char       *proargnames;
9154         char       *proiswindow;
9155         char       *provolatile;
9156         char       *proisstrict;
9157         char       *prosecdef;
9158         char       *proleakproof;
9159         char       *proconfig;
9160         char       *procost;
9161         char       *prorows;
9162         char       *lanname;
9163         char       *rettypename;
9164         int                     nallargs;
9165         char      **allargtypes = NULL;
9166         char      **argmodes = NULL;
9167         char      **argnames = NULL;
9168         char      **configitems = NULL;
9169         int                     nconfigitems = 0;
9170         int                     i;
9171
9172         /* Skip if not to be dumped */
9173         if (!finfo->dobj.dump || dataOnly)
9174                 return;
9175
9176         query = createPQExpBuffer();
9177         q = createPQExpBuffer();
9178         delqry = createPQExpBuffer();
9179         labelq = createPQExpBuffer();
9180         asPart = createPQExpBuffer();
9181
9182         /* Set proper schema search path so type references list correctly */
9183         selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
9184
9185         /* Fetch function-specific details */
9186         if (fout->remoteVersion >= 90200)
9187         {
9188                 /*
9189                  * proleakproof was added at v9.2
9190                  */
9191                 appendPQExpBuffer(query,
9192                                                   "SELECT proretset, prosrc, probin, "
9193                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9194                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9195                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9196                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
9197                                                   "proleakproof, proconfig, procost, prorows, "
9198                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9199                                                   "FROM pg_catalog.pg_proc "
9200                                                   "WHERE oid = '%u'::pg_catalog.oid",
9201                                                   finfo->dobj.catId.oid);
9202         }
9203         else if (fout->remoteVersion >= 80400)
9204         {
9205                 /*
9206                  * In 8.4 and up we rely on pg_get_function_arguments and
9207                  * pg_get_function_result instead of examining proallargtypes etc.
9208                  */
9209                 appendPQExpBuffer(query,
9210                                                   "SELECT proretset, prosrc, probin, "
9211                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9212                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9213                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9214                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
9215                                                   "false AS proleakproof, "
9216                                                   " proconfig, procost, prorows, "
9217                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9218                                                   "FROM pg_catalog.pg_proc "
9219                                                   "WHERE oid = '%u'::pg_catalog.oid",
9220                                                   finfo->dobj.catId.oid);
9221         }
9222         else if (fout->remoteVersion >= 80300)
9223         {
9224                 appendPQExpBuffer(query,
9225                                                   "SELECT proretset, prosrc, probin, "
9226                                                   "proallargtypes, proargmodes, proargnames, "
9227                                                   "false AS proiswindow, "
9228                                                   "provolatile, proisstrict, prosecdef, "
9229                                                   "false AS proleakproof, "
9230                                                   "proconfig, procost, prorows, "
9231                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9232                                                   "FROM pg_catalog.pg_proc "
9233                                                   "WHERE oid = '%u'::pg_catalog.oid",
9234                                                   finfo->dobj.catId.oid);
9235         }
9236         else if (fout->remoteVersion >= 80100)
9237         {
9238                 appendPQExpBuffer(query,
9239                                                   "SELECT proretset, prosrc, probin, "
9240                                                   "proallargtypes, proargmodes, proargnames, "
9241                                                   "false AS proiswindow, "
9242                                                   "provolatile, proisstrict, prosecdef, "
9243                                                   "false AS proleakproof, "
9244                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9245                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9246                                                   "FROM pg_catalog.pg_proc "
9247                                                   "WHERE oid = '%u'::pg_catalog.oid",
9248                                                   finfo->dobj.catId.oid);
9249         }
9250         else if (fout->remoteVersion >= 80000)
9251         {
9252                 appendPQExpBuffer(query,
9253                                                   "SELECT proretset, prosrc, probin, "
9254                                                   "null AS proallargtypes, "
9255                                                   "null AS proargmodes, "
9256                                                   "proargnames, "
9257                                                   "false AS proiswindow, "
9258                                                   "provolatile, proisstrict, prosecdef, "
9259                                                   "false AS proleakproof, "
9260                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9261                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9262                                                   "FROM pg_catalog.pg_proc "
9263                                                   "WHERE oid = '%u'::pg_catalog.oid",
9264                                                   finfo->dobj.catId.oid);
9265         }
9266         else if (fout->remoteVersion >= 70300)
9267         {
9268                 appendPQExpBuffer(query,
9269                                                   "SELECT proretset, prosrc, probin, "
9270                                                   "null AS proallargtypes, "
9271                                                   "null AS proargmodes, "
9272                                                   "null AS proargnames, "
9273                                                   "false AS proiswindow, "
9274                                                   "provolatile, proisstrict, prosecdef, "
9275                                                   "false AS proleakproof, "
9276                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9277                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9278                                                   "FROM pg_catalog.pg_proc "
9279                                                   "WHERE oid = '%u'::pg_catalog.oid",
9280                                                   finfo->dobj.catId.oid);
9281         }
9282         else if (fout->remoteVersion >= 70100)
9283         {
9284                 appendPQExpBuffer(query,
9285                                                   "SELECT proretset, prosrc, probin, "
9286                                                   "null AS proallargtypes, "
9287                                                   "null AS proargmodes, "
9288                                                   "null AS proargnames, "
9289                                                   "false AS proiswindow, "
9290                          "case when proiscachable then 'i' else 'v' end AS provolatile, "
9291                                                   "proisstrict, "
9292                                                   "false AS prosecdef, "
9293                                                   "false AS proleakproof, "
9294                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9295                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9296                                                   "FROM pg_proc "
9297                                                   "WHERE oid = '%u'::oid",
9298                                                   finfo->dobj.catId.oid);
9299         }
9300         else
9301         {
9302                 appendPQExpBuffer(query,
9303                                                   "SELECT proretset, prosrc, probin, "
9304                                                   "null AS proallargtypes, "
9305                                                   "null AS proargmodes, "
9306                                                   "null AS proargnames, "
9307                                                   "false AS proiswindow, "
9308                          "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9309                                                   "false AS proisstrict, "
9310                                                   "false AS prosecdef, "
9311                                                   "false AS proleakproof, "
9312                                                   "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9313                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9314                                                   "FROM pg_proc "
9315                                                   "WHERE oid = '%u'::oid",
9316                                                   finfo->dobj.catId.oid);
9317         }
9318
9319         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9320
9321         proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9322         prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9323         probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9324         if (fout->remoteVersion >= 80400)
9325         {
9326                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9327                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9328                 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9329                 proallargtypes = proargmodes = proargnames = NULL;
9330         }
9331         else
9332         {
9333                 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9334                 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9335                 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9336                 funcargs = funciargs = funcresult = NULL;
9337         }
9338         proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9339         provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9340         proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9341         prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9342         proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9343         proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9344         procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9345         prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9346         lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9347
9348         /*
9349          * See backend/commands/functioncmds.c for details of how the 'AS' clause
9350          * is used.  In 8.4 and up, an unused probin is NULL (here ""); previous
9351          * versions would set it to "-".  There are no known cases in which prosrc
9352          * is unused, so the tests below for "-" are probably useless.
9353          */
9354         if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9355         {
9356                 appendPQExpBuffer(asPart, "AS ");
9357                 appendStringLiteralAH(asPart, probin, fout);
9358                 if (strcmp(prosrc, "-") != 0)
9359                 {
9360                         appendPQExpBuffer(asPart, ", ");
9361
9362                         /*
9363                          * where we have bin, use dollar quoting if allowed and src
9364                          * contains quote or backslash; else use regular quoting.
9365                          */
9366                         if (disable_dollar_quoting ||
9367                           (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9368                                 appendStringLiteralAH(asPart, prosrc, fout);
9369                         else
9370                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9371                 }
9372         }
9373         else
9374         {
9375                 if (strcmp(prosrc, "-") != 0)
9376                 {
9377                         appendPQExpBuffer(asPart, "AS ");
9378                         /* with no bin, dollar quote src unconditionally if allowed */
9379                         if (disable_dollar_quoting)
9380                                 appendStringLiteralAH(asPart, prosrc, fout);
9381                         else
9382                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9383                 }
9384         }
9385
9386         nallargs = finfo->nargs;        /* unless we learn different from allargs */
9387
9388         if (proallargtypes && *proallargtypes)
9389         {
9390                 int                     nitems = 0;
9391
9392                 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9393                         nitems < finfo->nargs)
9394                 {
9395                         write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9396                         if (allargtypes)
9397                                 free(allargtypes);
9398                         allargtypes = NULL;
9399                 }
9400                 else
9401                         nallargs = nitems;
9402         }
9403
9404         if (proargmodes && *proargmodes)
9405         {
9406                 int                     nitems = 0;
9407
9408                 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9409                         nitems != nallargs)
9410                 {
9411                         write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9412                         if (argmodes)
9413                                 free(argmodes);
9414                         argmodes = NULL;
9415                 }
9416         }
9417
9418         if (proargnames && *proargnames)
9419         {
9420                 int                     nitems = 0;
9421
9422                 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9423                         nitems != nallargs)
9424                 {
9425                         write_msg(NULL, "WARNING: could not parse proargnames array\n");
9426                         if (argnames)
9427                                 free(argnames);
9428                         argnames = NULL;
9429                 }
9430         }
9431
9432         if (proconfig && *proconfig)
9433         {
9434                 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9435                 {
9436                         write_msg(NULL, "WARNING: could not parse proconfig array\n");
9437                         if (configitems)
9438                                 free(configitems);
9439                         configitems = NULL;
9440                         nconfigitems = 0;
9441                 }
9442         }
9443
9444         if (funcargs)
9445         {
9446                 /* 8.4 or later; we rely on server-side code for most of the work */
9447                 funcfullsig = format_function_arguments(finfo, funcargs);
9448                 funcsig = format_function_arguments(finfo, funciargs);
9449         }
9450         else
9451         {
9452                 /* pre-8.4, do it ourselves */
9453                 funcsig = format_function_arguments_old(fout,
9454                                                                                                 finfo, nallargs, allargtypes,
9455                                                                                                 argmodes, argnames);
9456                 funcfullsig = funcsig;
9457         }
9458
9459         funcsig_tag = format_function_signature(fout, finfo, false);
9460
9461         /*
9462          * DROP must be fully qualified in case same name appears in pg_catalog
9463          */
9464         appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9465                                           fmtId(finfo->dobj.namespace->dobj.name),
9466                                           funcsig);
9467
9468         appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9469         if (funcresult)
9470                 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9471         else
9472         {
9473                 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9474                                                                                    zeroAsOpaque);
9475                 appendPQExpBuffer(q, "RETURNS %s%s",
9476                                                   (proretset[0] == 't') ? "SETOF " : "",
9477                                                   rettypename);
9478                 free(rettypename);
9479         }
9480
9481         appendPQExpBuffer(q, "\n    LANGUAGE %s", fmtId(lanname));
9482
9483         if (proiswindow[0] == 't')
9484                 appendPQExpBuffer(q, " WINDOW");
9485
9486         if (provolatile[0] != PROVOLATILE_VOLATILE)
9487         {
9488                 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9489                         appendPQExpBuffer(q, " IMMUTABLE");
9490                 else if (provolatile[0] == PROVOLATILE_STABLE)
9491                         appendPQExpBuffer(q, " STABLE");
9492                 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9493                         exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9494                                                   finfo->dobj.name);
9495         }
9496
9497         if (proisstrict[0] == 't')
9498                 appendPQExpBuffer(q, " STRICT");
9499
9500         if (prosecdef[0] == 't')
9501                 appendPQExpBuffer(q, " SECURITY DEFINER");
9502
9503         if (proleakproof[0] == 't')
9504                 appendPQExpBuffer(q, " LEAKPROOF");
9505
9506         /*
9507          * COST and ROWS are emitted only if present and not default, so as not to
9508          * break backwards-compatibility of the dump without need.      Keep this code
9509          * in sync with the defaults in functioncmds.c.
9510          */
9511         if (strcmp(procost, "0") != 0)
9512         {
9513                 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9514                 {
9515                         /* default cost is 1 */
9516                         if (strcmp(procost, "1") != 0)
9517                                 appendPQExpBuffer(q, " COST %s", procost);
9518                 }
9519                 else
9520                 {
9521                         /* default cost is 100 */
9522                         if (strcmp(procost, "100") != 0)
9523                                 appendPQExpBuffer(q, " COST %s", procost);
9524                 }
9525         }
9526         if (proretset[0] == 't' &&
9527                 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9528                 appendPQExpBuffer(q, " ROWS %s", prorows);
9529
9530         for (i = 0; i < nconfigitems; i++)
9531         {
9532                 /* we feel free to scribble on configitems[] here */
9533                 char       *configitem = configitems[i];
9534                 char       *pos;
9535
9536                 pos = strchr(configitem, '=');
9537                 if (pos == NULL)
9538                         continue;
9539                 *pos++ = '\0';
9540                 appendPQExpBuffer(q, "\n    SET %s TO ", fmtId(configitem));
9541
9542                 /*
9543                  * Some GUC variable names are 'LIST' type and hence must not be
9544                  * quoted.
9545                  */
9546                 if (pg_strcasecmp(configitem, "DateStyle") == 0
9547                         || pg_strcasecmp(configitem, "search_path") == 0)
9548                         appendPQExpBuffer(q, "%s", pos);
9549                 else
9550                         appendStringLiteralAH(q, pos, fout);
9551         }
9552
9553         appendPQExpBuffer(q, "\n    %s;\n", asPart->data);
9554
9555         appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9556
9557         if (binary_upgrade)
9558                 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9559
9560         ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9561                                  funcsig_tag,
9562                                  finfo->dobj.namespace->dobj.name,
9563                                  NULL,
9564                                  finfo->rolname, false,
9565                                  "FUNCTION", SECTION_PRE_DATA,
9566                                  q->data, delqry->data, NULL,
9567                                  NULL, 0,
9568                                  NULL, NULL);
9569
9570         /* Dump Function Comments and Security Labels */
9571         dumpComment(fout, labelq->data,
9572                                 finfo->dobj.namespace->dobj.name, finfo->rolname,
9573                                 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9574         dumpSecLabel(fout, labelq->data,
9575                                  finfo->dobj.namespace->dobj.name, finfo->rolname,
9576                                  finfo->dobj.catId, 0, finfo->dobj.dumpId);
9577
9578         dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9579                         funcsig, NULL, funcsig_tag,
9580                         finfo->dobj.namespace->dobj.name,
9581                         finfo->rolname, finfo->proacl);
9582
9583         PQclear(res);
9584
9585         destroyPQExpBuffer(query);
9586         destroyPQExpBuffer(q);
9587         destroyPQExpBuffer(delqry);
9588         destroyPQExpBuffer(labelq);
9589         destroyPQExpBuffer(asPart);
9590         free(funcsig);
9591         free(funcsig_tag);
9592         if (allargtypes)
9593                 free(allargtypes);
9594         if (argmodes)
9595                 free(argmodes);
9596         if (argnames)
9597                 free(argnames);
9598         if (configitems)
9599                 free(configitems);
9600 }
9601
9602
9603 /*
9604  * Dump a user-defined cast
9605  */
9606 static void
9607 dumpCast(Archive *fout, CastInfo *cast)
9608 {
9609         PQExpBuffer defqry;
9610         PQExpBuffer delqry;
9611         PQExpBuffer labelq;
9612         FuncInfo   *funcInfo = NULL;
9613
9614         /* Skip if not to be dumped */
9615         if (!cast->dobj.dump || dataOnly)
9616                 return;
9617
9618         /* Cannot dump if we don't have the cast function's info */
9619         if (OidIsValid(cast->castfunc))
9620         {
9621                 funcInfo = findFuncByOid(cast->castfunc);
9622                 if (funcInfo == NULL)
9623                         return;
9624         }
9625
9626         /*
9627          * As per discussion we dump casts if one or more of the underlying
9628          * objects (the conversion function and the two data types) are not
9629          * builtin AND if all of the non-builtin objects are included in the dump.
9630          * Builtin meaning, the namespace name does not start with "pg_".
9631          *
9632          * However, for a cast that belongs to an extension, we must not use this
9633          * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9634          */
9635         if (!cast->dobj.ext_member)
9636         {
9637                 TypeInfo   *sourceInfo = findTypeByOid(cast->castsource);
9638                 TypeInfo   *targetInfo = findTypeByOid(cast->casttarget);
9639
9640                 if (sourceInfo == NULL || targetInfo == NULL)
9641                         return;
9642
9643                 /*
9644                  * Skip this cast if all objects are from pg_
9645                  */
9646                 if ((funcInfo == NULL ||
9647                          strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9648                         strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9649                         strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9650                         return;
9651
9652                 /*
9653                  * Skip cast if function isn't from pg_ and is not to be dumped.
9654                  */
9655                 if (funcInfo &&
9656                         strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9657                         !funcInfo->dobj.dump)
9658                         return;
9659
9660                 /*
9661                  * Same for the source type
9662                  */
9663                 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9664                         !sourceInfo->dobj.dump)
9665                         return;
9666
9667                 /*
9668                  * and the target type.
9669                  */
9670                 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9671                         !targetInfo->dobj.dump)
9672                         return;
9673         }
9674
9675         /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9676         selectSourceSchema(fout, "pg_catalog");
9677
9678         defqry = createPQExpBuffer();
9679         delqry = createPQExpBuffer();
9680         labelq = createPQExpBuffer();
9681
9682         appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9683                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9684                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9685
9686         appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9687                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9688                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9689
9690         switch (cast->castmethod)
9691         {
9692                 case COERCION_METHOD_BINARY:
9693                         appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9694                         break;
9695                 case COERCION_METHOD_INOUT:
9696                         appendPQExpBuffer(defqry, "WITH INOUT");
9697                         break;
9698                 case COERCION_METHOD_FUNCTION:
9699                         if (funcInfo)
9700                         {
9701                                 char       *fsig = format_function_signature(fout, funcInfo, true);
9702
9703                                 /*
9704                                  * Always qualify the function name, in case it is not in
9705                                  * pg_catalog schema (format_function_signature won't qualify
9706                                  * it).
9707                                  */
9708                                 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
9709                                                    fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
9710                                 free(fsig);
9711                         }
9712                         else
9713                                 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
9714                         break;
9715                 default:
9716                         write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9717         }
9718
9719         if (cast->castcontext == 'a')
9720                 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9721         else if (cast->castcontext == 'i')
9722                 appendPQExpBuffer(defqry, " AS IMPLICIT");
9723         appendPQExpBuffer(defqry, ";\n");
9724
9725         appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9726                                         getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9727                                    getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9728
9729         if (binary_upgrade)
9730                 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9731
9732         ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9733                                  labelq->data,
9734                                  "pg_catalog", NULL, "",
9735                                  false, "CAST", SECTION_PRE_DATA,
9736                                  defqry->data, delqry->data, NULL,
9737                                  NULL, 0,
9738                                  NULL, NULL);
9739
9740         /* Dump Cast Comments */
9741         dumpComment(fout, labelq->data,
9742                                 NULL, "",
9743                                 cast->dobj.catId, 0, cast->dobj.dumpId);
9744
9745         destroyPQExpBuffer(defqry);
9746         destroyPQExpBuffer(delqry);
9747         destroyPQExpBuffer(labelq);
9748 }
9749
9750 /*
9751  * dumpOpr
9752  *        write out a single operator definition
9753  */
9754 static void
9755 dumpOpr(Archive *fout, OprInfo *oprinfo)
9756 {
9757         PQExpBuffer query;
9758         PQExpBuffer q;
9759         PQExpBuffer delq;
9760         PQExpBuffer labelq;
9761         PQExpBuffer oprid;
9762         PQExpBuffer details;
9763         const char *name;
9764         PGresult   *res;
9765         int                     i_oprkind;
9766         int                     i_oprcode;
9767         int                     i_oprleft;
9768         int                     i_oprright;
9769         int                     i_oprcom;
9770         int                     i_oprnegate;
9771         int                     i_oprrest;
9772         int                     i_oprjoin;
9773         int                     i_oprcanmerge;
9774         int                     i_oprcanhash;
9775         char       *oprkind;
9776         char       *oprcode;
9777         char       *oprleft;
9778         char       *oprright;
9779         char       *oprcom;
9780         char       *oprnegate;
9781         char       *oprrest;
9782         char       *oprjoin;
9783         char       *oprcanmerge;
9784         char       *oprcanhash;
9785
9786         /* Skip if not to be dumped */
9787         if (!oprinfo->dobj.dump || dataOnly)
9788                 return;
9789
9790         /*
9791          * some operators are invalid because they were the result of user
9792          * defining operators before commutators exist
9793          */
9794         if (!OidIsValid(oprinfo->oprcode))
9795                 return;
9796
9797         query = createPQExpBuffer();
9798         q = createPQExpBuffer();
9799         delq = createPQExpBuffer();
9800         labelq = createPQExpBuffer();
9801         oprid = createPQExpBuffer();
9802         details = createPQExpBuffer();
9803
9804         /* Make sure we are in proper schema so regoperator works correctly */
9805         selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
9806
9807         if (fout->remoteVersion >= 80300)
9808         {
9809                 appendPQExpBuffer(query, "SELECT oprkind, "
9810                                                   "oprcode::pg_catalog.regprocedure, "
9811                                                   "oprleft::pg_catalog.regtype, "
9812                                                   "oprright::pg_catalog.regtype, "
9813                                                   "oprcom::pg_catalog.regoperator, "
9814                                                   "oprnegate::pg_catalog.regoperator, "
9815                                                   "oprrest::pg_catalog.regprocedure, "
9816                                                   "oprjoin::pg_catalog.regprocedure, "
9817                                                   "oprcanmerge, oprcanhash "
9818                                                   "FROM pg_catalog.pg_operator "
9819                                                   "WHERE oid = '%u'::pg_catalog.oid",
9820                                                   oprinfo->dobj.catId.oid);
9821         }
9822         else if (fout->remoteVersion >= 70300)
9823         {
9824                 appendPQExpBuffer(query, "SELECT oprkind, "
9825                                                   "oprcode::pg_catalog.regprocedure, "
9826                                                   "oprleft::pg_catalog.regtype, "
9827                                                   "oprright::pg_catalog.regtype, "
9828                                                   "oprcom::pg_catalog.regoperator, "
9829                                                   "oprnegate::pg_catalog.regoperator, "
9830                                                   "oprrest::pg_catalog.regprocedure, "
9831                                                   "oprjoin::pg_catalog.regprocedure, "
9832                                                   "(oprlsortop != 0) AS oprcanmerge, "
9833                                                   "oprcanhash "
9834                                                   "FROM pg_catalog.pg_operator "
9835                                                   "WHERE oid = '%u'::pg_catalog.oid",
9836                                                   oprinfo->dobj.catId.oid);
9837         }
9838         else if (fout->remoteVersion >= 70100)
9839         {
9840                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9841                                                   "CASE WHEN oprleft = 0 THEN '-' "
9842                                                   "ELSE format_type(oprleft, NULL) END AS oprleft, "
9843                                                   "CASE WHEN oprright = 0 THEN '-' "
9844                                                   "ELSE format_type(oprright, NULL) END AS oprright, "
9845                                                   "oprcom, oprnegate, oprrest, oprjoin, "
9846                                                   "(oprlsortop != 0) AS oprcanmerge, "
9847                                                   "oprcanhash "
9848                                                   "FROM pg_operator "
9849                                                   "WHERE oid = '%u'::oid",
9850                                                   oprinfo->dobj.catId.oid);
9851         }
9852         else
9853         {
9854                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9855                                                   "CASE WHEN oprleft = 0 THEN '-'::name "
9856                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
9857                                                   "CASE WHEN oprright = 0 THEN '-'::name "
9858                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
9859                                                   "oprcom, oprnegate, oprrest, oprjoin, "
9860                                                   "(oprlsortop != 0) AS oprcanmerge, "
9861                                                   "oprcanhash "
9862                                                   "FROM pg_operator "
9863                                                   "WHERE oid = '%u'::oid",
9864                                                   oprinfo->dobj.catId.oid);
9865         }
9866
9867         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9868
9869         i_oprkind = PQfnumber(res, "oprkind");
9870         i_oprcode = PQfnumber(res, "oprcode");
9871         i_oprleft = PQfnumber(res, "oprleft");
9872         i_oprright = PQfnumber(res, "oprright");
9873         i_oprcom = PQfnumber(res, "oprcom");
9874         i_oprnegate = PQfnumber(res, "oprnegate");
9875         i_oprrest = PQfnumber(res, "oprrest");
9876         i_oprjoin = PQfnumber(res, "oprjoin");
9877         i_oprcanmerge = PQfnumber(res, "oprcanmerge");
9878         i_oprcanhash = PQfnumber(res, "oprcanhash");
9879
9880         oprkind = PQgetvalue(res, 0, i_oprkind);
9881         oprcode = PQgetvalue(res, 0, i_oprcode);
9882         oprleft = PQgetvalue(res, 0, i_oprleft);
9883         oprright = PQgetvalue(res, 0, i_oprright);
9884         oprcom = PQgetvalue(res, 0, i_oprcom);
9885         oprnegate = PQgetvalue(res, 0, i_oprnegate);
9886         oprrest = PQgetvalue(res, 0, i_oprrest);
9887         oprjoin = PQgetvalue(res, 0, i_oprjoin);
9888         oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
9889         oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
9890
9891         appendPQExpBuffer(details, "    PROCEDURE = %s",
9892                                           convertRegProcReference(fout, oprcode));
9893
9894         appendPQExpBuffer(oprid, "%s (",
9895                                           oprinfo->dobj.name);
9896
9897         /*
9898          * right unary means there's a left arg and left unary means there's a
9899          * right arg
9900          */
9901         if (strcmp(oprkind, "r") == 0 ||
9902                 strcmp(oprkind, "b") == 0)
9903         {
9904                 if (fout->remoteVersion >= 70100)
9905                         name = oprleft;
9906                 else
9907                         name = fmtId(oprleft);
9908                 appendPQExpBuffer(details, ",\n    LEFTARG = %s", name);
9909                 appendPQExpBuffer(oprid, "%s", name);
9910         }
9911         else
9912                 appendPQExpBuffer(oprid, "NONE");
9913
9914         if (strcmp(oprkind, "l") == 0 ||
9915                 strcmp(oprkind, "b") == 0)
9916         {
9917                 if (fout->remoteVersion >= 70100)
9918                         name = oprright;
9919                 else
9920                         name = fmtId(oprright);
9921                 appendPQExpBuffer(details, ",\n    RIGHTARG = %s", name);
9922                 appendPQExpBuffer(oprid, ", %s)", name);
9923         }
9924         else
9925                 appendPQExpBuffer(oprid, ", NONE)");
9926
9927         name = convertOperatorReference(fout, oprcom);
9928         if (name)
9929                 appendPQExpBuffer(details, ",\n    COMMUTATOR = %s", name);
9930
9931         name = convertOperatorReference(fout, oprnegate);
9932         if (name)
9933                 appendPQExpBuffer(details, ",\n    NEGATOR = %s", name);
9934
9935         if (strcmp(oprcanmerge, "t") == 0)
9936                 appendPQExpBuffer(details, ",\n    MERGES");
9937
9938         if (strcmp(oprcanhash, "t") == 0)
9939                 appendPQExpBuffer(details, ",\n    HASHES");
9940
9941         name = convertRegProcReference(fout, oprrest);
9942         if (name)
9943                 appendPQExpBuffer(details, ",\n    RESTRICT = %s", name);
9944
9945         name = convertRegProcReference(fout, oprjoin);
9946         if (name)
9947                 appendPQExpBuffer(details, ",\n    JOIN = %s", name);
9948
9949         /*
9950          * DROP must be fully qualified in case same name appears in pg_catalog
9951          */
9952         appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
9953                                           fmtId(oprinfo->dobj.namespace->dobj.name),
9954                                           oprid->data);
9955
9956         appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
9957                                           oprinfo->dobj.name, details->data);
9958
9959         appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
9960
9961         if (binary_upgrade)
9962                 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
9963
9964         ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
9965                                  oprinfo->dobj.name,
9966                                  oprinfo->dobj.namespace->dobj.name,
9967                                  NULL,
9968                                  oprinfo->rolname,
9969                                  false, "OPERATOR", SECTION_PRE_DATA,
9970                                  q->data, delq->data, NULL,
9971                                  NULL, 0,
9972                                  NULL, NULL);
9973
9974         /* Dump Operator Comments */
9975         dumpComment(fout, labelq->data,
9976                                 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
9977                                 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
9978
9979         PQclear(res);
9980
9981         destroyPQExpBuffer(query);
9982         destroyPQExpBuffer(q);
9983         destroyPQExpBuffer(delq);
9984         destroyPQExpBuffer(labelq);
9985         destroyPQExpBuffer(oprid);
9986         destroyPQExpBuffer(details);
9987 }
9988
9989 /*
9990  * Convert a function reference obtained from pg_operator
9991  *
9992  * Returns what to print, or NULL if function references is InvalidOid
9993  *
9994  * In 7.3 the input is a REGPROCEDURE display; we have to strip the
9995  * argument-types part.  In prior versions, the input is a REGPROC display.
9996  */
9997 static const char *
9998 convertRegProcReference(Archive *fout, const char *proc)
9999 {
10000         /* In all cases "-" means a null reference */
10001         if (strcmp(proc, "-") == 0)
10002                 return NULL;
10003
10004         if (fout->remoteVersion >= 70300)
10005         {
10006                 char       *name;
10007                 char       *paren;
10008                 bool            inquote;
10009
10010                 name = pg_strdup(proc);
10011                 /* find non-double-quoted left paren */
10012                 inquote = false;
10013                 for (paren = name; *paren; paren++)
10014                 {
10015                         if (*paren == '(' && !inquote)
10016                         {
10017                                 *paren = '\0';
10018                                 break;
10019                         }
10020                         if (*paren == '"')
10021                                 inquote = !inquote;
10022                 }
10023                 return name;
10024         }
10025
10026         /* REGPROC before 7.3 does not quote its result */
10027         return fmtId(proc);
10028 }
10029
10030 /*
10031  * Convert an operator cross-reference obtained from pg_operator
10032  *
10033  * Returns what to print, or NULL to print nothing
10034  *
10035  * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
10036  * argument-types part, and add OPERATOR() decoration if the name is
10037  * schema-qualified.  In older versions, the input is just a numeric OID,
10038  * which we search our operator list for.
10039  */
10040 static const char *
10041 convertOperatorReference(Archive *fout, const char *opr)
10042 {
10043         OprInfo    *oprInfo;
10044
10045         /* In all cases "0" means a null reference */
10046         if (strcmp(opr, "0") == 0)
10047                 return NULL;
10048
10049         if (fout->remoteVersion >= 70300)
10050         {
10051                 char       *name;
10052                 char       *oname;
10053                 char       *ptr;
10054                 bool            inquote;
10055                 bool            sawdot;
10056
10057                 name = pg_strdup(opr);
10058                 /* find non-double-quoted left paren, and check for non-quoted dot */
10059                 inquote = false;
10060                 sawdot = false;
10061                 for (ptr = name; *ptr; ptr++)
10062                 {
10063                         if (*ptr == '"')
10064                                 inquote = !inquote;
10065                         else if (*ptr == '.' && !inquote)
10066                                 sawdot = true;
10067                         else if (*ptr == '(' && !inquote)
10068                         {
10069                                 *ptr = '\0';
10070                                 break;
10071                         }
10072                 }
10073                 /* If not schema-qualified, don't need to add OPERATOR() */
10074                 if (!sawdot)
10075                         return name;
10076                 oname = pg_malloc(strlen(name) + 11);
10077                 sprintf(oname, "OPERATOR(%s)", name);
10078                 free(name);
10079                 return oname;
10080         }
10081
10082         oprInfo = findOprByOid(atooid(opr));
10083         if (oprInfo == NULL)
10084         {
10085                 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
10086                                   opr);
10087                 return NULL;
10088         }
10089         return oprInfo->dobj.name;
10090 }
10091
10092 /*
10093  * Convert a function OID obtained from pg_ts_parser or pg_ts_template
10094  *
10095  * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
10096  * argument lists of these functions are predetermined.  Note that the
10097  * caller should ensure we are in the proper schema, because the results
10098  * are search path dependent!
10099  */
10100 static const char *
10101 convertTSFunction(Archive *fout, Oid funcOid)
10102 {
10103         char       *result;
10104         char            query[128];
10105         PGresult   *res;
10106
10107         snprintf(query, sizeof(query),
10108                          "SELECT '%u'::pg_catalog.regproc", funcOid);
10109         res = ExecuteSqlQueryForSingleRow(fout, query);
10110
10111         result = pg_strdup(PQgetvalue(res, 0, 0));
10112
10113         PQclear(res);
10114
10115         return result;
10116 }
10117
10118
10119 /*
10120  * dumpOpclass
10121  *        write out a single operator class definition
10122  */
10123 static void
10124 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
10125 {
10126         PQExpBuffer query;
10127         PQExpBuffer q;
10128         PQExpBuffer delq;
10129         PQExpBuffer labelq;
10130         PGresult   *res;
10131         int                     ntups;
10132         int                     i_opcintype;
10133         int                     i_opckeytype;
10134         int                     i_opcdefault;
10135         int                     i_opcfamily;
10136         int                     i_opcfamilyname;
10137         int                     i_opcfamilynsp;
10138         int                     i_amname;
10139         int                     i_amopstrategy;
10140         int                     i_amopreqcheck;
10141         int                     i_amopopr;
10142         int                     i_sortfamily;
10143         int                     i_sortfamilynsp;
10144         int                     i_amprocnum;
10145         int                     i_amproc;
10146         int                     i_amproclefttype;
10147         int                     i_amprocrighttype;
10148         char       *opcintype;
10149         char       *opckeytype;
10150         char       *opcdefault;
10151         char       *opcfamily;
10152         char       *opcfamilyname;
10153         char       *opcfamilynsp;
10154         char       *amname;
10155         char       *amopstrategy;
10156         char       *amopreqcheck;
10157         char       *amopopr;
10158         char       *sortfamily;
10159         char       *sortfamilynsp;
10160         char       *amprocnum;
10161         char       *amproc;
10162         char       *amproclefttype;
10163         char       *amprocrighttype;
10164         bool            needComma;
10165         int                     i;
10166
10167         /* Skip if not to be dumped */
10168         if (!opcinfo->dobj.dump || dataOnly)
10169                 return;
10170
10171         /*
10172          * XXX currently we do not implement dumping of operator classes from
10173          * pre-7.3 databases.  This could be done but it seems not worth the
10174          * trouble.
10175          */
10176         if (fout->remoteVersion < 70300)
10177                 return;
10178
10179         query = createPQExpBuffer();
10180         q = createPQExpBuffer();
10181         delq = createPQExpBuffer();
10182         labelq = createPQExpBuffer();
10183
10184         /* Make sure we are in proper schema so regoperator works correctly */
10185         selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
10186
10187         /* Get additional fields from the pg_opclass row */
10188         if (fout->remoteVersion >= 80300)
10189         {
10190                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10191                                                   "opckeytype::pg_catalog.regtype, "
10192                                                   "opcdefault, opcfamily, "
10193                                                   "opfname AS opcfamilyname, "
10194                                                   "nspname AS opcfamilynsp, "
10195                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
10196                                                   "FROM pg_catalog.pg_opclass c "
10197                                    "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
10198                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10199                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
10200                                                   opcinfo->dobj.catId.oid);
10201         }
10202         else
10203         {
10204                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10205                                                   "opckeytype::pg_catalog.regtype, "
10206                                                   "opcdefault, NULL AS opcfamily, "
10207                                                   "NULL AS opcfamilyname, "
10208                                                   "NULL AS opcfamilynsp, "
10209                 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
10210                                                   "FROM pg_catalog.pg_opclass "
10211                                                   "WHERE oid = '%u'::pg_catalog.oid",
10212                                                   opcinfo->dobj.catId.oid);
10213         }
10214
10215         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10216
10217         i_opcintype = PQfnumber(res, "opcintype");
10218         i_opckeytype = PQfnumber(res, "opckeytype");
10219         i_opcdefault = PQfnumber(res, "opcdefault");
10220         i_opcfamily = PQfnumber(res, "opcfamily");
10221         i_opcfamilyname = PQfnumber(res, "opcfamilyname");
10222         i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
10223         i_amname = PQfnumber(res, "amname");
10224
10225         opcintype = PQgetvalue(res, 0, i_opcintype);
10226         opckeytype = PQgetvalue(res, 0, i_opckeytype);
10227         opcdefault = PQgetvalue(res, 0, i_opcdefault);
10228         /* opcfamily will still be needed after we PQclear res */
10229         opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
10230         opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
10231         opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10232         /* amname will still be needed after we PQclear res */
10233         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10234
10235         /*
10236          * DROP must be fully qualified in case same name appears in pg_catalog
10237          */
10238         appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10239                                           fmtId(opcinfo->dobj.namespace->dobj.name));
10240         appendPQExpBuffer(delq, ".%s",
10241                                           fmtId(opcinfo->dobj.name));
10242         appendPQExpBuffer(delq, " USING %s;\n",
10243                                           fmtId(amname));
10244
10245         /* Build the fixed portion of the CREATE command */
10246         appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n    ",
10247                                           fmtId(opcinfo->dobj.name));
10248         if (strcmp(opcdefault, "t") == 0)
10249                 appendPQExpBuffer(q, "DEFAULT ");
10250         appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10251                                           opcintype,
10252                                           fmtId(amname));
10253         if (strlen(opcfamilyname) > 0 &&
10254                 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10255                  strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10256         {
10257                 appendPQExpBuffer(q, " FAMILY ");
10258                 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10259                         appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10260                 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10261         }
10262         appendPQExpBuffer(q, " AS\n    ");
10263
10264         needComma = false;
10265
10266         if (strcmp(opckeytype, "-") != 0)
10267         {
10268                 appendPQExpBuffer(q, "STORAGE %s",
10269                                                   opckeytype);
10270                 needComma = true;
10271         }
10272
10273         PQclear(res);
10274
10275         /*
10276          * Now fetch and print the OPERATOR entries (pg_amop rows).
10277          *
10278          * Print only those opfamily members that are tied to the opclass by
10279          * pg_depend entries.
10280          *
10281          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10282          * older server's opclass in which it is used.  This is to avoid
10283          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10284          * older server and then reload into that old version.  This can go away
10285          * once 8.3 is so old as to not be of interest to anyone.
10286          */
10287         resetPQExpBuffer(query);
10288
10289         if (fout->remoteVersion >= 90100)
10290         {
10291                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10292                                                   "amopopr::pg_catalog.regoperator, "
10293                                                   "opfname AS sortfamily, "
10294                                                   "nspname AS sortfamilynsp "
10295                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10296                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10297                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10298                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10299                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10300                                                   "AND refobjid = '%u'::pg_catalog.oid "
10301                                                   "AND amopfamily = '%s'::pg_catalog.oid "
10302                                                   "ORDER BY amopstrategy",
10303                                                   opcinfo->dobj.catId.oid,
10304                                                   opcfamily);
10305         }
10306         else if (fout->remoteVersion >= 80400)
10307         {
10308                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10309                                                   "amopopr::pg_catalog.regoperator, "
10310                                                   "NULL AS sortfamily, "
10311                                                   "NULL AS sortfamilynsp "
10312                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10313                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10314                                                   "AND refobjid = '%u'::pg_catalog.oid "
10315                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10316                                                   "AND objid = ao.oid "
10317                                                   "ORDER BY amopstrategy",
10318                                                   opcinfo->dobj.catId.oid);
10319         }
10320         else if (fout->remoteVersion >= 80300)
10321         {
10322                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10323                                                   "amopopr::pg_catalog.regoperator, "
10324                                                   "NULL AS sortfamily, "
10325                                                   "NULL AS sortfamilynsp "
10326                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10327                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10328                                                   "AND refobjid = '%u'::pg_catalog.oid "
10329                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10330                                                   "AND objid = ao.oid "
10331                                                   "ORDER BY amopstrategy",
10332                                                   opcinfo->dobj.catId.oid);
10333         }
10334         else
10335         {
10336                 /*
10337                  * Here, we print all entries since there are no opfamilies and hence
10338                  * no loose operators to worry about.
10339                  */
10340                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10341                                                   "amopopr::pg_catalog.regoperator, "
10342                                                   "NULL AS sortfamily, "
10343                                                   "NULL AS sortfamilynsp "
10344                                                   "FROM pg_catalog.pg_amop "
10345                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10346                                                   "ORDER BY amopstrategy",
10347                                                   opcinfo->dobj.catId.oid);
10348         }
10349
10350         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10351
10352         ntups = PQntuples(res);
10353
10354         i_amopstrategy = PQfnumber(res, "amopstrategy");
10355         i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10356         i_amopopr = PQfnumber(res, "amopopr");
10357         i_sortfamily = PQfnumber(res, "sortfamily");
10358         i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10359
10360         for (i = 0; i < ntups; i++)
10361         {
10362                 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10363                 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10364                 amopopr = PQgetvalue(res, i, i_amopopr);
10365                 sortfamily = PQgetvalue(res, i, i_sortfamily);
10366                 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10367
10368                 if (needComma)
10369                         appendPQExpBuffer(q, " ,\n    ");
10370
10371                 appendPQExpBuffer(q, "OPERATOR %s %s",
10372                                                   amopstrategy, amopopr);
10373
10374                 if (strlen(sortfamily) > 0)
10375                 {
10376                         appendPQExpBuffer(q, " FOR ORDER BY ");
10377                         if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10378                                 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10379                         appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10380                 }
10381
10382                 if (strcmp(amopreqcheck, "t") == 0)
10383                         appendPQExpBuffer(q, " RECHECK");
10384
10385                 needComma = true;
10386         }
10387
10388         PQclear(res);
10389
10390         /*
10391          * Now fetch and print the FUNCTION entries (pg_amproc rows).
10392          *
10393          * Print only those opfamily members that are tied to the opclass by
10394          * pg_depend entries.
10395          *
10396          * We print the amproclefttype/amprocrighttype even though in most cases
10397          * the backend could deduce the right values, because of the corner case
10398          * of a btree sort support function for a cross-type comparison.  That's
10399          * only allowed in 9.2 and later, but for simplicity print them in all
10400          * versions that have the columns.
10401          */
10402         resetPQExpBuffer(query);
10403
10404         if (fout->remoteVersion >= 80300)
10405         {
10406                 appendPQExpBuffer(query, "SELECT amprocnum, "
10407                                                   "amproc::pg_catalog.regprocedure, "
10408                                                   "amproclefttype::pg_catalog.regtype, "
10409                                                   "amprocrighttype::pg_catalog.regtype "
10410                                                 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10411                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10412                                                   "AND refobjid = '%u'::pg_catalog.oid "
10413                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10414                                                   "AND objid = ap.oid "
10415                                                   "ORDER BY amprocnum",
10416                                                   opcinfo->dobj.catId.oid);
10417         }
10418         else
10419         {
10420                 appendPQExpBuffer(query, "SELECT amprocnum, "
10421                                                   "amproc::pg_catalog.regprocedure, "
10422                                                   "'' AS amproclefttype, "
10423                                                   "'' AS amprocrighttype "
10424                                                   "FROM pg_catalog.pg_amproc "
10425                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10426                                                   "ORDER BY amprocnum",
10427                                                   opcinfo->dobj.catId.oid);
10428         }
10429
10430         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10431
10432         ntups = PQntuples(res);
10433
10434         i_amprocnum = PQfnumber(res, "amprocnum");
10435         i_amproc = PQfnumber(res, "amproc");
10436         i_amproclefttype = PQfnumber(res, "amproclefttype");
10437         i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10438
10439         for (i = 0; i < ntups; i++)
10440         {
10441                 amprocnum = PQgetvalue(res, i, i_amprocnum);
10442                 amproc = PQgetvalue(res, i, i_amproc);
10443                 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10444                 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10445
10446                 if (needComma)
10447                         appendPQExpBuffer(q, " ,\n    ");
10448
10449                 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10450
10451                 if (*amproclefttype && *amprocrighttype)
10452                         appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10453
10454                 appendPQExpBuffer(q, " %s", amproc);
10455
10456                 needComma = true;
10457         }
10458
10459         PQclear(res);
10460
10461         appendPQExpBuffer(q, ";\n");
10462
10463         appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10464                                           fmtId(opcinfo->dobj.name));
10465         appendPQExpBuffer(labelq, " USING %s",
10466                                           fmtId(amname));
10467
10468         if (binary_upgrade)
10469                 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10470
10471         ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10472                                  opcinfo->dobj.name,
10473                                  opcinfo->dobj.namespace->dobj.name,
10474                                  NULL,
10475                                  opcinfo->rolname,
10476                                  false, "OPERATOR CLASS", SECTION_PRE_DATA,
10477                                  q->data, delq->data, NULL,
10478                                  NULL, 0,
10479                                  NULL, NULL);
10480
10481         /* Dump Operator Class Comments */
10482         dumpComment(fout, labelq->data,
10483                                 NULL, opcinfo->rolname,
10484                                 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10485
10486         free(amname);
10487         destroyPQExpBuffer(query);
10488         destroyPQExpBuffer(q);
10489         destroyPQExpBuffer(delq);
10490         destroyPQExpBuffer(labelq);
10491 }
10492
10493 /*
10494  * dumpOpfamily
10495  *        write out a single operator family definition
10496  *
10497  * Note: this also dumps any "loose" operator members that aren't bound to a
10498  * specific opclass within the opfamily.
10499  */
10500 static void
10501 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10502 {
10503         PQExpBuffer query;
10504         PQExpBuffer q;
10505         PQExpBuffer delq;
10506         PQExpBuffer labelq;
10507         PGresult   *res;
10508         PGresult   *res_ops;
10509         PGresult   *res_procs;
10510         int                     ntups;
10511         int                     i_amname;
10512         int                     i_amopstrategy;
10513         int                     i_amopreqcheck;
10514         int                     i_amopopr;
10515         int                     i_sortfamily;
10516         int                     i_sortfamilynsp;
10517         int                     i_amprocnum;
10518         int                     i_amproc;
10519         int                     i_amproclefttype;
10520         int                     i_amprocrighttype;
10521         char       *amname;
10522         char       *amopstrategy;
10523         char       *amopreqcheck;
10524         char       *amopopr;
10525         char       *sortfamily;
10526         char       *sortfamilynsp;
10527         char       *amprocnum;
10528         char       *amproc;
10529         char       *amproclefttype;
10530         char       *amprocrighttype;
10531         bool            needComma;
10532         int                     i;
10533
10534         /* Skip if not to be dumped */
10535         if (!opfinfo->dobj.dump || dataOnly)
10536                 return;
10537
10538         /*
10539          * We want to dump the opfamily only if (1) it contains "loose" operators
10540          * or functions, or (2) it contains an opclass with a different name or
10541          * owner.  Otherwise it's sufficient to let it be created during creation
10542          * of the contained opclass, and not dumping it improves portability of
10543          * the dump.  Since we have to fetch the loose operators/funcs anyway, do
10544          * that first.
10545          */
10546
10547         query = createPQExpBuffer();
10548         q = createPQExpBuffer();
10549         delq = createPQExpBuffer();
10550         labelq = createPQExpBuffer();
10551
10552         /* Make sure we are in proper schema so regoperator works correctly */
10553         selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10554
10555         /*
10556          * Fetch only those opfamily members that are tied directly to the
10557          * opfamily by pg_depend entries.
10558          *
10559          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10560          * older server's opclass in which it is used.  This is to avoid
10561          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10562          * older server and then reload into that old version.  This can go away
10563          * once 8.3 is so old as to not be of interest to anyone.
10564          */
10565         if (fout->remoteVersion >= 90100)
10566         {
10567                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10568                                                   "amopopr::pg_catalog.regoperator, "
10569                                                   "opfname AS sortfamily, "
10570                                                   "nspname AS sortfamilynsp "
10571                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10572                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10573                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10574                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10575                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10576                                                   "AND refobjid = '%u'::pg_catalog.oid "
10577                                                   "AND amopfamily = '%u'::pg_catalog.oid "
10578                                                   "ORDER BY amopstrategy",
10579                                                   opfinfo->dobj.catId.oid,
10580                                                   opfinfo->dobj.catId.oid);
10581         }
10582         else if (fout->remoteVersion >= 80400)
10583         {
10584                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10585                                                   "amopopr::pg_catalog.regoperator, "
10586                                                   "NULL AS sortfamily, "
10587                                                   "NULL AS sortfamilynsp "
10588                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10589                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10590                                                   "AND refobjid = '%u'::pg_catalog.oid "
10591                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10592                                                   "AND objid = ao.oid "
10593                                                   "ORDER BY amopstrategy",
10594                                                   opfinfo->dobj.catId.oid);
10595         }
10596         else
10597         {
10598                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10599                                                   "amopopr::pg_catalog.regoperator, "
10600                                                   "NULL AS sortfamily, "
10601                                                   "NULL AS sortfamilynsp "
10602                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10603                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10604                                                   "AND refobjid = '%u'::pg_catalog.oid "
10605                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10606                                                   "AND objid = ao.oid "
10607                                                   "ORDER BY amopstrategy",
10608                                                   opfinfo->dobj.catId.oid);
10609         }
10610
10611         res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10612
10613         resetPQExpBuffer(query);
10614
10615         appendPQExpBuffer(query, "SELECT amprocnum, "
10616                                           "amproc::pg_catalog.regprocedure, "
10617                                           "amproclefttype::pg_catalog.regtype, "
10618                                           "amprocrighttype::pg_catalog.regtype "
10619                                           "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10620                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10621                                           "AND refobjid = '%u'::pg_catalog.oid "
10622                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10623                                           "AND objid = ap.oid "
10624                                           "ORDER BY amprocnum",
10625                                           opfinfo->dobj.catId.oid);
10626
10627         res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10628
10629         if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10630         {
10631                 /* No loose members, so check contained opclasses */
10632                 resetPQExpBuffer(query);
10633
10634                 appendPQExpBuffer(query, "SELECT 1 "
10635                                                   "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10636                                                   "WHERE f.oid = '%u'::pg_catalog.oid "
10637                         "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10638                                                   "AND refobjid = f.oid "
10639                                 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10640                                                   "AND objid = c.oid "
10641                                                   "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10642                                                   "LIMIT 1",
10643                                                   opfinfo->dobj.catId.oid);
10644
10645                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10646
10647                 if (PQntuples(res) == 0)
10648                 {
10649                         /* no need to dump it, so bail out */
10650                         PQclear(res);
10651                         PQclear(res_ops);
10652                         PQclear(res_procs);
10653                         destroyPQExpBuffer(query);
10654                         destroyPQExpBuffer(q);
10655                         destroyPQExpBuffer(delq);
10656                         destroyPQExpBuffer(labelq);
10657                         return;
10658                 }
10659
10660                 PQclear(res);
10661         }
10662
10663         /* Get additional fields from the pg_opfamily row */
10664         resetPQExpBuffer(query);
10665
10666         appendPQExpBuffer(query, "SELECT "
10667          "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10668                                           "FROM pg_catalog.pg_opfamily "
10669                                           "WHERE oid = '%u'::pg_catalog.oid",
10670                                           opfinfo->dobj.catId.oid);
10671
10672         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10673
10674         i_amname = PQfnumber(res, "amname");
10675
10676         /* amname will still be needed after we PQclear res */
10677         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10678
10679         /*
10680          * DROP must be fully qualified in case same name appears in pg_catalog
10681          */
10682         appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10683                                           fmtId(opfinfo->dobj.namespace->dobj.name));
10684         appendPQExpBuffer(delq, ".%s",
10685                                           fmtId(opfinfo->dobj.name));
10686         appendPQExpBuffer(delq, " USING %s;\n",
10687                                           fmtId(amname));
10688
10689         /* Build the fixed portion of the CREATE command */
10690         appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10691                                           fmtId(opfinfo->dobj.name));
10692         appendPQExpBuffer(q, " USING %s;\n",
10693                                           fmtId(amname));
10694
10695         PQclear(res);
10696
10697         /* Do we need an ALTER to add loose members? */
10698         if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10699         {
10700                 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10701                                                   fmtId(opfinfo->dobj.name));
10702                 appendPQExpBuffer(q, " USING %s ADD\n    ",
10703                                                   fmtId(amname));
10704
10705                 needComma = false;
10706
10707                 /*
10708                  * Now fetch and print the OPERATOR entries (pg_amop rows).
10709                  */
10710                 ntups = PQntuples(res_ops);
10711
10712                 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10713                 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10714                 i_amopopr = PQfnumber(res_ops, "amopopr");
10715                 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10716                 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10717
10718                 for (i = 0; i < ntups; i++)
10719                 {
10720                         amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10721                         amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10722                         amopopr = PQgetvalue(res_ops, i, i_amopopr);
10723                         sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10724                         sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10725
10726                         if (needComma)
10727                                 appendPQExpBuffer(q, " ,\n    ");
10728
10729                         appendPQExpBuffer(q, "OPERATOR %s %s",
10730                                                           amopstrategy, amopopr);
10731
10732                         if (strlen(sortfamily) > 0)
10733                         {
10734                                 appendPQExpBuffer(q, " FOR ORDER BY ");
10735                                 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10736                                         appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10737                                 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10738                         }
10739
10740                         if (strcmp(amopreqcheck, "t") == 0)
10741                                 appendPQExpBuffer(q, " RECHECK");
10742
10743                         needComma = true;
10744                 }
10745
10746                 /*
10747                  * Now fetch and print the FUNCTION entries (pg_amproc rows).
10748                  */
10749                 ntups = PQntuples(res_procs);
10750
10751                 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10752                 i_amproc = PQfnumber(res_procs, "amproc");
10753                 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10754                 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10755
10756                 for (i = 0; i < ntups; i++)
10757                 {
10758                         amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10759                         amproc = PQgetvalue(res_procs, i, i_amproc);
10760                         amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10761                         amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10762
10763                         if (needComma)
10764                                 appendPQExpBuffer(q, " ,\n    ");
10765
10766                         appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10767                                                           amprocnum, amproclefttype, amprocrighttype,
10768                                                           amproc);
10769
10770                         needComma = true;
10771                 }
10772
10773                 appendPQExpBuffer(q, ";\n");
10774         }
10775
10776         appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10777                                           fmtId(opfinfo->dobj.name));
10778         appendPQExpBuffer(labelq, " USING %s",
10779                                           fmtId(amname));
10780
10781         if (binary_upgrade)
10782                 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10783
10784         ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10785                                  opfinfo->dobj.name,
10786                                  opfinfo->dobj.namespace->dobj.name,
10787                                  NULL,
10788                                  opfinfo->rolname,
10789                                  false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10790                                  q->data, delq->data, NULL,
10791                                  NULL, 0,
10792                                  NULL, NULL);
10793
10794         /* Dump Operator Family Comments */
10795         dumpComment(fout, labelq->data,
10796                                 NULL, opfinfo->rolname,
10797                                 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10798
10799         free(amname);
10800         PQclear(res_ops);
10801         PQclear(res_procs);
10802         destroyPQExpBuffer(query);
10803         destroyPQExpBuffer(q);
10804         destroyPQExpBuffer(delq);
10805         destroyPQExpBuffer(labelq);
10806 }
10807
10808 /*
10809  * dumpCollation
10810  *        write out a single collation definition
10811  */
10812 static void
10813 dumpCollation(Archive *fout, CollInfo *collinfo)
10814 {
10815         PQExpBuffer query;
10816         PQExpBuffer q;
10817         PQExpBuffer delq;
10818         PQExpBuffer labelq;
10819         PGresult   *res;
10820         int                     i_collcollate;
10821         int                     i_collctype;
10822         const char *collcollate;
10823         const char *collctype;
10824
10825         /* Skip if not to be dumped */
10826         if (!collinfo->dobj.dump || dataOnly)
10827                 return;
10828
10829         query = createPQExpBuffer();
10830         q = createPQExpBuffer();
10831         delq = createPQExpBuffer();
10832         labelq = createPQExpBuffer();
10833
10834         /* Make sure we are in proper schema */
10835         selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
10836
10837         /* Get conversion-specific details */
10838         appendPQExpBuffer(query, "SELECT "
10839                                           "collcollate, "
10840                                           "collctype "
10841                                           "FROM pg_catalog.pg_collation c "
10842                                           "WHERE c.oid = '%u'::pg_catalog.oid",
10843                                           collinfo->dobj.catId.oid);
10844
10845         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10846
10847         i_collcollate = PQfnumber(res, "collcollate");
10848         i_collctype = PQfnumber(res, "collctype");
10849
10850         collcollate = PQgetvalue(res, 0, i_collcollate);
10851         collctype = PQgetvalue(res, 0, i_collctype);
10852
10853         /*
10854          * DROP must be fully qualified in case same name appears in pg_catalog
10855          */
10856         appendPQExpBuffer(delq, "DROP COLLATION %s",
10857                                           fmtId(collinfo->dobj.namespace->dobj.name));
10858         appendPQExpBuffer(delq, ".%s;\n",
10859                                           fmtId(collinfo->dobj.name));
10860
10861         appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
10862                                           fmtId(collinfo->dobj.name));
10863         appendStringLiteralAH(q, collcollate, fout);
10864         appendPQExpBuffer(q, ", lc_ctype = ");
10865         appendStringLiteralAH(q, collctype, fout);
10866         appendPQExpBuffer(q, ");\n");
10867
10868         appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
10869
10870         if (binary_upgrade)
10871                 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
10872
10873         ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
10874                                  collinfo->dobj.name,
10875                                  collinfo->dobj.namespace->dobj.name,
10876                                  NULL,
10877                                  collinfo->rolname,
10878                                  false, "COLLATION", SECTION_PRE_DATA,
10879                                  q->data, delq->data, NULL,
10880                                  NULL, 0,
10881                                  NULL, NULL);
10882
10883         /* Dump Collation Comments */
10884         dumpComment(fout, labelq->data,
10885                                 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
10886                                 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
10887
10888         PQclear(res);
10889
10890         destroyPQExpBuffer(query);
10891         destroyPQExpBuffer(q);
10892         destroyPQExpBuffer(delq);
10893         destroyPQExpBuffer(labelq);
10894 }
10895
10896 /*
10897  * dumpConversion
10898  *        write out a single conversion definition
10899  */
10900 static void
10901 dumpConversion(Archive *fout, ConvInfo *convinfo)
10902 {
10903         PQExpBuffer query;
10904         PQExpBuffer q;
10905         PQExpBuffer delq;
10906         PQExpBuffer labelq;
10907         PGresult   *res;
10908         int                     i_conforencoding;
10909         int                     i_contoencoding;
10910         int                     i_conproc;
10911         int                     i_condefault;
10912         const char *conforencoding;
10913         const char *contoencoding;
10914         const char *conproc;
10915         bool            condefault;
10916
10917         /* Skip if not to be dumped */
10918         if (!convinfo->dobj.dump || dataOnly)
10919                 return;
10920
10921         query = createPQExpBuffer();
10922         q = createPQExpBuffer();
10923         delq = createPQExpBuffer();
10924         labelq = createPQExpBuffer();
10925
10926         /* Make sure we are in proper schema */
10927         selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
10928
10929         /* Get conversion-specific details */
10930         appendPQExpBuffer(query, "SELECT "
10931                  "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
10932                    "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
10933                                           "conproc, condefault "
10934                                           "FROM pg_catalog.pg_conversion c "
10935                                           "WHERE c.oid = '%u'::pg_catalog.oid",
10936                                           convinfo->dobj.catId.oid);
10937
10938         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10939
10940         i_conforencoding = PQfnumber(res, "conforencoding");
10941         i_contoencoding = PQfnumber(res, "contoencoding");
10942         i_conproc = PQfnumber(res, "conproc");
10943         i_condefault = PQfnumber(res, "condefault");
10944
10945         conforencoding = PQgetvalue(res, 0, i_conforencoding);
10946         contoencoding = PQgetvalue(res, 0, i_contoencoding);
10947         conproc = PQgetvalue(res, 0, i_conproc);
10948         condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
10949
10950         /*
10951          * DROP must be fully qualified in case same name appears in pg_catalog
10952          */
10953         appendPQExpBuffer(delq, "DROP CONVERSION %s",
10954                                           fmtId(convinfo->dobj.namespace->dobj.name));
10955         appendPQExpBuffer(delq, ".%s;\n",
10956                                           fmtId(convinfo->dobj.name));
10957
10958         appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
10959                                           (condefault) ? "DEFAULT " : "",
10960                                           fmtId(convinfo->dobj.name));
10961         appendStringLiteralAH(q, conforencoding, fout);
10962         appendPQExpBuffer(q, " TO ");
10963         appendStringLiteralAH(q, contoencoding, fout);
10964         /* regproc is automatically quoted in 7.3 and above */
10965         appendPQExpBuffer(q, " FROM %s;\n", conproc);
10966
10967         appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
10968
10969         if (binary_upgrade)
10970                 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
10971
10972         ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
10973                                  convinfo->dobj.name,
10974                                  convinfo->dobj.namespace->dobj.name,
10975                                  NULL,
10976                                  convinfo->rolname,
10977                                  false, "CONVERSION", SECTION_PRE_DATA,
10978                                  q->data, delq->data, NULL,
10979                                  NULL, 0,
10980                                  NULL, NULL);
10981
10982         /* Dump Conversion Comments */
10983         dumpComment(fout, labelq->data,
10984                                 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
10985                                 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
10986
10987         PQclear(res);
10988
10989         destroyPQExpBuffer(query);
10990         destroyPQExpBuffer(q);
10991         destroyPQExpBuffer(delq);
10992         destroyPQExpBuffer(labelq);
10993 }
10994
10995 /*
10996  * format_aggregate_signature: generate aggregate name and argument list
10997  *
10998  * The argument type names are qualified if needed.  The aggregate name
10999  * is never qualified.
11000  */
11001 static char *
11002 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
11003 {
11004         PQExpBufferData buf;
11005         int                     j;
11006
11007         initPQExpBuffer(&buf);
11008         if (honor_quotes)
11009                 appendPQExpBuffer(&buf, "%s",
11010                                                   fmtId(agginfo->aggfn.dobj.name));
11011         else
11012                 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
11013
11014         if (agginfo->aggfn.nargs == 0)
11015                 appendPQExpBuffer(&buf, "(*)");
11016         else
11017         {
11018                 appendPQExpBuffer(&buf, "(");
11019                 for (j = 0; j < agginfo->aggfn.nargs; j++)
11020                 {
11021                         char       *typname;
11022
11023                         typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
11024                                                                                    zeroAsOpaque);
11025
11026                         appendPQExpBuffer(&buf, "%s%s",
11027                                                           (j > 0) ? ", " : "",
11028                                                           typname);
11029                         free(typname);
11030                 }
11031                 appendPQExpBuffer(&buf, ")");
11032         }
11033         return buf.data;
11034 }
11035
11036 /*
11037  * dumpAgg
11038  *        write out a single aggregate definition
11039  */
11040 static void
11041 dumpAgg(Archive *fout, AggInfo *agginfo)
11042 {
11043         PQExpBuffer query;
11044         PQExpBuffer q;
11045         PQExpBuffer delq;
11046         PQExpBuffer labelq;
11047         PQExpBuffer details;
11048         char       *aggsig;
11049         char       *aggsig_tag;
11050         PGresult   *res;
11051         int                     i_aggtransfn;
11052         int                     i_aggfinalfn;
11053         int                     i_aggsortop;
11054         int                     i_aggtranstype;
11055         int                     i_agginitval;
11056         int                     i_convertok;
11057         const char *aggtransfn;
11058         const char *aggfinalfn;
11059         const char *aggsortop;
11060         const char *aggtranstype;
11061         const char *agginitval;
11062         bool            convertok;
11063
11064         /* Skip if not to be dumped */
11065         if (!agginfo->aggfn.dobj.dump || dataOnly)
11066                 return;
11067
11068         query = createPQExpBuffer();
11069         q = createPQExpBuffer();
11070         delq = createPQExpBuffer();
11071         labelq = createPQExpBuffer();
11072         details = createPQExpBuffer();
11073
11074         /* Make sure we are in proper schema */
11075         selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
11076
11077         /* Get aggregate-specific details */
11078         if (fout->remoteVersion >= 80100)
11079         {
11080                 appendPQExpBuffer(query, "SELECT aggtransfn, "
11081                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11082                                                   "aggsortop::pg_catalog.regoperator, "
11083                                                   "agginitval, "
11084                                                   "'t'::boolean AS convertok "
11085                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11086                                                   "WHERE a.aggfnoid = p.oid "
11087                                                   "AND p.oid = '%u'::pg_catalog.oid",
11088                                                   agginfo->aggfn.dobj.catId.oid);
11089         }
11090         else if (fout->remoteVersion >= 70300)
11091         {
11092                 appendPQExpBuffer(query, "SELECT aggtransfn, "
11093                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11094                                                   "0 AS aggsortop, "
11095                                                   "agginitval, "
11096                                                   "'t'::boolean AS convertok "
11097                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11098                                                   "WHERE a.aggfnoid = p.oid "
11099                                                   "AND p.oid = '%u'::pg_catalog.oid",
11100                                                   agginfo->aggfn.dobj.catId.oid);
11101         }
11102         else if (fout->remoteVersion >= 70100)
11103         {
11104                 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
11105                                                   "format_type(aggtranstype, NULL) AS aggtranstype, "
11106                                                   "0 AS aggsortop, "
11107                                                   "agginitval, "
11108                                                   "'t'::boolean AS convertok "
11109                                                   "FROM pg_aggregate "
11110                                                   "WHERE oid = '%u'::oid",
11111                                                   agginfo->aggfn.dobj.catId.oid);
11112         }
11113         else
11114         {
11115                 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
11116                                                   "aggfinalfn, "
11117                                                   "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
11118                                                   "0 AS aggsortop, "
11119                                                   "agginitval1 AS agginitval, "
11120                                                   "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
11121                                                   "FROM pg_aggregate "
11122                                                   "WHERE oid = '%u'::oid",
11123                                                   agginfo->aggfn.dobj.catId.oid);
11124         }
11125
11126         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11127
11128         i_aggtransfn = PQfnumber(res, "aggtransfn");
11129         i_aggfinalfn = PQfnumber(res, "aggfinalfn");
11130         i_aggsortop = PQfnumber(res, "aggsortop");
11131         i_aggtranstype = PQfnumber(res, "aggtranstype");
11132         i_agginitval = PQfnumber(res, "agginitval");
11133         i_convertok = PQfnumber(res, "convertok");
11134
11135         aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
11136         aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
11137         aggsortop = PQgetvalue(res, 0, i_aggsortop);
11138         aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
11139         agginitval = PQgetvalue(res, 0, i_agginitval);
11140         convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
11141
11142         aggsig = format_aggregate_signature(agginfo, fout, true);
11143         aggsig_tag = format_aggregate_signature(agginfo, fout, false);
11144
11145         if (!convertok)
11146         {
11147                 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
11148                                   aggsig);
11149                 return;
11150         }
11151
11152         if (fout->remoteVersion >= 70300)
11153         {
11154                 /* If using 7.3's regproc or regtype, data is already quoted */
11155                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
11156                                                   aggtransfn,
11157                                                   aggtranstype);
11158         }
11159         else if (fout->remoteVersion >= 70100)
11160         {
11161                 /* format_type quotes, regproc does not */
11162                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
11163                                                   fmtId(aggtransfn),
11164                                                   aggtranstype);
11165         }
11166         else
11167         {
11168                 /* need quotes all around */
11169                 appendPQExpBuffer(details, "    SFUNC = %s,\n",
11170                                                   fmtId(aggtransfn));
11171                 appendPQExpBuffer(details, "    STYPE = %s",
11172                                                   fmtId(aggtranstype));
11173         }
11174
11175         if (!PQgetisnull(res, 0, i_agginitval))
11176         {
11177                 appendPQExpBuffer(details, ",\n    INITCOND = ");
11178                 appendStringLiteralAH(details, agginitval, fout);
11179         }
11180
11181         if (strcmp(aggfinalfn, "-") != 0)
11182         {
11183                 appendPQExpBuffer(details, ",\n    FINALFUNC = %s",
11184                                                   aggfinalfn);
11185         }
11186
11187         aggsortop = convertOperatorReference(fout, aggsortop);
11188         if (aggsortop)
11189         {
11190                 appendPQExpBuffer(details, ",\n    SORTOP = %s",
11191                                                   aggsortop);
11192         }
11193
11194         /*
11195          * DROP must be fully qualified in case same name appears in pg_catalog
11196          */
11197         appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
11198                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
11199                                           aggsig);
11200
11201         appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
11202                                           aggsig, details->data);
11203
11204         appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
11205
11206         if (binary_upgrade)
11207                 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
11208
11209         ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11210                                  aggsig_tag,
11211                                  agginfo->aggfn.dobj.namespace->dobj.name,
11212                                  NULL,
11213                                  agginfo->aggfn.rolname,
11214                                  false, "AGGREGATE", SECTION_PRE_DATA,
11215                                  q->data, delq->data, NULL,
11216                                  NULL, 0,
11217                                  NULL, NULL);
11218
11219         /* Dump Aggregate Comments */
11220         dumpComment(fout, labelq->data,
11221                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11222                                 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11223         dumpSecLabel(fout, labelq->data,
11224                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11225                                  agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11226
11227         /*
11228          * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
11229          * command look like a function's GRANT; in particular this affects the
11230          * syntax for zero-argument aggregates.
11231          */
11232         free(aggsig);
11233         free(aggsig_tag);
11234
11235         aggsig = format_function_signature(fout, &agginfo->aggfn, true);
11236         aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
11237
11238         dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11239                         "FUNCTION",
11240                         aggsig, NULL, aggsig_tag,
11241                         agginfo->aggfn.dobj.namespace->dobj.name,
11242                         agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11243
11244         free(aggsig);
11245         free(aggsig_tag);
11246
11247         PQclear(res);
11248
11249         destroyPQExpBuffer(query);
11250         destroyPQExpBuffer(q);
11251         destroyPQExpBuffer(delq);
11252         destroyPQExpBuffer(labelq);
11253         destroyPQExpBuffer(details);
11254 }
11255
11256 /*
11257  * dumpTSParser
11258  *        write out a single text search parser
11259  */
11260 static void
11261 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11262 {
11263         PQExpBuffer q;
11264         PQExpBuffer delq;
11265         PQExpBuffer labelq;
11266
11267         /* Skip if not to be dumped */
11268         if (!prsinfo->dobj.dump || dataOnly)
11269                 return;
11270
11271         q = createPQExpBuffer();
11272         delq = createPQExpBuffer();
11273         labelq = createPQExpBuffer();
11274
11275         /* Make sure we are in proper schema */
11276         selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11277
11278         appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11279                                           fmtId(prsinfo->dobj.name));
11280
11281         appendPQExpBuffer(q, "    START = %s,\n",
11282                                           convertTSFunction(fout, prsinfo->prsstart));
11283         appendPQExpBuffer(q, "    GETTOKEN = %s,\n",
11284                                           convertTSFunction(fout, prsinfo->prstoken));
11285         appendPQExpBuffer(q, "    END = %s,\n",
11286                                           convertTSFunction(fout, prsinfo->prsend));
11287         if (prsinfo->prsheadline != InvalidOid)
11288                 appendPQExpBuffer(q, "    HEADLINE = %s,\n",
11289                                                   convertTSFunction(fout, prsinfo->prsheadline));
11290         appendPQExpBuffer(q, "    LEXTYPES = %s );\n",
11291                                           convertTSFunction(fout, prsinfo->prslextype));
11292
11293         /*
11294          * DROP must be fully qualified in case same name appears in pg_catalog
11295          */
11296         appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11297                                           fmtId(prsinfo->dobj.namespace->dobj.name));
11298         appendPQExpBuffer(delq, ".%s;\n",
11299                                           fmtId(prsinfo->dobj.name));
11300
11301         appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11302                                           fmtId(prsinfo->dobj.name));
11303
11304         if (binary_upgrade)
11305                 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11306
11307         ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11308                                  prsinfo->dobj.name,
11309                                  prsinfo->dobj.namespace->dobj.name,
11310                                  NULL,
11311                                  "",
11312                                  false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11313                                  q->data, delq->data, NULL,
11314                                  NULL, 0,
11315                                  NULL, NULL);
11316
11317         /* Dump Parser Comments */
11318         dumpComment(fout, labelq->data,
11319                                 NULL, "",
11320                                 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11321
11322         destroyPQExpBuffer(q);
11323         destroyPQExpBuffer(delq);
11324         destroyPQExpBuffer(labelq);
11325 }
11326
11327 /*
11328  * dumpTSDictionary
11329  *        write out a single text search dictionary
11330  */
11331 static void
11332 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11333 {
11334         PQExpBuffer q;
11335         PQExpBuffer delq;
11336         PQExpBuffer labelq;
11337         PQExpBuffer query;
11338         PGresult   *res;
11339         char       *nspname;
11340         char       *tmplname;
11341
11342         /* Skip if not to be dumped */
11343         if (!dictinfo->dobj.dump || dataOnly)
11344                 return;
11345
11346         q = createPQExpBuffer();
11347         delq = createPQExpBuffer();
11348         labelq = createPQExpBuffer();
11349         query = createPQExpBuffer();
11350
11351         /* Fetch name and namespace of the dictionary's template */
11352         selectSourceSchema(fout, "pg_catalog");
11353         appendPQExpBuffer(query, "SELECT nspname, tmplname "
11354                                           "FROM pg_ts_template p, pg_namespace n "
11355                                           "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11356                                           dictinfo->dicttemplate);
11357         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11358         nspname = PQgetvalue(res, 0, 0);
11359         tmplname = PQgetvalue(res, 0, 1);
11360
11361         /* Make sure we are in proper schema */
11362         selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11363
11364         appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11365                                           fmtId(dictinfo->dobj.name));
11366
11367         appendPQExpBuffer(q, "    TEMPLATE = ");
11368         if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11369                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11370         appendPQExpBuffer(q, "%s", fmtId(tmplname));
11371
11372         PQclear(res);
11373
11374         /* the dictinitoption can be dumped straight into the command */
11375         if (dictinfo->dictinitoption)
11376                 appendPQExpBuffer(q, ",\n    %s", dictinfo->dictinitoption);
11377
11378         appendPQExpBuffer(q, " );\n");
11379
11380         /*
11381          * DROP must be fully qualified in case same name appears in pg_catalog
11382          */
11383         appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11384                                           fmtId(dictinfo->dobj.namespace->dobj.name));
11385         appendPQExpBuffer(delq, ".%s;\n",
11386                                           fmtId(dictinfo->dobj.name));
11387
11388         appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11389                                           fmtId(dictinfo->dobj.name));
11390
11391         if (binary_upgrade)
11392                 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11393
11394         ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11395                                  dictinfo->dobj.name,
11396                                  dictinfo->dobj.namespace->dobj.name,
11397                                  NULL,
11398                                  dictinfo->rolname,
11399                                  false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11400                                  q->data, delq->data, NULL,
11401                                  NULL, 0,
11402                                  NULL, NULL);
11403
11404         /* Dump Dictionary Comments */
11405         dumpComment(fout, labelq->data,
11406                                 NULL, dictinfo->rolname,
11407                                 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11408
11409         destroyPQExpBuffer(q);
11410         destroyPQExpBuffer(delq);
11411         destroyPQExpBuffer(labelq);
11412         destroyPQExpBuffer(query);
11413 }
11414
11415 /*
11416  * dumpTSTemplate
11417  *        write out a single text search template
11418  */
11419 static void
11420 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11421 {
11422         PQExpBuffer q;
11423         PQExpBuffer delq;
11424         PQExpBuffer labelq;
11425
11426         /* Skip if not to be dumped */
11427         if (!tmplinfo->dobj.dump || dataOnly)
11428                 return;
11429
11430         q = createPQExpBuffer();
11431         delq = createPQExpBuffer();
11432         labelq = createPQExpBuffer();
11433
11434         /* Make sure we are in proper schema */
11435         selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11436
11437         appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11438                                           fmtId(tmplinfo->dobj.name));
11439
11440         if (tmplinfo->tmplinit != InvalidOid)
11441                 appendPQExpBuffer(q, "    INIT = %s,\n",
11442                                                   convertTSFunction(fout, tmplinfo->tmplinit));
11443         appendPQExpBuffer(q, "    LEXIZE = %s );\n",
11444                                           convertTSFunction(fout, tmplinfo->tmpllexize));
11445
11446         /*
11447          * DROP must be fully qualified in case same name appears in pg_catalog
11448          */
11449         appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11450                                           fmtId(tmplinfo->dobj.namespace->dobj.name));
11451         appendPQExpBuffer(delq, ".%s;\n",
11452                                           fmtId(tmplinfo->dobj.name));
11453
11454         appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11455                                           fmtId(tmplinfo->dobj.name));
11456
11457         if (binary_upgrade)
11458                 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11459
11460         ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11461                                  tmplinfo->dobj.name,
11462                                  tmplinfo->dobj.namespace->dobj.name,
11463                                  NULL,
11464                                  "",
11465                                  false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11466                                  q->data, delq->data, NULL,
11467                                  NULL, 0,
11468                                  NULL, NULL);
11469
11470         /* Dump Template Comments */
11471         dumpComment(fout, labelq->data,
11472                                 NULL, "",
11473                                 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11474
11475         destroyPQExpBuffer(q);
11476         destroyPQExpBuffer(delq);
11477         destroyPQExpBuffer(labelq);
11478 }
11479
11480 /*
11481  * dumpTSConfig
11482  *        write out a single text search configuration
11483  */
11484 static void
11485 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11486 {
11487         PQExpBuffer q;
11488         PQExpBuffer delq;
11489         PQExpBuffer labelq;
11490         PQExpBuffer query;
11491         PGresult   *res;
11492         char       *nspname;
11493         char       *prsname;
11494         int                     ntups,
11495                                 i;
11496         int                     i_tokenname;
11497         int                     i_dictname;
11498
11499         /* Skip if not to be dumped */
11500         if (!cfginfo->dobj.dump || dataOnly)
11501                 return;
11502
11503         q = createPQExpBuffer();
11504         delq = createPQExpBuffer();
11505         labelq = createPQExpBuffer();
11506         query = createPQExpBuffer();
11507
11508         /* Fetch name and namespace of the config's parser */
11509         selectSourceSchema(fout, "pg_catalog");
11510         appendPQExpBuffer(query, "SELECT nspname, prsname "
11511                                           "FROM pg_ts_parser p, pg_namespace n "
11512                                           "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11513                                           cfginfo->cfgparser);
11514         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11515         nspname = PQgetvalue(res, 0, 0);
11516         prsname = PQgetvalue(res, 0, 1);
11517
11518         /* Make sure we are in proper schema */
11519         selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11520
11521         appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11522                                           fmtId(cfginfo->dobj.name));
11523
11524         appendPQExpBuffer(q, "    PARSER = ");
11525         if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11526                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11527         appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11528
11529         PQclear(res);
11530
11531         resetPQExpBuffer(query);
11532         appendPQExpBuffer(query,
11533                                           "SELECT \n"
11534                                           "  ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11535                                           "    WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11536                                           "  m.mapdict::pg_catalog.regdictionary AS dictname \n"
11537                                           "FROM pg_catalog.pg_ts_config_map AS m \n"
11538                                           "WHERE m.mapcfg = '%u' \n"
11539                                           "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11540                                           cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11541
11542         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11543         ntups = PQntuples(res);
11544
11545         i_tokenname = PQfnumber(res, "tokenname");
11546         i_dictname = PQfnumber(res, "dictname");
11547
11548         for (i = 0; i < ntups; i++)
11549         {
11550                 char       *tokenname = PQgetvalue(res, i, i_tokenname);
11551                 char       *dictname = PQgetvalue(res, i, i_dictname);
11552
11553                 if (i == 0 ||
11554                         strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11555                 {
11556                         /* starting a new token type, so start a new command */
11557                         if (i > 0)
11558                                 appendPQExpBuffer(q, ";\n");
11559                         appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11560                                                           fmtId(cfginfo->dobj.name));
11561                         /* tokenname needs quoting, dictname does NOT */
11562                         appendPQExpBuffer(q, "    ADD MAPPING FOR %s WITH %s",
11563                                                           fmtId(tokenname), dictname);
11564                 }
11565                 else
11566                         appendPQExpBuffer(q, ", %s", dictname);
11567         }
11568
11569         if (ntups > 0)
11570                 appendPQExpBuffer(q, ";\n");
11571
11572         PQclear(res);
11573
11574         /*
11575          * DROP must be fully qualified in case same name appears in pg_catalog
11576          */
11577         appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11578                                           fmtId(cfginfo->dobj.namespace->dobj.name));
11579         appendPQExpBuffer(delq, ".%s;\n",
11580                                           fmtId(cfginfo->dobj.name));
11581
11582         appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11583                                           fmtId(cfginfo->dobj.name));
11584
11585         if (binary_upgrade)
11586                 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11587
11588         ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11589                                  cfginfo->dobj.name,
11590                                  cfginfo->dobj.namespace->dobj.name,
11591                                  NULL,
11592                                  cfginfo->rolname,
11593                                  false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11594                                  q->data, delq->data, NULL,
11595                                  NULL, 0,
11596                                  NULL, NULL);
11597
11598         /* Dump Configuration Comments */
11599         dumpComment(fout, labelq->data,
11600                                 NULL, cfginfo->rolname,
11601                                 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11602
11603         destroyPQExpBuffer(q);
11604         destroyPQExpBuffer(delq);
11605         destroyPQExpBuffer(labelq);
11606         destroyPQExpBuffer(query);
11607 }
11608
11609 /*
11610  * dumpForeignDataWrapper
11611  *        write out a single foreign-data wrapper definition
11612  */
11613 static void
11614 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11615 {
11616         PQExpBuffer q;
11617         PQExpBuffer delq;
11618         PQExpBuffer labelq;
11619         char       *qfdwname;
11620
11621         /* Skip if not to be dumped */
11622         if (!fdwinfo->dobj.dump || dataOnly)
11623                 return;
11624
11625         /*
11626          * FDWs that belong to an extension are dumped based on their "dump"
11627          * field. Otherwise omit them if we are only dumping some specific object.
11628          */
11629         if (!fdwinfo->dobj.ext_member)
11630                 if (!include_everything)
11631                         return;
11632
11633         q = createPQExpBuffer();
11634         delq = createPQExpBuffer();
11635         labelq = createPQExpBuffer();
11636
11637         qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11638
11639         appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11640                                           qfdwname);
11641
11642         if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11643                 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11644
11645         if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11646                 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11647
11648         if (strlen(fdwinfo->fdwoptions) > 0)
11649                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", fdwinfo->fdwoptions);
11650
11651         appendPQExpBuffer(q, ";\n");
11652
11653         appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11654                                           qfdwname);
11655
11656         appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11657                                           qfdwname);
11658
11659         if (binary_upgrade)
11660                 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11661
11662         ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11663                                  fdwinfo->dobj.name,
11664                                  NULL,
11665                                  NULL,
11666                                  fdwinfo->rolname,
11667                                  false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11668                                  q->data, delq->data, NULL,
11669                                  NULL, 0,
11670                                  NULL, NULL);
11671
11672         /* Handle the ACL */
11673         dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11674                         "FOREIGN DATA WRAPPER",
11675                         qfdwname, NULL, fdwinfo->dobj.name,
11676                         NULL, fdwinfo->rolname,
11677                         fdwinfo->fdwacl);
11678
11679         /* Dump Foreign Data Wrapper Comments */
11680         dumpComment(fout, labelq->data,
11681                                 NULL, fdwinfo->rolname,
11682                                 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11683
11684         free(qfdwname);
11685
11686         destroyPQExpBuffer(q);
11687         destroyPQExpBuffer(delq);
11688         destroyPQExpBuffer(labelq);
11689 }
11690
11691 /*
11692  * dumpForeignServer
11693  *        write out a foreign server definition
11694  */
11695 static void
11696 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11697 {
11698         PQExpBuffer q;
11699         PQExpBuffer delq;
11700         PQExpBuffer labelq;
11701         PQExpBuffer query;
11702         PGresult   *res;
11703         char       *qsrvname;
11704         char       *fdwname;
11705
11706         /* Skip if not to be dumped */
11707         if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11708                 return;
11709
11710         q = createPQExpBuffer();
11711         delq = createPQExpBuffer();
11712         labelq = createPQExpBuffer();
11713         query = createPQExpBuffer();
11714
11715         qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11716
11717         /* look up the foreign-data wrapper */
11718         selectSourceSchema(fout, "pg_catalog");
11719         appendPQExpBuffer(query, "SELECT fdwname "
11720                                           "FROM pg_foreign_data_wrapper w "
11721                                           "WHERE w.oid = '%u'",
11722                                           srvinfo->srvfdw);
11723         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11724         fdwname = PQgetvalue(res, 0, 0);
11725
11726         appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11727         if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11728         {
11729                 appendPQExpBuffer(q, " TYPE ");
11730                 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11731         }
11732         if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11733         {
11734                 appendPQExpBuffer(q, " VERSION ");
11735                 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11736         }
11737
11738         appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11739         appendPQExpBuffer(q, "%s", fmtId(fdwname));
11740
11741         if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11742                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", srvinfo->srvoptions);
11743
11744         appendPQExpBuffer(q, ";\n");
11745
11746         appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11747                                           qsrvname);
11748
11749         appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11750
11751         if (binary_upgrade)
11752                 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11753
11754         ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11755                                  srvinfo->dobj.name,
11756                                  NULL,
11757                                  NULL,
11758                                  srvinfo->rolname,
11759                                  false, "SERVER", SECTION_PRE_DATA,
11760                                  q->data, delq->data, NULL,
11761                                  NULL, 0,
11762                                  NULL, NULL);
11763
11764         /* Handle the ACL */
11765         dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11766                         "FOREIGN SERVER",
11767                         qsrvname, NULL, srvinfo->dobj.name,
11768                         NULL, srvinfo->rolname,
11769                         srvinfo->srvacl);
11770
11771         /* Dump user mappings */
11772         dumpUserMappings(fout,
11773                                          srvinfo->dobj.name, NULL,
11774                                          srvinfo->rolname,
11775                                          srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11776
11777         /* Dump Foreign Server Comments */
11778         dumpComment(fout, labelq->data,
11779                                 NULL, srvinfo->rolname,
11780                                 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11781
11782         free(qsrvname);
11783
11784         destroyPQExpBuffer(q);
11785         destroyPQExpBuffer(delq);
11786         destroyPQExpBuffer(labelq);
11787 }
11788
11789 /*
11790  * dumpUserMappings
11791  *
11792  * This routine is used to dump any user mappings associated with the
11793  * server handed to this routine. Should be called after ArchiveEntry()
11794  * for the server.
11795  */
11796 static void
11797 dumpUserMappings(Archive *fout,
11798                                  const char *servername, const char *namespace,
11799                                  const char *owner,
11800                                  CatalogId catalogId, DumpId dumpId)
11801 {
11802         PQExpBuffer q;
11803         PQExpBuffer delq;
11804         PQExpBuffer query;
11805         PQExpBuffer tag;
11806         PGresult   *res;
11807         int                     ntups;
11808         int                     i_usename;
11809         int                     i_umoptions;
11810         int                     i;
11811
11812         q = createPQExpBuffer();
11813         tag = createPQExpBuffer();
11814         delq = createPQExpBuffer();
11815         query = createPQExpBuffer();
11816
11817         /*
11818          * We read from the publicly accessible view pg_user_mappings, so as not
11819          * to fail if run by a non-superuser.  Note that the view will show
11820          * umoptions as null if the user hasn't got privileges for the associated
11821          * server; this means that pg_dump will dump such a mapping, but with no
11822          * OPTIONS clause.      A possible alternative is to skip such mappings
11823          * altogether, but it's not clear that that's an improvement.
11824          */
11825         selectSourceSchema(fout, "pg_catalog");
11826
11827         appendPQExpBuffer(query,
11828                                           "SELECT usename, "
11829                                           "array_to_string(ARRAY("
11830                                           "SELECT quote_ident(option_name) || ' ' || "
11831                                           "quote_literal(option_value) "
11832                                           "FROM pg_options_to_table(umoptions) "
11833                                           "ORDER BY option_name"
11834                                           "), E',\n    ') AS umoptions "
11835                                           "FROM pg_user_mappings "
11836                                           "WHERE srvid = '%u' "
11837                                           "ORDER BY usename",
11838                                           catalogId.oid);
11839
11840         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11841
11842         ntups = PQntuples(res);
11843         i_usename = PQfnumber(res, "usename");
11844         i_umoptions = PQfnumber(res, "umoptions");
11845
11846         for (i = 0; i < ntups; i++)
11847         {
11848                 char       *usename;
11849                 char       *umoptions;
11850
11851                 usename = PQgetvalue(res, i, i_usename);
11852                 umoptions = PQgetvalue(res, i, i_umoptions);
11853
11854                 resetPQExpBuffer(q);
11855                 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
11856                 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
11857
11858                 if (umoptions && strlen(umoptions) > 0)
11859                         appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", umoptions);
11860
11861                 appendPQExpBuffer(q, ";\n");
11862
11863                 resetPQExpBuffer(delq);
11864                 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
11865                 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
11866
11867                 resetPQExpBuffer(tag);
11868                 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
11869                                                   usename, servername);
11870
11871                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11872                                          tag->data,
11873                                          namespace,
11874                                          NULL,
11875                                          owner, false,
11876                                          "USER MAPPING", SECTION_PRE_DATA,
11877                                          q->data, delq->data, NULL,
11878                                          &dumpId, 1,
11879                                          NULL, NULL);
11880         }
11881
11882         PQclear(res);
11883
11884         destroyPQExpBuffer(query);
11885         destroyPQExpBuffer(delq);
11886         destroyPQExpBuffer(q);
11887 }
11888
11889 /*
11890  * Write out default privileges information
11891  */
11892 static void
11893 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
11894 {
11895         PQExpBuffer q;
11896         PQExpBuffer tag;
11897         const char *type;
11898
11899         /* Skip if not to be dumped */
11900         if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
11901                 return;
11902
11903         q = createPQExpBuffer();
11904         tag = createPQExpBuffer();
11905
11906         switch (daclinfo->defaclobjtype)
11907         {
11908                 case DEFACLOBJ_RELATION:
11909                         type = "TABLES";
11910                         break;
11911                 case DEFACLOBJ_SEQUENCE:
11912                         type = "SEQUENCES";
11913                         break;
11914                 case DEFACLOBJ_FUNCTION:
11915                         type = "FUNCTIONS";
11916                         break;
11917                 case DEFACLOBJ_TYPE:
11918                         type = "TYPES";
11919                         break;
11920                 default:
11921                         /* shouldn't get here */
11922                         exit_horribly(NULL,
11923                                                   "unrecognized object type in default privileges: %d\n",
11924                                                   (int) daclinfo->defaclobjtype);
11925                         type = "";                      /* keep compiler quiet */
11926         }
11927
11928         appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
11929
11930         /* build the actual command(s) for this tuple */
11931         if (!buildDefaultACLCommands(type,
11932                                                                  daclinfo->dobj.namespace != NULL ?
11933                                                                  daclinfo->dobj.namespace->dobj.name : NULL,
11934                                                                  daclinfo->defaclacl,
11935                                                                  daclinfo->defaclrole,
11936                                                                  fout->remoteVersion,
11937                                                                  q))
11938                 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
11939                                           daclinfo->defaclacl);
11940
11941         ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
11942                                  tag->data,
11943            daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
11944                                  NULL,
11945                                  daclinfo->defaclrole,
11946                                  false, "DEFAULT ACL", SECTION_POST_DATA,
11947                                  q->data, "", NULL,
11948                                  NULL, 0,
11949                                  NULL, NULL);
11950
11951         destroyPQExpBuffer(tag);
11952         destroyPQExpBuffer(q);
11953 }
11954
11955 /*----------
11956  * Write out grant/revoke information
11957  *
11958  * 'objCatId' is the catalog ID of the underlying object.
11959  * 'objDumpId' is the dump ID of the underlying object.
11960  * 'type' must be one of
11961  *              TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
11962  *              FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
11963  * 'name' is the formatted name of the object.  Must be quoted etc. already.
11964  * 'subname' is the formatted name of the sub-object, if any.  Must be quoted.
11965  * 'tag' is the tag for the archive entry (typ. unquoted name of object).
11966  * 'nspname' is the namespace the object is in (NULL if none).
11967  * 'owner' is the owner, NULL if there is no owner (for languages).
11968  * 'acls' is the string read out of the fooacl system catalog field;
11969  *              it will be parsed here.
11970  *----------
11971  */
11972 static void
11973 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
11974                 const char *type, const char *name, const char *subname,
11975                 const char *tag, const char *nspname, const char *owner,
11976                 const char *acls)
11977 {
11978         PQExpBuffer sql;
11979
11980         /* Do nothing if ACL dump is not enabled */
11981         if (aclsSkip)
11982                 return;
11983
11984         /* --data-only skips ACLs *except* BLOB ACLs */
11985         if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
11986                 return;
11987
11988         sql = createPQExpBuffer();
11989
11990         if (!buildACLCommands(name, subname, type, acls, owner,
11991                                                   "", fout->remoteVersion, sql))
11992                 exit_horribly(NULL,
11993                                         "could not parse ACL list (%s) for object \"%s\" (%s)\n",
11994                                           acls, name, type);
11995
11996         if (sql->len > 0)
11997                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11998                                          tag, nspname,
11999                                          NULL,
12000                                          owner ? owner : "",
12001                                          false, "ACL", SECTION_NONE,
12002                                          sql->data, "", NULL,
12003                                          &(objDumpId), 1,
12004                                          NULL, NULL);
12005
12006         destroyPQExpBuffer(sql);
12007 }
12008
12009 /*
12010  * dumpSecLabel
12011  *
12012  * This routine is used to dump any security labels associated with the
12013  * object handed to this routine. The routine takes a constant character
12014  * string for the target part of the security-label command, plus
12015  * the namespace and owner of the object (for labeling the ArchiveEntry),
12016  * plus catalog ID and subid which are the lookup key for pg_seclabel,
12017  * plus the dump ID for the object (for setting a dependency).
12018  * If a matching pg_seclabel entry is found, it is dumped.
12019  *
12020  * Note: although this routine takes a dumpId for dependency purposes,
12021  * that purpose is just to mark the dependency in the emitted dump file
12022  * for possible future use by pg_restore.  We do NOT use it for determining
12023  * ordering of the label in the dump file, because this routine is called
12024  * after dependency sorting occurs.  This routine should be called just after
12025  * calling ArchiveEntry() for the specified object.
12026  */
12027 static void
12028 dumpSecLabel(Archive *fout, const char *target,
12029                          const char *namespace, const char *owner,
12030                          CatalogId catalogId, int subid, DumpId dumpId)
12031 {
12032         SecLabelItem *labels;
12033         int                     nlabels;
12034         int                     i;
12035         PQExpBuffer query;
12036
12037         /* do nothing, if --no-security-labels is supplied */
12038         if (no_security_labels)
12039                 return;
12040
12041         /* Comments are schema not data ... except blob comments are data */
12042         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
12043         {
12044                 if (dataOnly)
12045                         return;
12046         }
12047         else
12048         {
12049                 if (schemaOnly)
12050                         return;
12051         }
12052
12053         /* Search for security labels associated with catalogId, using table */
12054         nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
12055
12056         query = createPQExpBuffer();
12057
12058         for (i = 0; i < nlabels; i++)
12059         {
12060                 /*
12061                  * Ignore label entries for which the subid doesn't match.
12062                  */
12063                 if (labels[i].objsubid != subid)
12064                         continue;
12065
12066                 appendPQExpBuffer(query,
12067                                                   "SECURITY LABEL FOR %s ON %s IS ",
12068                                                   fmtId(labels[i].provider), target);
12069                 appendStringLiteralAH(query, labels[i].label, fout);
12070                 appendPQExpBuffer(query, ";\n");
12071         }
12072
12073         if (query->len > 0)
12074         {
12075                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12076                                          target, namespace, NULL, owner,
12077                                          false, "SECURITY LABEL", SECTION_NONE,
12078                                          query->data, "", NULL,
12079                                          &(dumpId), 1,
12080                                          NULL, NULL);
12081         }
12082         destroyPQExpBuffer(query);
12083 }
12084
12085 /*
12086  * dumpTableSecLabel
12087  *
12088  * As above, but dump security label for both the specified table (or view)
12089  * and its columns.
12090  */
12091 static void
12092 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
12093 {
12094         SecLabelItem *labels;
12095         int                     nlabels;
12096         int                     i;
12097         PQExpBuffer query;
12098         PQExpBuffer target;
12099
12100         /* do nothing, if --no-security-labels is supplied */
12101         if (no_security_labels)
12102                 return;
12103
12104         /* SecLabel are SCHEMA not data */
12105         if (dataOnly)
12106                 return;
12107
12108         /* Search for comments associated with relation, using table */
12109         nlabels = findSecLabels(fout,
12110                                                         tbinfo->dobj.catId.tableoid,
12111                                                         tbinfo->dobj.catId.oid,
12112                                                         &labels);
12113
12114         /* If security labels exist, build SECURITY LABEL statements */
12115         if (nlabels <= 0)
12116                 return;
12117
12118         query = createPQExpBuffer();
12119         target = createPQExpBuffer();
12120
12121         for (i = 0; i < nlabels; i++)
12122         {
12123                 const char *colname;
12124                 const char *provider = labels[i].provider;
12125                 const char *label = labels[i].label;
12126                 int                     objsubid = labels[i].objsubid;
12127
12128                 resetPQExpBuffer(target);
12129                 if (objsubid == 0)
12130                 {
12131                         appendPQExpBuffer(target, "%s %s", reltypename,
12132                                                           fmtId(tbinfo->dobj.name));
12133                 }
12134                 else
12135                 {
12136                         colname = getAttrName(objsubid, tbinfo);
12137                         /* first fmtId result must be consumed before calling it again */
12138                         appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
12139                         appendPQExpBuffer(target, ".%s", fmtId(colname));
12140                 }
12141                 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
12142                                                   fmtId(provider), target->data);
12143                 appendStringLiteralAH(query, label, fout);
12144                 appendPQExpBuffer(query, ";\n");
12145         }
12146         if (query->len > 0)
12147         {
12148                 resetPQExpBuffer(target);
12149                 appendPQExpBuffer(target, "%s %s", reltypename,
12150                                                   fmtId(tbinfo->dobj.name));
12151                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12152                                          target->data,
12153                                          tbinfo->dobj.namespace->dobj.name,
12154                                          NULL, tbinfo->rolname,
12155                                          false, "SECURITY LABEL", SECTION_NONE,
12156                                          query->data, "", NULL,
12157                                          &(tbinfo->dobj.dumpId), 1,
12158                                          NULL, NULL);
12159         }
12160         destroyPQExpBuffer(query);
12161         destroyPQExpBuffer(target);
12162 }
12163
12164 /*
12165  * findSecLabels
12166  *
12167  * Find the security label(s), if any, associated with the given object.
12168  * All the objsubid values associated with the given classoid/objoid are
12169  * found with one search.
12170  */
12171 static int
12172 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
12173 {
12174         /* static storage for table of security labels */
12175         static SecLabelItem *labels = NULL;
12176         static int      nlabels = -1;
12177
12178         SecLabelItem *middle = NULL;
12179         SecLabelItem *low;
12180         SecLabelItem *high;
12181         int                     nmatch;
12182
12183         /* Get security labels if we didn't already */
12184         if (nlabels < 0)
12185                 nlabels = collectSecLabels(fout, &labels);
12186
12187         if (nlabels <= 0)                       /* no labels, so no match is possible */
12188         {
12189                 *items = NULL;
12190                 return 0;
12191         }
12192
12193         /*
12194          * Do binary search to find some item matching the object.
12195          */
12196         low = &labels[0];
12197         high = &labels[nlabels - 1];
12198         while (low <= high)
12199         {
12200                 middle = low + (high - low) / 2;
12201
12202                 if (classoid < middle->classoid)
12203                         high = middle - 1;
12204                 else if (classoid > middle->classoid)
12205                         low = middle + 1;
12206                 else if (objoid < middle->objoid)
12207                         high = middle - 1;
12208                 else if (objoid > middle->objoid)
12209                         low = middle + 1;
12210                 else
12211                         break;                          /* found a match */
12212         }
12213
12214         if (low > high)                         /* no matches */
12215         {
12216                 *items = NULL;
12217                 return 0;
12218         }
12219
12220         /*
12221          * Now determine how many items match the object.  The search loop
12222          * invariant still holds: only items between low and high inclusive could
12223          * match.
12224          */
12225         nmatch = 1;
12226         while (middle > low)
12227         {
12228                 if (classoid != middle[-1].classoid ||
12229                         objoid != middle[-1].objoid)
12230                         break;
12231                 middle--;
12232                 nmatch++;
12233         }
12234
12235         *items = middle;
12236
12237         middle += nmatch;
12238         while (middle <= high)
12239         {
12240                 if (classoid != middle->classoid ||
12241                         objoid != middle->objoid)
12242                         break;
12243                 middle++;
12244                 nmatch++;
12245         }
12246
12247         return nmatch;
12248 }
12249
12250 /*
12251  * collectSecLabels
12252  *
12253  * Construct a table of all security labels available for database objects.
12254  * It's much faster to pull them all at once.
12255  *
12256  * The table is sorted by classoid/objid/objsubid for speed in lookup.
12257  */
12258 static int
12259 collectSecLabels(Archive *fout, SecLabelItem **items)
12260 {
12261         PGresult   *res;
12262         PQExpBuffer query;
12263         int                     i_label;
12264         int                     i_provider;
12265         int                     i_classoid;
12266         int                     i_objoid;
12267         int                     i_objsubid;
12268         int                     ntups;
12269         int                     i;
12270         SecLabelItem *labels;
12271
12272         query = createPQExpBuffer();
12273
12274         appendPQExpBuffer(query,
12275                                           "SELECT label, provider, classoid, objoid, objsubid "
12276                                           "FROM pg_catalog.pg_seclabel "
12277                                           "ORDER BY classoid, objoid, objsubid");
12278
12279         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12280
12281         /* Construct lookup table containing OIDs in numeric form */
12282         i_label = PQfnumber(res, "label");
12283         i_provider = PQfnumber(res, "provider");
12284         i_classoid = PQfnumber(res, "classoid");
12285         i_objoid = PQfnumber(res, "objoid");
12286         i_objsubid = PQfnumber(res, "objsubid");
12287
12288         ntups = PQntuples(res);
12289
12290         labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12291
12292         for (i = 0; i < ntups; i++)
12293         {
12294                 labels[i].label = PQgetvalue(res, i, i_label);
12295                 labels[i].provider = PQgetvalue(res, i, i_provider);
12296                 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12297                 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12298                 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12299         }
12300
12301         /* Do NOT free the PGresult since we are keeping pointers into it */
12302         destroyPQExpBuffer(query);
12303
12304         *items = labels;
12305         return ntups;
12306 }
12307
12308 /*
12309  * dumpTable
12310  *        write out to fout the declarations (not data) of a user-defined table
12311  */
12312 static void
12313 dumpTable(Archive *fout, TableInfo *tbinfo)
12314 {
12315         if (tbinfo->dobj.dump && !dataOnly)
12316         {
12317                 char       *namecopy;
12318
12319                 if (tbinfo->relkind == RELKIND_SEQUENCE)
12320                         dumpSequence(fout, tbinfo);
12321                 else
12322                         dumpTableSchema(fout, tbinfo);
12323
12324                 /* Handle the ACL here */
12325                 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12326                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12327                                 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12328                                 "TABLE",
12329                                 namecopy, NULL, tbinfo->dobj.name,
12330                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12331                                 tbinfo->relacl);
12332
12333                 /*
12334                  * Handle column ACLs, if any.  Note: we pull these with a separate
12335                  * query rather than trying to fetch them during getTableAttrs, so
12336                  * that we won't miss ACLs on system columns.
12337                  */
12338                 if (fout->remoteVersion >= 80400)
12339                 {
12340                         PQExpBuffer query = createPQExpBuffer();
12341                         PGresult   *res;
12342                         int                     i;
12343
12344                         appendPQExpBuffer(query,
12345                                            "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12346                                                           "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12347                                                           "ORDER BY attnum",
12348                                                           tbinfo->dobj.catId.oid);
12349                         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12350
12351                         for (i = 0; i < PQntuples(res); i++)
12352                         {
12353                                 char       *attname = PQgetvalue(res, i, 0);
12354                                 char       *attacl = PQgetvalue(res, i, 1);
12355                                 char       *attnamecopy;
12356                                 char       *acltag;
12357
12358                                 attnamecopy = pg_strdup(fmtId(attname));
12359                                 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12360                                 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12361                                 /* Column's GRANT type is always TABLE */
12362                                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12363                                                 namecopy, attnamecopy, acltag,
12364                                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12365                                                 attacl);
12366                                 free(attnamecopy);
12367                                 free(acltag);
12368                         }
12369                         PQclear(res);
12370                         destroyPQExpBuffer(query);
12371                 }
12372
12373                 free(namecopy);
12374         }
12375 }
12376
12377 /*
12378  * dumpTableSchema
12379  *        write the declaration (not data) of one user-defined table or view
12380  */
12381 static void
12382 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12383 {
12384         PQExpBuffer query = createPQExpBuffer();
12385         PQExpBuffer q = createPQExpBuffer();
12386         PQExpBuffer delq = createPQExpBuffer();
12387         PQExpBuffer labelq = createPQExpBuffer();
12388         PGresult   *res;
12389         int                     numParents;
12390         TableInfo **parents;
12391         int                     actual_atts;    /* number of attrs in this CREATE statement */
12392         const char *reltypename;
12393         char       *storage;
12394         char       *srvname;
12395         char       *ftoptions;
12396         int                     j,
12397                                 k;
12398
12399         /* Make sure we are in proper schema */
12400         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12401
12402         if (binary_upgrade)
12403                 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12404                                                                                                 tbinfo->dobj.catId.oid);
12405
12406         /* Is it a table or a view? */
12407         if (tbinfo->relkind == RELKIND_VIEW)
12408         {
12409                 char       *viewdef;
12410
12411                 reltypename = "VIEW";
12412
12413                 /* Fetch the view definition */
12414                 if (fout->remoteVersion >= 70300)
12415                 {
12416                         /* Beginning in 7.3, viewname is not unique; rely on OID */
12417                         appendPQExpBuffer(query,
12418                                                           "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12419                                                           tbinfo->dobj.catId.oid);
12420                 }
12421                 else
12422                 {
12423                         appendPQExpBuffer(query, "SELECT definition AS viewdef "
12424                                                           "FROM pg_views WHERE viewname = ");
12425                         appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12426                         appendPQExpBuffer(query, ";");
12427                 }
12428
12429                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12430
12431                 if (PQntuples(res) != 1)
12432                 {
12433                         if (PQntuples(res) < 1)
12434                                 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12435                                                           tbinfo->dobj.name);
12436                         else
12437                                 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12438                                                           tbinfo->dobj.name);
12439                 }
12440
12441                 viewdef = PQgetvalue(res, 0, 0);
12442
12443                 if (strlen(viewdef) == 0)
12444                         exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12445                                                   tbinfo->dobj.name);
12446
12447                 /*
12448                  * DROP must be fully qualified in case same name appears in
12449                  * pg_catalog
12450                  */
12451                 appendPQExpBuffer(delq, "DROP VIEW %s.",
12452                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12453                 appendPQExpBuffer(delq, "%s;\n",
12454                                                   fmtId(tbinfo->dobj.name));
12455
12456                 if (binary_upgrade)
12457                         binary_upgrade_set_pg_class_oids(fout, q,
12458                                                                                          tbinfo->dobj.catId.oid, false);
12459
12460                 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12461                 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12462                         appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12463                 appendPQExpBuffer(q, " AS\n    %s\n", viewdef);
12464
12465                 appendPQExpBuffer(labelq, "VIEW %s",
12466                                                   fmtId(tbinfo->dobj.name));
12467
12468                 PQclear(res);
12469         }
12470         else
12471         {
12472                 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12473                 {
12474                         int                     i_srvname;
12475                         int                     i_ftoptions;
12476
12477                         reltypename = "FOREIGN TABLE";
12478
12479                         /* retrieve name of foreign server and generic options */
12480                         appendPQExpBuffer(query,
12481                                                           "SELECT fs.srvname, "
12482                                                           "pg_catalog.array_to_string(ARRAY("
12483                                                           "SELECT pg_catalog.quote_ident(option_name) || "
12484                                                           "' ' || pg_catalog.quote_literal(option_value) "
12485                                                         "FROM pg_catalog.pg_options_to_table(ftoptions) "
12486                                                           "ORDER BY option_name"
12487                                                           "), E',\n    ') AS ftoptions "
12488                                                           "FROM pg_catalog.pg_foreign_table ft "
12489                                                           "JOIN pg_catalog.pg_foreign_server fs "
12490                                                           "ON (fs.oid = ft.ftserver) "
12491                                                           "WHERE ft.ftrelid = '%u'",
12492                                                           tbinfo->dobj.catId.oid);
12493                         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12494                         i_srvname = PQfnumber(res, "srvname");
12495                         i_ftoptions = PQfnumber(res, "ftoptions");
12496                         srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12497                         ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12498                         PQclear(res);
12499                 }
12500                 else
12501                 {
12502                         reltypename = "TABLE";
12503                         srvname = NULL;
12504                         ftoptions = NULL;
12505                 }
12506                 numParents = tbinfo->numParents;
12507                 parents = tbinfo->parents;
12508
12509                 /*
12510                  * DROP must be fully qualified in case same name appears in
12511                  * pg_catalog
12512                  */
12513                 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12514                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12515                 appendPQExpBuffer(delq, "%s;\n",
12516                                                   fmtId(tbinfo->dobj.name));
12517
12518                 appendPQExpBuffer(labelq, "%s %s", reltypename,
12519                                                   fmtId(tbinfo->dobj.name));
12520
12521                 if (binary_upgrade)
12522                         binary_upgrade_set_pg_class_oids(fout, q,
12523                                                                                          tbinfo->dobj.catId.oid, false);
12524
12525                 appendPQExpBuffer(q, "CREATE %s%s %s",
12526                                                   tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12527                                                   "UNLOGGED " : "",
12528                                                   reltypename,
12529                                                   fmtId(tbinfo->dobj.name));
12530
12531                 /*
12532                  * Attach to type, if reloftype; except in case of a binary upgrade,
12533                  * we dump the table normally and attach it to the type afterward.
12534                  */
12535                 if (tbinfo->reloftype && !binary_upgrade)
12536                         appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12537
12538                 /* Dump the attributes */
12539                 actual_atts = 0;
12540                 for (j = 0; j < tbinfo->numatts; j++)
12541                 {
12542                         /*
12543                          * Normally, dump if it's locally defined in this table, and not
12544                          * dropped.  But for binary upgrade, we'll dump all the columns,
12545                          * and then fix up the dropped and nonlocal cases below.
12546                          */
12547                         if (shouldPrintColumn(tbinfo, j))
12548                         {
12549                                 /*
12550                                  * Default value --- suppress if to be printed separately.
12551                                  */
12552                                 bool            has_default = (tbinfo->attrdefs[j] != NULL &&
12553                                                                                    !tbinfo->attrdefs[j]->separate);
12554
12555                                 /*
12556                                  * Not Null constraint --- suppress if inherited, except in
12557                                  * binary-upgrade case where that won't work.
12558                                  */
12559                                 bool            has_notnull = (tbinfo->notnull[j] &&
12560                                                                                    (!tbinfo->inhNotNull[j] ||
12561                                                                                         binary_upgrade));
12562
12563                                 /* Skip column if fully defined by reloftype */
12564                                 if (tbinfo->reloftype &&
12565                                         !has_default && !has_notnull && !binary_upgrade)
12566                                         continue;
12567
12568                                 /* Format properly if not first attr */
12569                                 if (actual_atts == 0)
12570                                         appendPQExpBuffer(q, " (");
12571                                 else
12572                                         appendPQExpBuffer(q, ",");
12573                                 appendPQExpBuffer(q, "\n    ");
12574                                 actual_atts++;
12575
12576                                 /* Attribute name */
12577                                 appendPQExpBuffer(q, "%s ",
12578                                                                   fmtId(tbinfo->attnames[j]));
12579
12580                                 if (tbinfo->attisdropped[j])
12581                                 {
12582                                         /*
12583                                          * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12584                                          * so we will not have gotten a valid type name; insert
12585                                          * INTEGER as a stopgap.  We'll clean things up later.
12586                                          */
12587                                         appendPQExpBuffer(q, "INTEGER /* dummy */");
12588                                         /* Skip all the rest, too */
12589                                         continue;
12590                                 }
12591
12592                                 /* Attribute type */
12593                                 if (tbinfo->reloftype && !binary_upgrade)
12594                                 {
12595                                         appendPQExpBuffer(q, "WITH OPTIONS");
12596                                 }
12597                                 else if (fout->remoteVersion >= 70100)
12598                                 {
12599                                         appendPQExpBuffer(q, "%s",
12600                                                                           tbinfo->atttypnames[j]);
12601                                 }
12602                                 else
12603                                 {
12604                                         /* If no format_type, fake it */
12605                                         appendPQExpBuffer(q, "%s",
12606                                                                           myFormatType(tbinfo->atttypnames[j],
12607                                                                                                    tbinfo->atttypmod[j]));
12608                                 }
12609
12610                                 /* Add collation if not default for the type */
12611                                 if (OidIsValid(tbinfo->attcollation[j]))
12612                                 {
12613                                         CollInfo   *coll;
12614
12615                                         coll = findCollationByOid(tbinfo->attcollation[j]);
12616                                         if (coll)
12617                                         {
12618                                                 /* always schema-qualify, don't try to be smart */
12619                                                 appendPQExpBuffer(q, " COLLATE %s.",
12620                                                                          fmtId(coll->dobj.namespace->dobj.name));
12621                                                 appendPQExpBuffer(q, "%s",
12622                                                                                   fmtId(coll->dobj.name));
12623                                         }
12624                                 }
12625
12626                                 if (has_default)
12627                                         appendPQExpBuffer(q, " DEFAULT %s",
12628                                                                           tbinfo->attrdefs[j]->adef_expr);
12629
12630                                 if (has_notnull)
12631                                         appendPQExpBuffer(q, " NOT NULL");
12632                         }
12633                 }
12634
12635                 /*
12636                  * Add non-inherited CHECK constraints, if any.
12637                  */
12638                 for (j = 0; j < tbinfo->ncheck; j++)
12639                 {
12640                         ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12641
12642                         if (constr->separate || !constr->conislocal)
12643                                 continue;
12644
12645                         if (actual_atts == 0)
12646                                 appendPQExpBuffer(q, " (\n    ");
12647                         else
12648                                 appendPQExpBuffer(q, ",\n    ");
12649
12650                         appendPQExpBuffer(q, "CONSTRAINT %s ",
12651                                                           fmtId(constr->dobj.name));
12652                         appendPQExpBuffer(q, "%s", constr->condef);
12653
12654                         actual_atts++;
12655                 }
12656
12657                 if (actual_atts)
12658                         appendPQExpBuffer(q, "\n)");
12659                 else if (!(tbinfo->reloftype && !binary_upgrade))
12660                 {
12661                         /*
12662                          * We must have a parenthesized attribute list, even though empty,
12663                          * when not using the OF TYPE syntax.
12664                          */
12665                         appendPQExpBuffer(q, " (\n)");
12666                 }
12667
12668                 if (numParents > 0 && !binary_upgrade)
12669                 {
12670                         appendPQExpBuffer(q, "\nINHERITS (");
12671                         for (k = 0; k < numParents; k++)
12672                         {
12673                                 TableInfo  *parentRel = parents[k];
12674
12675                                 if (k > 0)
12676                                         appendPQExpBuffer(q, ", ");
12677                                 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12678                                         appendPQExpBuffer(q, "%s.",
12679                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
12680                                 appendPQExpBuffer(q, "%s",
12681                                                                   fmtId(parentRel->dobj.name));
12682                         }
12683                         appendPQExpBuffer(q, ")");
12684                 }
12685
12686                 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12687                         appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12688
12689                 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12690                   (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12691                 {
12692                         bool            addcomma = false;
12693
12694                         appendPQExpBuffer(q, "\nWITH (");
12695                         if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12696                         {
12697                                 addcomma = true;
12698                                 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12699                         }
12700                         if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12701                         {
12702                                 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12703                                                                   tbinfo->toast_reloptions);
12704                         }
12705                         appendPQExpBuffer(q, ")");
12706                 }
12707
12708                 /* Dump generic options if any */
12709                 if (ftoptions && ftoptions[0])
12710                         appendPQExpBuffer(q, "\nOPTIONS (\n    %s\n)", ftoptions);
12711
12712                 appendPQExpBuffer(q, ";\n");
12713
12714                 /*
12715                  * To create binary-compatible heap files, we have to ensure the same
12716                  * physical column order, including dropped columns, as in the
12717                  * original.  Therefore, we create dropped columns above and drop them
12718                  * here, also updating their attlen/attalign values so that the
12719                  * dropped column can be skipped properly.      (We do not bother with
12720                  * restoring the original attbyval setting.)  Also, inheritance
12721                  * relationships are set up by doing ALTER INHERIT rather than using
12722                  * an INHERITS clause --- the latter would possibly mess up the column
12723                  * order.  That also means we have to take care about setting
12724                  * attislocal correctly, plus fix up any inherited CHECK constraints.
12725                  * Analogously, we set up typed tables using ALTER TABLE / OF here.
12726                  */
12727                 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12728                 {
12729                         for (j = 0; j < tbinfo->numatts; j++)
12730                         {
12731                                 if (tbinfo->attisdropped[j])
12732                                 {
12733                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12734                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12735                                                                           "SET attlen = %d, "
12736                                                                           "attalign = '%c', attbyval = false\n"
12737                                                                           "WHERE attname = ",
12738                                                                           tbinfo->attlen[j],
12739                                                                           tbinfo->attalign[j]);
12740                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12741                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
12742                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12743                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12744
12745                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12746                                                                           fmtId(tbinfo->dobj.name));
12747                                         appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12748                                                                           fmtId(tbinfo->attnames[j]));
12749                                 }
12750                                 else if (!tbinfo->attislocal[j])
12751                                 {
12752                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12753                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12754                                                                           "SET attislocal = false\n"
12755                                                                           "WHERE attname = ");
12756                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12757                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
12758                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12759                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12760                                 }
12761                         }
12762
12763                         for (k = 0; k < tbinfo->ncheck; k++)
12764                         {
12765                                 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12766
12767                                 if (constr->separate || constr->conislocal)
12768                                         continue;
12769
12770                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12771                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12772                                                                   fmtId(tbinfo->dobj.name));
12773                                 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12774                                                                   fmtId(constr->dobj.name));
12775                                 appendPQExpBuffer(q, "%s;\n", constr->condef);
12776                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
12777                                                                   "SET conislocal = false\n"
12778                                                                   "WHERE contype = 'c' AND conname = ");
12779                                 appendStringLiteralAH(q, constr->dobj.name, fout);
12780                                 appendPQExpBuffer(q, "\n  AND conrelid = ");
12781                                 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12782                                 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12783                         }
12784
12785                         if (numParents > 0)
12786                         {
12787                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
12788                                 for (k = 0; k < numParents; k++)
12789                                 {
12790                                         TableInfo  *parentRel = parents[k];
12791
12792                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
12793                                                                           fmtId(tbinfo->dobj.name));
12794                                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12795                                                 appendPQExpBuffer(q, "%s.",
12796                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
12797                                         appendPQExpBuffer(q, "%s;\n",
12798                                                                           fmtId(parentRel->dobj.name));
12799                                 }
12800                         }
12801
12802                         if (tbinfo->reloftype)
12803                         {
12804                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
12805                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
12806                                                                   fmtId(tbinfo->dobj.name),
12807                                                                   tbinfo->reloftype);
12808                         }
12809
12810                         appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
12811                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12812                                                           "SET relfrozenxid = '%u'\n"
12813                                                           "WHERE oid = ",
12814                                                           tbinfo->frozenxid);
12815                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12816                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12817
12818                         if (tbinfo->toast_oid)
12819                         {
12820                                 /* We preserve the toast oids, so we can use it during restore */
12821                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
12822                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12823                                                                   "SET relfrozenxid = '%u'\n"
12824                                                                   "WHERE oid = '%u';\n",
12825                                                                   tbinfo->toast_frozenxid, tbinfo->toast_oid);
12826                         }
12827                 }
12828
12829                 /*
12830                  * Dump additional per-column properties that we can't handle in the
12831                  * main CREATE TABLE command.
12832                  */
12833                 for (j = 0; j < tbinfo->numatts; j++)
12834                 {
12835                         /* None of this applies to dropped columns */
12836                         if (tbinfo->attisdropped[j])
12837                                 continue;
12838
12839                         /*
12840                          * If we didn't dump the column definition explicitly above, and
12841                          * it is NOT NULL and did not inherit that property from a parent,
12842                          * we have to mark it separately.
12843                          */
12844                         if (!shouldPrintColumn(tbinfo, j) &&
12845                                 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
12846                         {
12847                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12848                                                                   fmtId(tbinfo->dobj.name));
12849                                 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
12850                                                                   fmtId(tbinfo->attnames[j]));
12851                         }
12852
12853                         /*
12854                          * Dump per-column statistics information. We only issue an ALTER
12855                          * TABLE statement if the attstattarget entry for this column is
12856                          * non-negative (i.e. it's not the default value)
12857                          */
12858                         if (tbinfo->attstattarget[j] >= 0)
12859                         {
12860                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12861                                                                   fmtId(tbinfo->dobj.name));
12862                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12863                                                                   fmtId(tbinfo->attnames[j]));
12864                                 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
12865                                                                   tbinfo->attstattarget[j]);
12866                         }
12867
12868                         /*
12869                          * Dump per-column storage information.  The statement is only
12870                          * dumped if the storage has been changed from the type's default.
12871                          */
12872                         if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
12873                         {
12874                                 switch (tbinfo->attstorage[j])
12875                                 {
12876                                         case 'p':
12877                                                 storage = "PLAIN";
12878                                                 break;
12879                                         case 'e':
12880                                                 storage = "EXTERNAL";
12881                                                 break;
12882                                         case 'm':
12883                                                 storage = "MAIN";
12884                                                 break;
12885                                         case 'x':
12886                                                 storage = "EXTENDED";
12887                                                 break;
12888                                         default:
12889                                                 storage = NULL;
12890                                 }
12891
12892                                 /*
12893                                  * Only dump the statement if it's a storage type we recognize
12894                                  */
12895                                 if (storage != NULL)
12896                                 {
12897                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12898                                                                           fmtId(tbinfo->dobj.name));
12899                                         appendPQExpBuffer(q, "ALTER COLUMN %s ",
12900                                                                           fmtId(tbinfo->attnames[j]));
12901                                         appendPQExpBuffer(q, "SET STORAGE %s;\n",
12902                                                                           storage);
12903                                 }
12904                         }
12905
12906                         /*
12907                          * Dump per-column attributes.
12908                          */
12909                         if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
12910                         {
12911                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12912                                                                   fmtId(tbinfo->dobj.name));
12913                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12914                                                                   fmtId(tbinfo->attnames[j]));
12915                                 appendPQExpBuffer(q, "SET (%s);\n",
12916                                                                   tbinfo->attoptions[j]);
12917                         }
12918
12919                         /*
12920                          * Dump per-column fdw options.
12921                          */
12922                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
12923                                 tbinfo->attfdwoptions[j] &&
12924                                 tbinfo->attfdwoptions[j][0] != '\0')
12925                         {
12926                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
12927                                                                   fmtId(tbinfo->dobj.name));
12928                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12929                                                                   fmtId(tbinfo->attnames[j]));
12930                                 appendPQExpBuffer(q, "OPTIONS (\n    %s\n);\n",
12931                                                                   tbinfo->attfdwoptions[j]);
12932                         }
12933                 }
12934         }
12935
12936         if (binary_upgrade)
12937                 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
12938
12939         ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12940                                  tbinfo->dobj.name,
12941                                  tbinfo->dobj.namespace->dobj.name,
12942                         (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
12943                                  tbinfo->rolname,
12944                            (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
12945                                  reltypename, SECTION_PRE_DATA,
12946                                  q->data, delq->data, NULL,
12947                                  NULL, 0,
12948                                  NULL, NULL);
12949
12950
12951         /* Dump Table Comments */
12952         dumpTableComment(fout, tbinfo, reltypename);
12953
12954         /* Dump Table Security Labels */
12955         dumpTableSecLabel(fout, tbinfo, reltypename);
12956
12957         /* Dump comments on inlined table constraints */
12958         for (j = 0; j < tbinfo->ncheck; j++)
12959         {
12960                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12961
12962                 if (constr->separate || !constr->conislocal)
12963                         continue;
12964
12965                 dumpTableConstraintComment(fout, constr);
12966         }
12967
12968         destroyPQExpBuffer(query);
12969         destroyPQExpBuffer(q);
12970         destroyPQExpBuffer(delq);
12971         destroyPQExpBuffer(labelq);
12972 }
12973
12974 /*
12975  * dumpAttrDef --- dump an attribute's default-value declaration
12976  */
12977 static void
12978 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
12979 {
12980         TableInfo  *tbinfo = adinfo->adtable;
12981         int                     adnum = adinfo->adnum;
12982         PQExpBuffer q;
12983         PQExpBuffer delq;
12984
12985         /* Skip if table definition not to be dumped */
12986         if (!tbinfo->dobj.dump || dataOnly)
12987                 return;
12988
12989         /* Skip if not "separate"; it was dumped in the table's definition */
12990         if (!adinfo->separate)
12991                 return;
12992
12993         q = createPQExpBuffer();
12994         delq = createPQExpBuffer();
12995
12996         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12997                                           fmtId(tbinfo->dobj.name));
12998         appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
12999                                           fmtId(tbinfo->attnames[adnum - 1]),
13000                                           adinfo->adef_expr);
13001
13002         /*
13003          * DROP must be fully qualified in case same name appears in pg_catalog
13004          */
13005         appendPQExpBuffer(delq, "ALTER TABLE %s.",
13006                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13007         appendPQExpBuffer(delq, "%s ",
13008                                           fmtId(tbinfo->dobj.name));
13009         appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
13010                                           fmtId(tbinfo->attnames[adnum - 1]));
13011
13012         ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
13013                                  tbinfo->attnames[adnum - 1],
13014                                  tbinfo->dobj.namespace->dobj.name,
13015                                  NULL,
13016                                  tbinfo->rolname,
13017                                  false, "DEFAULT", SECTION_PRE_DATA,
13018                                  q->data, delq->data, NULL,
13019                                  NULL, 0,
13020                                  NULL, NULL);
13021
13022         destroyPQExpBuffer(q);
13023         destroyPQExpBuffer(delq);
13024 }
13025
13026 /*
13027  * getAttrName: extract the correct name for an attribute
13028  *
13029  * The array tblInfo->attnames[] only provides names of user attributes;
13030  * if a system attribute number is supplied, we have to fake it.
13031  * We also do a little bit of bounds checking for safety's sake.
13032  */
13033 static const char *
13034 getAttrName(int attrnum, TableInfo *tblInfo)
13035 {
13036         if (attrnum > 0 && attrnum <= tblInfo->numatts)
13037                 return tblInfo->attnames[attrnum - 1];
13038         switch (attrnum)
13039         {
13040                 case SelfItemPointerAttributeNumber:
13041                         return "ctid";
13042                 case ObjectIdAttributeNumber:
13043                         return "oid";
13044                 case MinTransactionIdAttributeNumber:
13045                         return "xmin";
13046                 case MinCommandIdAttributeNumber:
13047                         return "cmin";
13048                 case MaxTransactionIdAttributeNumber:
13049                         return "xmax";
13050                 case MaxCommandIdAttributeNumber:
13051                         return "cmax";
13052                 case TableOidAttributeNumber:
13053                         return "tableoid";
13054         }
13055         exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
13056                                   attrnum, tblInfo->dobj.name);
13057         return NULL;                            /* keep compiler quiet */
13058 }
13059
13060 /*
13061  * dumpIndex
13062  *        write out to fout a user-defined index
13063  */
13064 static void
13065 dumpIndex(Archive *fout, IndxInfo *indxinfo)
13066 {
13067         TableInfo  *tbinfo = indxinfo->indextable;
13068         PQExpBuffer q;
13069         PQExpBuffer delq;
13070         PQExpBuffer labelq;
13071
13072         if (dataOnly)
13073                 return;
13074
13075         q = createPQExpBuffer();
13076         delq = createPQExpBuffer();
13077         labelq = createPQExpBuffer();
13078
13079         appendPQExpBuffer(labelq, "INDEX %s",
13080                                           fmtId(indxinfo->dobj.name));
13081
13082         /*
13083          * If there's an associated constraint, don't dump the index per se, but
13084          * do dump any comment for it.  (This is safe because dependency ordering
13085          * will have ensured the constraint is emitted first.)
13086          */
13087         if (indxinfo->indexconstraint == 0)
13088         {
13089                 if (binary_upgrade)
13090                         binary_upgrade_set_pg_class_oids(fout, q,
13091                                                                                          indxinfo->dobj.catId.oid, true);
13092
13093                 /* Plain secondary index */
13094                 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
13095
13096                 /* If the index is clustered, we need to record that. */
13097                 if (indxinfo->indisclustered)
13098                 {
13099                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13100                                                           fmtId(tbinfo->dobj.name));
13101                         appendPQExpBuffer(q, " ON %s;\n",
13102                                                           fmtId(indxinfo->dobj.name));
13103                 }
13104
13105                 /*
13106                  * DROP must be fully qualified in case same name appears in
13107                  * pg_catalog
13108                  */
13109                 appendPQExpBuffer(delq, "DROP INDEX %s.",
13110                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13111                 appendPQExpBuffer(delq, "%s;\n",
13112                                                   fmtId(indxinfo->dobj.name));
13113
13114                 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
13115                                          indxinfo->dobj.name,
13116                                          tbinfo->dobj.namespace->dobj.name,
13117                                          indxinfo->tablespace,
13118                                          tbinfo->rolname, false,
13119                                          "INDEX", SECTION_POST_DATA,
13120                                          q->data, delq->data, NULL,
13121                                          NULL, 0,
13122                                          NULL, NULL);
13123         }
13124
13125         /* Dump Index Comments */
13126         dumpComment(fout, labelq->data,
13127                                 tbinfo->dobj.namespace->dobj.name,
13128                                 tbinfo->rolname,
13129                                 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
13130
13131         destroyPQExpBuffer(q);
13132         destroyPQExpBuffer(delq);
13133         destroyPQExpBuffer(labelq);
13134 }
13135
13136 /*
13137  * dumpConstraint
13138  *        write out to fout a user-defined constraint
13139  */
13140 static void
13141 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
13142 {
13143         TableInfo  *tbinfo = coninfo->contable;
13144         PQExpBuffer q;
13145         PQExpBuffer delq;
13146
13147         /* Skip if not to be dumped */
13148         if (!coninfo->dobj.dump || dataOnly)
13149                 return;
13150
13151         q = createPQExpBuffer();
13152         delq = createPQExpBuffer();
13153
13154         if (coninfo->contype == 'p' ||
13155                 coninfo->contype == 'u' ||
13156                 coninfo->contype == 'x')
13157         {
13158                 /* Index-related constraint */
13159                 IndxInfo   *indxinfo;
13160                 int                     k;
13161
13162                 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
13163
13164                 if (indxinfo == NULL)
13165                         exit_horribly(NULL, "missing index for constraint \"%s\"\n",
13166                                                   coninfo->dobj.name);
13167
13168                 if (binary_upgrade)
13169                         binary_upgrade_set_pg_class_oids(fout, q,
13170                                                                                          indxinfo->dobj.catId.oid, true);
13171
13172                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13173                                                   fmtId(tbinfo->dobj.name));
13174                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s ",
13175                                                   fmtId(coninfo->dobj.name));
13176
13177                 if (coninfo->condef)
13178                 {
13179                         /* pg_get_constraintdef should have provided everything */
13180                         appendPQExpBuffer(q, "%s;\n", coninfo->condef);
13181                 }
13182                 else
13183                 {
13184                         appendPQExpBuffer(q, "%s (",
13185                                                  coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
13186                         for (k = 0; k < indxinfo->indnkeys; k++)
13187                         {
13188                                 int                     indkey = (int) indxinfo->indkeys[k];
13189                                 const char *attname;
13190
13191                                 if (indkey == InvalidAttrNumber)
13192                                         break;
13193                                 attname = getAttrName(indkey, tbinfo);
13194
13195                                 appendPQExpBuffer(q, "%s%s",
13196                                                                   (k == 0) ? "" : ", ",
13197                                                                   fmtId(attname));
13198                         }
13199
13200                         appendPQExpBuffer(q, ")");
13201
13202                         if (indxinfo->options && strlen(indxinfo->options) > 0)
13203                                 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
13204
13205                         if (coninfo->condeferrable)
13206                         {
13207                                 appendPQExpBuffer(q, " DEFERRABLE");
13208                                 if (coninfo->condeferred)
13209                                         appendPQExpBuffer(q, " INITIALLY DEFERRED");
13210                         }
13211
13212                         appendPQExpBuffer(q, ";\n");
13213                 }
13214
13215                 /* If the index is clustered, we need to record that. */
13216                 if (indxinfo->indisclustered)
13217                 {
13218                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13219                                                           fmtId(tbinfo->dobj.name));
13220                         appendPQExpBuffer(q, " ON %s;\n",
13221                                                           fmtId(indxinfo->dobj.name));
13222                 }
13223
13224                 /*
13225                  * DROP must be fully qualified in case same name appears in
13226                  * pg_catalog
13227                  */
13228                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13229                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13230                 appendPQExpBuffer(delq, "%s ",
13231                                                   fmtId(tbinfo->dobj.name));
13232                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13233                                                   fmtId(coninfo->dobj.name));
13234
13235                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13236                                          coninfo->dobj.name,
13237                                          tbinfo->dobj.namespace->dobj.name,
13238                                          indxinfo->tablespace,
13239                                          tbinfo->rolname, false,
13240                                          "CONSTRAINT", SECTION_POST_DATA,
13241                                          q->data, delq->data, NULL,
13242                                          NULL, 0,
13243                                          NULL, NULL);
13244         }
13245         else if (coninfo->contype == 'f')
13246         {
13247                 /*
13248                  * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13249                  * current table data is not processed
13250                  */
13251                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13252                                                   fmtId(tbinfo->dobj.name));
13253                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13254                                                   fmtId(coninfo->dobj.name),
13255                                                   coninfo->condef);
13256
13257                 /*
13258                  * DROP must be fully qualified in case same name appears in
13259                  * pg_catalog
13260                  */
13261                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13262                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13263                 appendPQExpBuffer(delq, "%s ",
13264                                                   fmtId(tbinfo->dobj.name));
13265                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13266                                                   fmtId(coninfo->dobj.name));
13267
13268                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13269                                          coninfo->dobj.name,
13270                                          tbinfo->dobj.namespace->dobj.name,
13271                                          NULL,
13272                                          tbinfo->rolname, false,
13273                                          "FK CONSTRAINT", SECTION_POST_DATA,
13274                                          q->data, delq->data, NULL,
13275                                          NULL, 0,
13276                                          NULL, NULL);
13277         }
13278         else if (coninfo->contype == 'c' && tbinfo)
13279         {
13280                 /* CHECK constraint on a table */
13281
13282                 /* Ignore if not to be dumped separately */
13283                 if (coninfo->separate)
13284                 {
13285                         /* not ONLY since we want it to propagate to children */
13286                         appendPQExpBuffer(q, "ALTER TABLE %s\n",
13287                                                           fmtId(tbinfo->dobj.name));
13288                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13289                                                           fmtId(coninfo->dobj.name),
13290                                                           coninfo->condef);
13291
13292                         /*
13293                          * DROP must be fully qualified in case same name appears in
13294                          * pg_catalog
13295                          */
13296                         appendPQExpBuffer(delq, "ALTER TABLE %s.",
13297                                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13298                         appendPQExpBuffer(delq, "%s ",
13299                                                           fmtId(tbinfo->dobj.name));
13300                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13301                                                           fmtId(coninfo->dobj.name));
13302
13303                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13304                                                  coninfo->dobj.name,
13305                                                  tbinfo->dobj.namespace->dobj.name,
13306                                                  NULL,
13307                                                  tbinfo->rolname, false,
13308                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13309                                                  q->data, delq->data, NULL,
13310                                                  NULL, 0,
13311                                                  NULL, NULL);
13312                 }
13313         }
13314         else if (coninfo->contype == 'c' && tbinfo == NULL)
13315         {
13316                 /* CHECK constraint on a domain */
13317                 TypeInfo   *tyinfo = coninfo->condomain;
13318
13319                 /* Ignore if not to be dumped separately */
13320                 if (coninfo->separate)
13321                 {
13322                         appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13323                                                           fmtId(tyinfo->dobj.name));
13324                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13325                                                           fmtId(coninfo->dobj.name),
13326                                                           coninfo->condef);
13327
13328                         /*
13329                          * DROP must be fully qualified in case same name appears in
13330                          * pg_catalog
13331                          */
13332                         appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13333                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
13334                         appendPQExpBuffer(delq, "%s ",
13335                                                           fmtId(tyinfo->dobj.name));
13336                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13337                                                           fmtId(coninfo->dobj.name));
13338
13339                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13340                                                  coninfo->dobj.name,
13341                                                  tyinfo->dobj.namespace->dobj.name,
13342                                                  NULL,
13343                                                  tyinfo->rolname, false,
13344                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13345                                                  q->data, delq->data, NULL,
13346                                                  NULL, 0,
13347                                                  NULL, NULL);
13348                 }
13349         }
13350         else
13351         {
13352                 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13353                                           coninfo->contype);
13354         }
13355
13356         /* Dump Constraint Comments --- only works for table constraints */
13357         if (tbinfo && coninfo->separate)
13358                 dumpTableConstraintComment(fout, coninfo);
13359
13360         destroyPQExpBuffer(q);
13361         destroyPQExpBuffer(delq);
13362 }
13363
13364 /*
13365  * dumpTableConstraintComment --- dump a constraint's comment if any
13366  *
13367  * This is split out because we need the function in two different places
13368  * depending on whether the constraint is dumped as part of CREATE TABLE
13369  * or as a separate ALTER command.
13370  */
13371 static void
13372 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13373 {
13374         TableInfo  *tbinfo = coninfo->contable;
13375         PQExpBuffer labelq = createPQExpBuffer();
13376
13377         appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13378                                           fmtId(coninfo->dobj.name));
13379         appendPQExpBuffer(labelq, "ON %s",
13380                                           fmtId(tbinfo->dobj.name));
13381         dumpComment(fout, labelq->data,
13382                                 tbinfo->dobj.namespace->dobj.name,
13383                                 tbinfo->rolname,
13384                                 coninfo->dobj.catId, 0,
13385                          coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13386
13387         destroyPQExpBuffer(labelq);
13388 }
13389
13390 /*
13391  * findLastBuiltInOid -
13392  * find the last built in oid
13393  *
13394  * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13395  * pg_database entry for the current database
13396  */
13397 static Oid
13398 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13399 {
13400         PGresult   *res;
13401         Oid                     last_oid;
13402         PQExpBuffer query = createPQExpBuffer();
13403
13404         resetPQExpBuffer(query);
13405         appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13406         appendStringLiteralAH(query, dbname, fout);
13407
13408         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13409         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13410         PQclear(res);
13411         destroyPQExpBuffer(query);
13412         return last_oid;
13413 }
13414
13415 /*
13416  * findLastBuiltInOid -
13417  * find the last built in oid
13418  *
13419  * For 7.0, we do this by assuming that the last thing that initdb does is to
13420  * create the pg_indexes view.  This sucks in general, but seeing that 7.0.x
13421  * initdb won't be changing anymore, it'll do.
13422  */
13423 static Oid
13424 findLastBuiltinOid_V70(Archive *fout)
13425 {
13426         PGresult   *res;
13427         int                     last_oid;
13428
13429         res = ExecuteSqlQueryForSingleRow(fout,
13430                                         "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13431         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13432         PQclear(res);
13433         return last_oid;
13434 }
13435
13436 /*
13437  * dumpSequence
13438  *        write the declaration (not data) of one user-defined sequence
13439  */
13440 static void
13441 dumpSequence(Archive *fout, TableInfo *tbinfo)
13442 {
13443         PGresult   *res;
13444         char       *startv,
13445                            *incby,
13446                            *maxv = NULL,
13447                            *minv = NULL,
13448                            *cache;
13449         char            bufm[100],
13450                                 bufx[100];
13451         bool            cycled;
13452         PQExpBuffer query = createPQExpBuffer();
13453         PQExpBuffer delqry = createPQExpBuffer();
13454         PQExpBuffer labelq = createPQExpBuffer();
13455
13456         /* Make sure we are in proper schema */
13457         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13458
13459         snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13460         snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13461
13462         if (fout->remoteVersion >= 80400)
13463         {
13464                 appendPQExpBuffer(query,
13465                                                   "SELECT sequence_name, "
13466                                                   "start_value, increment_by, "
13467                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13468                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13469                                                   "     ELSE max_value "
13470                                                   "END AS max_value, "
13471                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13472                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13473                                                   "     ELSE min_value "
13474                                                   "END AS min_value, "
13475                                                   "cache_value, is_cycled FROM %s",
13476                                                   bufx, bufm,
13477                                                   fmtId(tbinfo->dobj.name));
13478         }
13479         else
13480         {
13481                 appendPQExpBuffer(query,
13482                                                   "SELECT sequence_name, "
13483                                                   "0 AS start_value, increment_by, "
13484                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13485                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13486                                                   "     ELSE max_value "
13487                                                   "END AS max_value, "
13488                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13489                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13490                                                   "     ELSE min_value "
13491                                                   "END AS min_value, "
13492                                                   "cache_value, is_cycled FROM %s",
13493                                                   bufx, bufm,
13494                                                   fmtId(tbinfo->dobj.name));
13495         }
13496
13497         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13498
13499         if (PQntuples(res) != 1)
13500         {
13501                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13502                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13503                                                                  PQntuples(res)),
13504                                   tbinfo->dobj.name, PQntuples(res));
13505                 exit_nicely(1);
13506         }
13507
13508         /* Disable this check: it fails if sequence has been renamed */
13509 #ifdef NOT_USED
13510         if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13511         {
13512                 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13513                                   tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13514                 exit_nicely(1);
13515         }
13516 #endif
13517
13518         startv = PQgetvalue(res, 0, 1);
13519         incby = PQgetvalue(res, 0, 2);
13520         if (!PQgetisnull(res, 0, 3))
13521                 maxv = PQgetvalue(res, 0, 3);
13522         if (!PQgetisnull(res, 0, 4))
13523                 minv = PQgetvalue(res, 0, 4);
13524         cache = PQgetvalue(res, 0, 5);
13525         cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
13526
13527         /*
13528          * DROP must be fully qualified in case same name appears in pg_catalog
13529          */
13530         appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13531                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13532         appendPQExpBuffer(delqry, "%s;\n",
13533                                           fmtId(tbinfo->dobj.name));
13534
13535         resetPQExpBuffer(query);
13536
13537         if (binary_upgrade)
13538         {
13539                 binary_upgrade_set_pg_class_oids(fout, query,
13540                                                                                  tbinfo->dobj.catId.oid, false);
13541                 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13542                                                                                                 tbinfo->dobj.catId.oid);
13543         }
13544
13545         appendPQExpBuffer(query,
13546                                           "CREATE SEQUENCE %s\n",
13547                                           fmtId(tbinfo->dobj.name));
13548
13549         if (fout->remoteVersion >= 80400)
13550                 appendPQExpBuffer(query, "    START WITH %s\n", startv);
13551
13552         appendPQExpBuffer(query, "    INCREMENT BY %s\n", incby);
13553
13554         if (minv)
13555                 appendPQExpBuffer(query, "    MINVALUE %s\n", minv);
13556         else
13557                 appendPQExpBuffer(query, "    NO MINVALUE\n");
13558
13559         if (maxv)
13560                 appendPQExpBuffer(query, "    MAXVALUE %s\n", maxv);
13561         else
13562                 appendPQExpBuffer(query, "    NO MAXVALUE\n");
13563
13564         appendPQExpBuffer(query,
13565                                           "    CACHE %s%s",
13566                                           cache, (cycled ? "\n    CYCLE" : ""));
13567
13568         appendPQExpBuffer(query, ";\n");
13569
13570         appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13571
13572         /* binary_upgrade:      no need to clear TOAST table oid */
13573
13574         if (binary_upgrade)
13575                 binary_upgrade_extension_member(query, &tbinfo->dobj,
13576                                                                                 labelq->data);
13577
13578         ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13579                                  tbinfo->dobj.name,
13580                                  tbinfo->dobj.namespace->dobj.name,
13581                                  NULL,
13582                                  tbinfo->rolname,
13583                                  false, "SEQUENCE", SECTION_PRE_DATA,
13584                                  query->data, delqry->data, NULL,
13585                                  NULL, 0,
13586                                  NULL, NULL);
13587
13588         /*
13589          * If the sequence is owned by a table column, emit the ALTER for it as a
13590          * separate TOC entry immediately following the sequence's own entry.
13591          * It's OK to do this rather than using full sorting logic, because the
13592          * dependency that tells us it's owned will have forced the table to be
13593          * created first.  We can't just include the ALTER in the TOC entry
13594          * because it will fail if we haven't reassigned the sequence owner to
13595          * match the table's owner.
13596          *
13597          * We need not schema-qualify the table reference because both sequence
13598          * and table must be in the same schema.
13599          */
13600         if (OidIsValid(tbinfo->owning_tab))
13601         {
13602                 TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
13603
13604                 if (owning_tab && owning_tab->dobj.dump)
13605                 {
13606                         resetPQExpBuffer(query);
13607                         appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13608                                                           fmtId(tbinfo->dobj.name));
13609                         appendPQExpBuffer(query, " OWNED BY %s",
13610                                                           fmtId(owning_tab->dobj.name));
13611                         appendPQExpBuffer(query, ".%s;\n",
13612                                                 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13613
13614                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
13615                                                  tbinfo->dobj.name,
13616                                                  tbinfo->dobj.namespace->dobj.name,
13617                                                  NULL,
13618                                                  tbinfo->rolname,
13619                                                  false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13620                                                  query->data, "", NULL,
13621                                                  &(tbinfo->dobj.dumpId), 1,
13622                                                  NULL, NULL);
13623                 }
13624         }
13625
13626         /* Dump Sequence Comments and Security Labels */
13627         dumpComment(fout, labelq->data,
13628                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13629                                 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13630         dumpSecLabel(fout, labelq->data,
13631                                  tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13632                                  tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13633
13634         PQclear(res);
13635
13636         destroyPQExpBuffer(query);
13637         destroyPQExpBuffer(delqry);
13638         destroyPQExpBuffer(labelq);
13639 }
13640
13641 /*
13642  * dumpSequenceData
13643  *        write the data of one user-defined sequence
13644  */
13645 static void
13646 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
13647 {
13648         TableInfo  *tbinfo = tdinfo->tdtable;
13649         PGresult   *res;
13650         char       *last;
13651         bool            called;
13652         PQExpBuffer query = createPQExpBuffer();
13653
13654         /* Make sure we are in proper schema */
13655         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13656
13657         appendPQExpBuffer(query,
13658                                           "SELECT last_value, is_called FROM %s",
13659                                           fmtId(tbinfo->dobj.name));
13660
13661         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13662
13663         if (PQntuples(res) != 1)
13664         {
13665                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13666                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13667                                                                  PQntuples(res)),
13668                                   tbinfo->dobj.name, PQntuples(res));
13669                 exit_nicely(1);
13670         }
13671
13672         last = PQgetvalue(res, 0, 0);
13673         called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
13674
13675         resetPQExpBuffer(query);
13676         appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13677         appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13678         appendPQExpBuffer(query, ", %s, %s);\n",
13679                                           last, (called ? "true" : "false"));
13680
13681         ArchiveEntry(fout, nilCatalogId, createDumpId(),
13682                                  tbinfo->dobj.name,
13683                                  tbinfo->dobj.namespace->dobj.name,
13684                                  NULL,
13685                                  tbinfo->rolname,
13686                                  false, "SEQUENCE SET", SECTION_DATA,
13687                                  query->data, "", NULL,
13688                                  &(tbinfo->dobj.dumpId), 1,
13689                                  NULL, NULL);
13690
13691         PQclear(res);
13692
13693         destroyPQExpBuffer(query);
13694 }
13695
13696 static void
13697 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13698 {
13699         TableInfo  *tbinfo = tginfo->tgtable;
13700         PQExpBuffer query;
13701         PQExpBuffer delqry;
13702         PQExpBuffer labelq;
13703         char       *tgargs;
13704         size_t          lentgargs;
13705         const char *p;
13706         int                     findx;
13707
13708         if (dataOnly)
13709                 return;
13710
13711         query = createPQExpBuffer();
13712         delqry = createPQExpBuffer();
13713         labelq = createPQExpBuffer();
13714
13715         /*
13716          * DROP must be fully qualified in case same name appears in pg_catalog
13717          */
13718         appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13719                                           fmtId(tginfo->dobj.name));
13720         appendPQExpBuffer(delqry, "ON %s.",
13721                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13722         appendPQExpBuffer(delqry, "%s;\n",
13723                                           fmtId(tbinfo->dobj.name));
13724
13725         if (tginfo->tgdef)
13726         {
13727                 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13728         }
13729         else
13730         {
13731                 if (tginfo->tgisconstraint)
13732                 {
13733                         appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13734                         appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13735                 }
13736                 else
13737                 {
13738                         appendPQExpBuffer(query, "CREATE TRIGGER ");
13739                         appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13740                 }
13741                 appendPQExpBuffer(query, "\n    ");
13742
13743                 /* Trigger type */
13744                 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13745                         appendPQExpBuffer(query, "BEFORE");
13746                 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13747                         appendPQExpBuffer(query, "AFTER");
13748                 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13749                         appendPQExpBuffer(query, "INSTEAD OF");
13750                 else
13751                 {
13752                         write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13753                         exit_nicely(1);
13754                 }
13755
13756                 findx = 0;
13757                 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13758                 {
13759                         appendPQExpBuffer(query, " INSERT");
13760                         findx++;
13761                 }
13762                 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13763                 {
13764                         if (findx > 0)
13765                                 appendPQExpBuffer(query, " OR DELETE");
13766                         else
13767                                 appendPQExpBuffer(query, " DELETE");
13768                         findx++;
13769                 }
13770                 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13771                 {
13772                         if (findx > 0)
13773                                 appendPQExpBuffer(query, " OR UPDATE");
13774                         else
13775                                 appendPQExpBuffer(query, " UPDATE");
13776                         findx++;
13777                 }
13778                 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
13779                 {
13780                         if (findx > 0)
13781                                 appendPQExpBuffer(query, " OR TRUNCATE");
13782                         else
13783                                 appendPQExpBuffer(query, " TRUNCATE");
13784                         findx++;
13785                 }
13786                 appendPQExpBuffer(query, " ON %s\n",
13787                                                   fmtId(tbinfo->dobj.name));
13788
13789                 if (tginfo->tgisconstraint)
13790                 {
13791                         if (OidIsValid(tginfo->tgconstrrelid))
13792                         {
13793                                 /* If we are using regclass, name is already quoted */
13794                                 if (fout->remoteVersion >= 70300)
13795                                         appendPQExpBuffer(query, "    FROM %s\n    ",
13796                                                                           tginfo->tgconstrrelname);
13797                                 else
13798                                         appendPQExpBuffer(query, "    FROM %s\n    ",
13799                                                                           fmtId(tginfo->tgconstrrelname));
13800                         }
13801                         if (!tginfo->tgdeferrable)
13802                                 appendPQExpBuffer(query, "NOT ");
13803                         appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
13804                         if (tginfo->tginitdeferred)
13805                                 appendPQExpBuffer(query, "DEFERRED\n");
13806                         else
13807                                 appendPQExpBuffer(query, "IMMEDIATE\n");
13808                 }
13809
13810                 if (TRIGGER_FOR_ROW(tginfo->tgtype))
13811                         appendPQExpBuffer(query, "    FOR EACH ROW\n    ");
13812                 else
13813                         appendPQExpBuffer(query, "    FOR EACH STATEMENT\n    ");
13814
13815                 /* In 7.3, result of regproc is already quoted */
13816                 if (fout->remoteVersion >= 70300)
13817                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13818                                                           tginfo->tgfname);
13819                 else
13820                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13821                                                           fmtId(tginfo->tgfname));
13822
13823                 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
13824                                                                                   &lentgargs);
13825                 p = tgargs;
13826                 for (findx = 0; findx < tginfo->tgnargs; findx++)
13827                 {
13828                         /* find the embedded null that terminates this trigger argument */
13829                         size_t          tlen = strlen(p);
13830
13831                         if (p + tlen >= tgargs + lentgargs)
13832                         {
13833                                 /* hm, not found before end of bytea value... */
13834                                 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
13835                                                   tginfo->tgargs,
13836                                                   tginfo->dobj.name,
13837                                                   tbinfo->dobj.name);
13838                                 exit_nicely(1);
13839                         }
13840
13841                         if (findx > 0)
13842                                 appendPQExpBuffer(query, ", ");
13843                         appendStringLiteralAH(query, p, fout);
13844                         p += tlen + 1;
13845                 }
13846                 free(tgargs);
13847                 appendPQExpBuffer(query, ");\n");
13848         }
13849
13850         if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
13851         {
13852                 appendPQExpBuffer(query, "\nALTER TABLE %s ",
13853                                                   fmtId(tbinfo->dobj.name));
13854                 switch (tginfo->tgenabled)
13855                 {
13856                         case 'D':
13857                         case 'f':
13858                                 appendPQExpBuffer(query, "DISABLE");
13859                                 break;
13860                         case 'A':
13861                                 appendPQExpBuffer(query, "ENABLE ALWAYS");
13862                                 break;
13863                         case 'R':
13864                                 appendPQExpBuffer(query, "ENABLE REPLICA");
13865                                 break;
13866                         default:
13867                                 appendPQExpBuffer(query, "ENABLE");
13868                                 break;
13869                 }
13870                 appendPQExpBuffer(query, " TRIGGER %s;\n",
13871                                                   fmtId(tginfo->dobj.name));
13872         }
13873
13874         appendPQExpBuffer(labelq, "TRIGGER %s ",
13875                                           fmtId(tginfo->dobj.name));
13876         appendPQExpBuffer(labelq, "ON %s",
13877                                           fmtId(tbinfo->dobj.name));
13878
13879         ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
13880                                  tginfo->dobj.name,
13881                                  tbinfo->dobj.namespace->dobj.name,
13882                                  NULL,
13883                                  tbinfo->rolname, false,
13884                                  "TRIGGER", SECTION_POST_DATA,
13885                                  query->data, delqry->data, NULL,
13886                                  NULL, 0,
13887                                  NULL, NULL);
13888
13889         dumpComment(fout, labelq->data,
13890                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13891                                 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
13892
13893         destroyPQExpBuffer(query);
13894         destroyPQExpBuffer(delqry);
13895         destroyPQExpBuffer(labelq);
13896 }
13897
13898 static void
13899 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
13900 {
13901         PQExpBuffer query;
13902         PQExpBuffer labelq;
13903
13904         query = createPQExpBuffer();
13905         labelq = createPQExpBuffer();
13906
13907         appendPQExpBuffer(query, "CREATE EVENT TRIGGER ");
13908         appendPQExpBufferStr(query, fmtId(evtinfo->dobj.name));
13909         appendPQExpBuffer(query, " ON ");
13910         appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
13911         appendPQExpBufferStr(query, " ");
13912
13913         if (strcmp("", evtinfo->evttags) != 0)
13914         {
13915                 appendPQExpBufferStr(query, "\n         WHEN TAG IN (");
13916                 appendPQExpBufferStr(query, evtinfo->evttags);
13917                 appendPQExpBufferStr(query, ") ");
13918         }
13919
13920         appendPQExpBuffer(query, "\n   EXECUTE PROCEDURE ");
13921         appendPQExpBufferStr(query, evtinfo->evtfname);
13922         appendPQExpBuffer(query, "();\n");
13923
13924         if (evtinfo->evtenabled != 'O')
13925         {
13926                 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
13927                                                   fmtId(evtinfo->dobj.name));
13928                 switch (evtinfo->evtenabled)
13929                 {
13930                         case 'D':
13931                                 appendPQExpBuffer(query, "DISABLE");
13932                                 break;
13933                         case 'A':
13934                                 appendPQExpBuffer(query, "ENABLE ALWAYS");
13935                                 break;
13936                         case 'R':
13937                                 appendPQExpBuffer(query, "ENABLE REPLICA");
13938                                 break;
13939                         default:
13940                                 appendPQExpBuffer(query, "ENABLE");
13941                                 break;
13942                 }
13943                 appendPQExpBuffer(query, ";\n");
13944         }
13945         appendPQExpBuffer(labelq, "EVENT TRIGGER %s ",
13946                                           fmtId(evtinfo->dobj.name));
13947
13948         ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
13949                                  evtinfo->dobj.name, NULL, NULL, evtinfo->evtowner, false,
13950                                  "EVENT TRIGGER", SECTION_POST_DATA,
13951                                  query->data, "", NULL, NULL, 0, NULL, NULL);
13952
13953         dumpComment(fout, labelq->data,
13954                                 NULL, NULL,
13955                                 evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
13956
13957         destroyPQExpBuffer(query);
13958         destroyPQExpBuffer(labelq);
13959 }
13960
13961 /*
13962  * dumpRule
13963  *              Dump a rule
13964  */
13965 static void
13966 dumpRule(Archive *fout, RuleInfo *rinfo)
13967 {
13968         TableInfo  *tbinfo = rinfo->ruletable;
13969         PQExpBuffer query;
13970         PQExpBuffer cmd;
13971         PQExpBuffer delcmd;
13972         PQExpBuffer labelq;
13973         PGresult   *res;
13974
13975         /* Skip if not to be dumped */
13976         if (!rinfo->dobj.dump || dataOnly)
13977                 return;
13978
13979         /*
13980          * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
13981          * we do not want to dump it as a separate object.
13982          */
13983         if (!rinfo->separate)
13984                 return;
13985
13986         /*
13987          * Make sure we are in proper schema.
13988          */
13989         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13990
13991         query = createPQExpBuffer();
13992         cmd = createPQExpBuffer();
13993         delcmd = createPQExpBuffer();
13994         labelq = createPQExpBuffer();
13995
13996         if (fout->remoteVersion >= 70300)
13997         {
13998                 appendPQExpBuffer(query,
13999                                                   "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
14000                                                   rinfo->dobj.catId.oid);
14001         }
14002         else
14003         {
14004                 /* Rule name was unique before 7.3 ... */
14005                 appendPQExpBuffer(query,
14006                                                   "SELECT pg_get_ruledef('%s') AS definition",
14007                                                   rinfo->dobj.name);
14008         }
14009
14010         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14011
14012         if (PQntuples(res) != 1)
14013         {
14014                 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
14015                                   rinfo->dobj.name, tbinfo->dobj.name);
14016                 exit_nicely(1);
14017         }
14018
14019         printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
14020
14021         /*
14022          * Add the command to alter the rules replication firing semantics if it
14023          * differs from the default.
14024          */
14025         if (rinfo->ev_enabled != 'O')
14026         {
14027                 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtId(tbinfo->dobj.name));
14028                 switch (rinfo->ev_enabled)
14029                 {
14030                         case 'A':
14031                                 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
14032                                                                   fmtId(rinfo->dobj.name));
14033                                 break;
14034                         case 'R':
14035                                 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
14036                                                                   fmtId(rinfo->dobj.name));
14037                                 break;
14038                         case 'D':
14039                                 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
14040                                                                   fmtId(rinfo->dobj.name));
14041                                 break;
14042                 }
14043         }
14044
14045         /*
14046          * Apply view's reloptions when its ON SELECT rule is separate.
14047          */
14048         if (rinfo->reloptions && strlen(rinfo->reloptions) > 0)
14049         {
14050                 appendPQExpBuffer(cmd, "ALTER VIEW %s SET (%s);\n",
14051                                                   fmtId(tbinfo->dobj.name),
14052                                                   rinfo->reloptions);
14053         }
14054
14055         /*
14056          * DROP must be fully qualified in case same name appears in pg_catalog
14057          */
14058         appendPQExpBuffer(delcmd, "DROP RULE %s ",
14059                                           fmtId(rinfo->dobj.name));
14060         appendPQExpBuffer(delcmd, "ON %s.",
14061                                           fmtId(tbinfo->dobj.namespace->dobj.name));
14062         appendPQExpBuffer(delcmd, "%s;\n",
14063                                           fmtId(tbinfo->dobj.name));
14064
14065         appendPQExpBuffer(labelq, "RULE %s",
14066                                           fmtId(rinfo->dobj.name));
14067         appendPQExpBuffer(labelq, " ON %s",
14068                                           fmtId(tbinfo->dobj.name));
14069
14070         ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
14071                                  rinfo->dobj.name,
14072                                  tbinfo->dobj.namespace->dobj.name,
14073                                  NULL,
14074                                  tbinfo->rolname, false,
14075                                  "RULE", SECTION_POST_DATA,
14076                                  cmd->data, delcmd->data, NULL,
14077                                  NULL, 0,
14078                                  NULL, NULL);
14079
14080         /* Dump rule comments */
14081         dumpComment(fout, labelq->data,
14082                                 tbinfo->dobj.namespace->dobj.name,
14083                                 tbinfo->rolname,
14084                                 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
14085
14086         PQclear(res);
14087
14088         destroyPQExpBuffer(query);
14089         destroyPQExpBuffer(cmd);
14090         destroyPQExpBuffer(delcmd);
14091         destroyPQExpBuffer(labelq);
14092 }
14093
14094 /*
14095  * getExtensionMembership --- obtain extension membership data
14096  */
14097 void
14098 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
14099                                            int numExtensions)
14100 {
14101         PQExpBuffer query;
14102         PGresult   *res;
14103         int                     ntups,
14104                                 i;
14105         int                     i_classid,
14106                                 i_objid,
14107                                 i_refclassid,
14108                                 i_refobjid;
14109         DumpableObject *dobj,
14110                            *refdobj;
14111
14112         /* Nothing to do if no extensions */
14113         if (numExtensions == 0)
14114                 return;
14115
14116         /* Make sure we are in proper schema */
14117         selectSourceSchema(fout, "pg_catalog");
14118
14119         query = createPQExpBuffer();
14120
14121         /* refclassid constraint is redundant but may speed the search */
14122         appendPQExpBuffer(query, "SELECT "
14123                                           "classid, objid, refclassid, refobjid "
14124                                           "FROM pg_depend "
14125                                           "WHERE refclassid = 'pg_extension'::regclass "
14126                                           "AND deptype = 'e' "
14127                                           "ORDER BY 3,4");
14128
14129         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14130
14131         ntups = PQntuples(res);
14132
14133         i_classid = PQfnumber(res, "classid");
14134         i_objid = PQfnumber(res, "objid");
14135         i_refclassid = PQfnumber(res, "refclassid");
14136         i_refobjid = PQfnumber(res, "refobjid");
14137
14138         /*
14139          * Since we ordered the SELECT by referenced ID, we can expect that
14140          * multiple entries for the same extension will appear together; this
14141          * saves on searches.
14142          */
14143         refdobj = NULL;
14144
14145         for (i = 0; i < ntups; i++)
14146         {
14147                 CatalogId       objId;
14148                 CatalogId       refobjId;
14149
14150                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14151                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14152                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14153                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14154
14155                 if (refdobj == NULL ||
14156                         refdobj->catId.tableoid != refobjId.tableoid ||
14157                         refdobj->catId.oid != refobjId.oid)
14158                         refdobj = findObjectByCatalogId(refobjId);
14159
14160                 /*
14161                  * Failure to find objects mentioned in pg_depend is not unexpected,
14162                  * since for example we don't collect info about TOAST tables.
14163                  */
14164                 if (refdobj == NULL)
14165                 {
14166 #ifdef NOT_USED
14167                         fprintf(stderr, "no referenced object %u %u\n",
14168                                         refobjId.tableoid, refobjId.oid);
14169 #endif
14170                         continue;
14171                 }
14172
14173                 dobj = findObjectByCatalogId(objId);
14174
14175                 if (dobj == NULL)
14176                 {
14177 #ifdef NOT_USED
14178                         fprintf(stderr, "no referencing object %u %u\n",
14179                                         objId.tableoid, objId.oid);
14180 #endif
14181                         continue;
14182                 }
14183
14184                 /* Record dependency so that getDependencies needn't repeat this */
14185                 addObjectDependency(dobj, refdobj->dumpId);
14186
14187                 dobj->ext_member = true;
14188
14189                 /*
14190                  * Normally, mark the member object as not to be dumped.  But in
14191                  * binary upgrades, we still dump the members individually, since the
14192                  * idea is to exactly reproduce the database contents rather than
14193                  * replace the extension contents with something different.
14194                  */
14195                 if (!binary_upgrade)
14196                         dobj->dump = false;
14197                 else
14198                         dobj->dump = refdobj->dump;
14199         }
14200
14201         PQclear(res);
14202
14203         /*
14204          * Now identify extension configuration tables and create TableDataInfo
14205          * objects for them, ensuring their data will be dumped even though the
14206          * tables themselves won't be.
14207          *
14208          * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
14209          * user data in a configuration table is treated like schema data. This
14210          * seems appropriate since system data in a config table would get
14211          * reloaded by CREATE EXTENSION.
14212          */
14213         for (i = 0; i < numExtensions; i++)
14214         {
14215                 ExtensionInfo *curext = &(extinfo[i]);
14216                 char       *extconfig = curext->extconfig;
14217                 char       *extcondition = curext->extcondition;
14218                 char      **extconfigarray = NULL;
14219                 char      **extconditionarray = NULL;
14220                 int                     nconfigitems;
14221                 int                     nconditionitems;
14222
14223                 /* Tables of not-to-be-dumped extensions shouldn't be dumped */
14224                 if (!curext->dobj.dump)
14225                         continue;
14226
14227                 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
14228                   parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
14229                         nconfigitems == nconditionitems)
14230                 {
14231                         int                     j;
14232
14233                         for (j = 0; j < nconfigitems; j++)
14234                         {
14235                                 TableInfo  *configtbl;
14236
14237                                 configtbl = findTableByOid(atooid(extconfigarray[j]));
14238                                 if (configtbl == NULL)
14239                                         continue;
14240
14241                                 /*
14242                                  * Note: config tables are dumped without OIDs regardless of
14243                                  * the --oids setting.  This is because row filtering
14244                                  * conditions aren't compatible with dumping OIDs.
14245                                  */
14246                                 makeTableDataInfo(configtbl, false);
14247                                 if (configtbl->dataObj != NULL)
14248                                 {
14249                                         if (strlen(extconditionarray[j]) > 0)
14250                                                 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
14251                                 }
14252                         }
14253                 }
14254                 if (extconfigarray)
14255                         free(extconfigarray);
14256                 if (extconditionarray)
14257                         free(extconditionarray);
14258         }
14259
14260         destroyPQExpBuffer(query);
14261 }
14262
14263 /*
14264  * getDependencies --- obtain available dependency data
14265  */
14266 static void
14267 getDependencies(Archive *fout)
14268 {
14269         PQExpBuffer query;
14270         PGresult   *res;
14271         int                     ntups,
14272                                 i;
14273         int                     i_classid,
14274                                 i_objid,
14275                                 i_refclassid,
14276                                 i_refobjid,
14277                                 i_deptype;
14278         DumpableObject *dobj,
14279                            *refdobj;
14280
14281         /* No dependency info available before 7.3 */
14282         if (fout->remoteVersion < 70300)
14283                 return;
14284
14285         if (g_verbose)
14286                 write_msg(NULL, "reading dependency data\n");
14287
14288         /* Make sure we are in proper schema */
14289         selectSourceSchema(fout, "pg_catalog");
14290
14291         query = createPQExpBuffer();
14292
14293         /*
14294          * PIN dependencies aren't interesting, and EXTENSION dependencies were
14295          * already processed by getExtensionMembership.
14296          */
14297         appendPQExpBuffer(query, "SELECT "
14298                                           "classid, objid, refclassid, refobjid, deptype "
14299                                           "FROM pg_depend "
14300                                           "WHERE deptype != 'p' AND deptype != 'e' "
14301                                           "ORDER BY 1,2");
14302
14303         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14304
14305         ntups = PQntuples(res);
14306
14307         i_classid = PQfnumber(res, "classid");
14308         i_objid = PQfnumber(res, "objid");
14309         i_refclassid = PQfnumber(res, "refclassid");
14310         i_refobjid = PQfnumber(res, "refobjid");
14311         i_deptype = PQfnumber(res, "deptype");
14312
14313         /*
14314          * Since we ordered the SELECT by referencing ID, we can expect that
14315          * multiple entries for the same object will appear together; this saves
14316          * on searches.
14317          */
14318         dobj = NULL;
14319
14320         for (i = 0; i < ntups; i++)
14321         {
14322                 CatalogId       objId;
14323                 CatalogId       refobjId;
14324                 char            deptype;
14325
14326                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14327                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14328                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14329                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14330                 deptype = *(PQgetvalue(res, i, i_deptype));
14331
14332                 if (dobj == NULL ||
14333                         dobj->catId.tableoid != objId.tableoid ||
14334                         dobj->catId.oid != objId.oid)
14335                         dobj = findObjectByCatalogId(objId);
14336
14337                 /*
14338                  * Failure to find objects mentioned in pg_depend is not unexpected,
14339                  * since for example we don't collect info about TOAST tables.
14340                  */
14341                 if (dobj == NULL)
14342                 {
14343 #ifdef NOT_USED
14344                         fprintf(stderr, "no referencing object %u %u\n",
14345                                         objId.tableoid, objId.oid);
14346 #endif
14347                         continue;
14348                 }
14349
14350                 refdobj = findObjectByCatalogId(refobjId);
14351
14352                 if (refdobj == NULL)
14353                 {
14354 #ifdef NOT_USED
14355                         fprintf(stderr, "no referenced object %u %u\n",
14356                                         refobjId.tableoid, refobjId.oid);
14357 #endif
14358                         continue;
14359                 }
14360
14361                 /*
14362                  * Ordinarily, table rowtypes have implicit dependencies on their
14363                  * tables.      However, for a composite type the implicit dependency goes
14364                  * the other way in pg_depend; which is the right thing for DROP but
14365                  * it doesn't produce the dependency ordering we need. So in that one
14366                  * case, we reverse the direction of the dependency.
14367                  */
14368                 if (deptype == 'i' &&
14369                         dobj->objType == DO_TABLE &&
14370                         refdobj->objType == DO_TYPE)
14371                         addObjectDependency(refdobj, dobj->dumpId);
14372                 else
14373                         /* normal case */
14374                         addObjectDependency(dobj, refdobj->dumpId);
14375         }
14376
14377         PQclear(res);
14378
14379         destroyPQExpBuffer(query);
14380 }
14381
14382
14383 /*
14384  * createBoundaryObjects - create dummy DumpableObjects to represent
14385  * dump section boundaries.
14386  */
14387 static DumpableObject *
14388 createBoundaryObjects(void)
14389 {
14390         DumpableObject *dobjs;
14391
14392         dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
14393
14394         dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
14395         dobjs[0].catId = nilCatalogId;
14396         AssignDumpId(dobjs + 0);
14397         dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
14398
14399         dobjs[1].objType = DO_POST_DATA_BOUNDARY;
14400         dobjs[1].catId = nilCatalogId;
14401         AssignDumpId(dobjs + 1);
14402         dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
14403
14404         return dobjs;
14405 }
14406
14407 /*
14408  * addBoundaryDependencies - add dependencies as needed to enforce the dump
14409  * section boundaries.
14410  */
14411 static void
14412 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
14413                                                 DumpableObject *boundaryObjs)
14414 {
14415         DumpableObject *preDataBound = boundaryObjs + 0;
14416         DumpableObject *postDataBound = boundaryObjs + 1;
14417         int                     i;
14418
14419         for (i = 0; i < numObjs; i++)
14420         {
14421                 DumpableObject *dobj = dobjs[i];
14422
14423                 /*
14424                  * The classification of object types here must match the SECTION_xxx
14425                  * values assigned during subsequent ArchiveEntry calls!
14426                  */
14427                 switch (dobj->objType)
14428                 {
14429                         case DO_NAMESPACE:
14430                         case DO_EXTENSION:
14431                         case DO_TYPE:
14432                         case DO_SHELL_TYPE:
14433                         case DO_FUNC:
14434                         case DO_AGG:
14435                         case DO_OPERATOR:
14436                         case DO_OPCLASS:
14437                         case DO_OPFAMILY:
14438                         case DO_COLLATION:
14439                         case DO_CONVERSION:
14440                         case DO_TABLE:
14441                         case DO_ATTRDEF:
14442                         case DO_PROCLANG:
14443                         case DO_CAST:
14444                         case DO_DUMMY_TYPE:
14445                         case DO_TSPARSER:
14446                         case DO_TSDICT:
14447                         case DO_TSTEMPLATE:
14448                         case DO_TSCONFIG:
14449                         case DO_FDW:
14450                         case DO_FOREIGN_SERVER:
14451                         case DO_BLOB:
14452                                 /* Pre-data objects: must come before the pre-data boundary */
14453                                 addObjectDependency(preDataBound, dobj->dumpId);
14454                                 break;
14455                         case DO_TABLE_DATA:
14456                         case DO_BLOB_DATA:
14457                                 /* Data objects: must come between the boundaries */
14458                                 addObjectDependency(dobj, preDataBound->dumpId);
14459                                 addObjectDependency(postDataBound, dobj->dumpId);
14460                                 break;
14461                         case DO_INDEX:
14462                         case DO_TRIGGER:
14463                         case DO_EVENT_TRIGGER:
14464                         case DO_DEFAULT_ACL:
14465                                 /* Post-data objects: must come after the post-data boundary */
14466                                 addObjectDependency(dobj, postDataBound->dumpId);
14467                                 break;
14468                         case DO_RULE:
14469                                 /* Rules are post-data, but only if dumped separately */
14470                                 if (((RuleInfo *) dobj)->separate)
14471                                         addObjectDependency(dobj, postDataBound->dumpId);
14472                                 break;
14473                         case DO_CONSTRAINT:
14474                         case DO_FK_CONSTRAINT:
14475                                 /* Constraints are post-data, but only if dumped separately */
14476                                 if (((ConstraintInfo *) dobj)->separate)
14477                                         addObjectDependency(dobj, postDataBound->dumpId);
14478                                 break;
14479                         case DO_PRE_DATA_BOUNDARY:
14480                                 /* nothing to do */
14481                                 break;
14482                         case DO_POST_DATA_BOUNDARY:
14483                                 /* must come after the pre-data boundary */
14484                                 addObjectDependency(dobj, preDataBound->dumpId);
14485                                 break;
14486                 }
14487         }
14488 }
14489
14490
14491 /*
14492  * BuildArchiveDependencies - create dependency data for archive TOC entries
14493  *
14494  * The raw dependency data obtained by getDependencies() is not terribly
14495  * useful in an archive dump, because in many cases there are dependency
14496  * chains linking through objects that don't appear explicitly in the dump.
14497  * For example, a view will depend on its _RETURN rule while the _RETURN rule
14498  * will depend on other objects --- but the rule will not appear as a separate
14499  * object in the dump.  We need to adjust the view's dependencies to include
14500  * whatever the rule depends on that is included in the dump.
14501  *
14502  * Just to make things more complicated, there are also "special" dependencies
14503  * such as the dependency of a TABLE DATA item on its TABLE, which we must
14504  * not rearrange because pg_restore knows that TABLE DATA only depends on
14505  * its table.  In these cases we must leave the dependencies strictly as-is
14506  * even if they refer to not-to-be-dumped objects.
14507  *
14508  * To handle this, the convention is that "special" dependencies are created
14509  * during ArchiveEntry calls, and an archive TOC item that has any such
14510  * entries will not be touched here.  Otherwise, we recursively search the
14511  * DumpableObject data structures to build the correct dependencies for each
14512  * archive TOC item.
14513  */
14514 static void
14515 BuildArchiveDependencies(Archive *fout)
14516 {
14517         ArchiveHandle *AH = (ArchiveHandle *) fout;
14518         TocEntry   *te;
14519
14520         /* Scan all TOC entries in the archive */
14521         for (te = AH->toc->next; te != AH->toc; te = te->next)
14522         {
14523                 DumpableObject *dobj;
14524                 DumpId     *dependencies;
14525                 int                     nDeps;
14526                 int                     allocDeps;
14527
14528                 /* No need to process entries that will not be dumped */
14529                 if (te->reqs == 0)
14530                         continue;
14531                 /* Ignore entries that already have "special" dependencies */
14532                 if (te->nDeps > 0)
14533                         continue;
14534                 /* Otherwise, look up the item's original DumpableObject, if any */
14535                 dobj = findObjectByDumpId(te->dumpId);
14536                 if (dobj == NULL)
14537                         continue;
14538                 /* No work if it has no dependencies */
14539                 if (dobj->nDeps <= 0)
14540                         continue;
14541                 /* Set up work array */
14542                 allocDeps = 64;
14543                 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
14544                 nDeps = 0;
14545                 /* Recursively find all dumpable dependencies */
14546                 findDumpableDependencies(AH, dobj,
14547                                                                  &dependencies, &nDeps, &allocDeps);
14548                 /* And save 'em ... */
14549                 if (nDeps > 0)
14550                 {
14551                         dependencies = (DumpId *) pg_realloc(dependencies,
14552                                                                                                  nDeps * sizeof(DumpId));
14553                         te->dependencies = dependencies;
14554                         te->nDeps = nDeps;
14555                 }
14556                 else
14557                         free(dependencies);
14558         }
14559 }
14560
14561 /* Recursive search subroutine for BuildArchiveDependencies */
14562 static void
14563 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
14564                                                  DumpId **dependencies, int *nDeps, int *allocDeps)
14565 {
14566         int                     i;
14567
14568         /*
14569          * Ignore section boundary objects: if we search through them, we'll
14570          * report lots of bogus dependencies.
14571          */
14572         if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
14573                 dobj->objType == DO_POST_DATA_BOUNDARY)
14574                 return;
14575
14576         for (i = 0; i < dobj->nDeps; i++)
14577         {
14578                 DumpId          depid = dobj->dependencies[i];
14579
14580                 if (TocIDRequired(AH, depid) != 0)
14581                 {
14582                         /* Object will be dumped, so just reference it as a dependency */
14583                         if (*nDeps >= *allocDeps)
14584                         {
14585                                 *allocDeps *= 2;
14586                                 *dependencies = (DumpId *) pg_realloc(*dependencies,
14587                                                                                           *allocDeps * sizeof(DumpId));
14588                         }
14589                         (*dependencies)[*nDeps] = depid;
14590                         (*nDeps)++;
14591                 }
14592                 else
14593                 {
14594                         /*
14595                          * Object will not be dumped, so recursively consider its deps.
14596                          * We rely on the assumption that sortDumpableObjects already
14597                          * broke any dependency loops, else we might recurse infinitely.
14598                          */
14599                         DumpableObject *otherdobj = findObjectByDumpId(depid);
14600
14601                         if (otherdobj)
14602                                 findDumpableDependencies(AH, otherdobj,
14603                                                                                  dependencies, nDeps, allocDeps);
14604                 }
14605         }
14606 }
14607
14608
14609 /*
14610  * selectSourceSchema - make the specified schema the active search path
14611  * in the source database.
14612  *
14613  * NB: pg_catalog is explicitly searched after the specified schema;
14614  * so user names are only qualified if they are cross-schema references,
14615  * and system names are only qualified if they conflict with a user name
14616  * in the current schema.
14617  *
14618  * Whenever the selected schema is not pg_catalog, be careful to qualify
14619  * references to system catalogs and types in our emitted commands!
14620  */
14621 static void
14622 selectSourceSchema(Archive *fout, const char *schemaName)
14623 {
14624         static char *curSchemaName = NULL;
14625         PQExpBuffer query;
14626
14627         /* Not relevant if fetching from pre-7.3 DB */
14628         if (fout->remoteVersion < 70300)
14629                 return;
14630         /* Ignore null schema names */
14631         if (schemaName == NULL || *schemaName == '\0')
14632                 return;
14633         /* Optimize away repeated selection of same schema */
14634         if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14635                 return;
14636
14637         query = createPQExpBuffer();
14638         appendPQExpBuffer(query, "SET search_path = %s",
14639                                           fmtId(schemaName));
14640         if (strcmp(schemaName, "pg_catalog") != 0)
14641                 appendPQExpBuffer(query, ", pg_catalog");
14642
14643         ExecuteSqlStatement(fout, query->data);
14644
14645         destroyPQExpBuffer(query);
14646         if (curSchemaName)
14647                 free(curSchemaName);
14648         curSchemaName = pg_strdup(schemaName);
14649 }
14650
14651 /*
14652  * getFormattedTypeName - retrieve a nicely-formatted type name for the
14653  * given type name.
14654  *
14655  * NB: in 7.3 and up the result may depend on the currently-selected
14656  * schema; this is why we don't try to cache the names.
14657  */
14658 static char *
14659 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
14660 {
14661         char       *result;
14662         PQExpBuffer query;
14663         PGresult   *res;
14664
14665         if (oid == 0)
14666         {
14667                 if ((opts & zeroAsOpaque) != 0)
14668                         return pg_strdup(g_opaque_type);
14669                 else if ((opts & zeroAsAny) != 0)
14670                         return pg_strdup("'any'");
14671                 else if ((opts & zeroAsStar) != 0)
14672                         return pg_strdup("*");
14673                 else if ((opts & zeroAsNone) != 0)
14674                         return pg_strdup("NONE");
14675         }
14676
14677         query = createPQExpBuffer();
14678         if (fout->remoteVersion >= 70300)
14679         {
14680                 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14681                                                   oid);
14682         }
14683         else if (fout->remoteVersion >= 70100)
14684         {
14685                 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14686                                                   oid);
14687         }
14688         else
14689         {
14690                 appendPQExpBuffer(query, "SELECT typname "
14691                                                   "FROM pg_type "
14692                                                   "WHERE oid = '%u'::oid",
14693                                                   oid);
14694         }
14695
14696         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14697
14698         if (fout->remoteVersion >= 70100)
14699         {
14700                 /* already quoted */
14701                 result = pg_strdup(PQgetvalue(res, 0, 0));
14702         }
14703         else
14704         {
14705                 /* may need to quote it */
14706                 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14707         }
14708
14709         PQclear(res);
14710         destroyPQExpBuffer(query);
14711
14712         return result;
14713 }
14714
14715 /*
14716  * myFormatType --- local implementation of format_type for use with 7.0.
14717  */
14718 static char *
14719 myFormatType(const char *typname, int32 typmod)
14720 {
14721         char       *result;
14722         bool            isarray = false;
14723         PQExpBuffer buf = createPQExpBuffer();
14724
14725         /* Handle array types */
14726         if (typname[0] == '_')
14727         {
14728                 isarray = true;
14729                 typname++;
14730         }
14731
14732         /* Show lengths on bpchar and varchar */
14733         if (strcmp(typname, "bpchar") == 0)
14734         {
14735                 int                     len = (typmod - VARHDRSZ);
14736
14737                 appendPQExpBuffer(buf, "character");
14738                 if (len > 1)
14739                         appendPQExpBuffer(buf, "(%d)",
14740                                                           typmod - VARHDRSZ);
14741         }
14742         else if (strcmp(typname, "varchar") == 0)
14743         {
14744                 appendPQExpBuffer(buf, "character varying");
14745                 if (typmod != -1)
14746                         appendPQExpBuffer(buf, "(%d)",
14747                                                           typmod - VARHDRSZ);
14748         }
14749         else if (strcmp(typname, "numeric") == 0)
14750         {
14751                 appendPQExpBuffer(buf, "numeric");
14752                 if (typmod != -1)
14753                 {
14754                         int32           tmp_typmod;
14755                         int                     precision;
14756                         int                     scale;
14757
14758                         tmp_typmod = typmod - VARHDRSZ;
14759                         precision = (tmp_typmod >> 16) & 0xffff;
14760                         scale = tmp_typmod & 0xffff;
14761                         appendPQExpBuffer(buf, "(%d,%d)",
14762                                                           precision, scale);
14763                 }
14764         }
14765
14766         /*
14767          * char is an internal single-byte data type; Let's make sure we force it
14768          * through with quotes. - thomas 1998-12-13
14769          */
14770         else if (strcmp(typname, "char") == 0)
14771                 appendPQExpBuffer(buf, "\"char\"");
14772         else
14773                 appendPQExpBuffer(buf, "%s", fmtId(typname));
14774
14775         /* Append array qualifier for array types */
14776         if (isarray)
14777                 appendPQExpBuffer(buf, "[]");
14778
14779         result = pg_strdup(buf->data);
14780         destroyPQExpBuffer(buf);
14781
14782         return result;
14783 }
14784
14785 /*
14786  * fmtQualifiedId - convert a qualified name to the proper format for
14787  * the source database.
14788  *
14789  * Like fmtId, use the result before calling again.
14790  */
14791 static const char *
14792 fmtQualifiedId(Archive *fout, const char *schema, const char *id)
14793 {
14794         static PQExpBuffer id_return = NULL;
14795
14796         if (id_return)                          /* first time through? */
14797                 resetPQExpBuffer(id_return);
14798         else
14799                 id_return = createPQExpBuffer();
14800
14801         /* Suppress schema name if fetching from pre-7.3 DB */
14802         if (fout->remoteVersion >= 70300 && schema && *schema)
14803         {
14804                 appendPQExpBuffer(id_return, "%s.",
14805                                                   fmtId(schema));
14806         }
14807         appendPQExpBuffer(id_return, "%s",
14808                                           fmtId(id));
14809
14810         return id_return->data;
14811 }
14812
14813 /*
14814  * Return a column list clause for the given relation.
14815  *
14816  * Special case: if there are no undropped columns in the relation, return
14817  * "", not an invalid "()" column list.
14818  */
14819 static const char *
14820 fmtCopyColumnList(const TableInfo *ti)
14821 {
14822         static PQExpBuffer q = NULL;
14823         int                     numatts = ti->numatts;
14824         char      **attnames = ti->attnames;
14825         bool       *attisdropped = ti->attisdropped;
14826         bool            needComma;
14827         int                     i;
14828
14829         if (q)                                          /* first time through? */
14830                 resetPQExpBuffer(q);
14831         else
14832                 q = createPQExpBuffer();
14833
14834         appendPQExpBuffer(q, "(");
14835         needComma = false;
14836         for (i = 0; i < numatts; i++)
14837         {
14838                 if (attisdropped[i])
14839                         continue;
14840                 if (needComma)
14841                         appendPQExpBuffer(q, ", ");
14842                 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
14843                 needComma = true;
14844         }
14845
14846         if (!needComma)
14847                 return "";                              /* no undropped columns */
14848
14849         appendPQExpBuffer(q, ")");
14850         return q->data;
14851 }
14852
14853 /*
14854  * Execute an SQL query and verify that we got exactly one row back.
14855  */
14856 static PGresult *
14857 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
14858 {
14859         PGresult   *res;
14860         int                     ntups;
14861
14862         res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
14863
14864         /* Expecting a single result only */
14865         ntups = PQntuples(res);
14866         if (ntups != 1)
14867                 exit_horribly(NULL,
14868                                           ngettext("query returned %d row instead of one: %s\n",
14869                                                            "query returned %d rows instead of one: %s\n",
14870                                                            ntups),
14871                                           ntups, query);
14872
14873         return res;
14874 }