]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_dump.c
Fix O(N^2) behavior in pg_dump for large numbers of owned sequences.
[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-2012, 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_largeobject.h"
53 #include "catalog/pg_largeobject_metadata.h"
54 #include "catalog/pg_proc.h"
55 #include "catalog/pg_trigger.h"
56 #include "catalog/pg_type.h"
57 #include "libpq/libpq-fs.h"
58
59 #include "pg_backup_archiver.h"
60 #include "pg_backup_db.h"
61 #include "dumpmem.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 /* these are to avoid passing around info for findNamespace() */
133 static NamespaceInfo *g_namespaces;
134 static int      g_numNamespaces;
135
136 /* flags for various command-line long options */
137 static int      binary_upgrade = 0;
138 static int      disable_dollar_quoting = 0;
139 static int      dump_inserts = 0;
140 static int      column_inserts = 0;
141 static int      no_security_labels = 0;
142 static int      no_unlogged_table_data = 0;
143 static int      serializable_deferrable = 0;
144
145
146 static void help(const char *progname);
147 static void setup_connection(Archive *AH, const char *dumpencoding,
148                                  char *use_role);
149 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
150 static void expand_schema_name_patterns(Archive *fout,
151                                                         SimpleStringList *patterns,
152                                                         SimpleOidList *oids);
153 static void expand_table_name_patterns(Archive *fout,
154                                                    SimpleStringList *patterns,
155                                                    SimpleOidList *oids);
156 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid, Oid objoid);
157 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
158 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
159 static void dumpComment(Archive *fout, const char *target,
160                         const char *namespace, const char *owner,
161                         CatalogId catalogId, int subid, DumpId dumpId);
162 static int findComments(Archive *fout, Oid classoid, Oid objoid,
163                          CommentItem **items);
164 static int      collectComments(Archive *fout, CommentItem **items);
165 static void dumpSecLabel(Archive *fout, const char *target,
166                          const char *namespace, const char *owner,
167                          CatalogId catalogId, int subid, DumpId dumpId);
168 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
169                           SecLabelItem **items);
170 static int      collectSecLabels(Archive *fout, SecLabelItem **items);
171 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
172 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
173 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
174 static void dumpType(Archive *fout, TypeInfo *tyinfo);
175 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
176 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
177 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
178 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
179 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
180 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
181 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
182 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
183 static void dumpFunc(Archive *fout, FuncInfo *finfo);
184 static void dumpCast(Archive *fout, CastInfo *cast);
185 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
186 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
187 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
188 static void dumpCollation(Archive *fout, CollInfo *convinfo);
189 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
190 static void dumpRule(Archive *fout, RuleInfo *rinfo);
191 static void dumpAgg(Archive *fout, AggInfo *agginfo);
192 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
193 static void dumpTable(Archive *fout, TableInfo *tbinfo);
194 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
195 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
196 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
197 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
198 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
199 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
200 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
201 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
202 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
203 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
204 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
205 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
206 static void dumpUserMappings(Archive *fout,
207                                  const char *servername, const char *namespace,
208                                  const char *owner, CatalogId catalogId, DumpId dumpId);
209 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
210
211 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
212                 const char *type, const char *name, const char *subname,
213                 const char *tag, const char *nspname, const char *owner,
214                 const char *acls);
215
216 static void getDependencies(Archive *fout);
217 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
218 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
219 static void makeTableDataInfo(TableInfo *tbinfo, bool oids);
220 static void getTableDataFKConstraints(void);
221 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
222 static char *format_function_arguments_old(Archive *fout,
223                                                           FuncInfo *finfo, int nallargs,
224                                                           char **allargtypes,
225                                                           char **argmodes,
226                                                           char **argnames);
227 static char *format_function_signature(Archive *fout,
228                                                                            FuncInfo *finfo, bool honor_quotes);
229 static const char *convertRegProcReference(Archive *fout,
230                                                                                    const char *proc);
231 static const char *convertOperatorReference(Archive *fout, const char *opr);
232 static const char *convertTSFunction(Archive *fout, Oid funcOid);
233 static Oid      findLastBuiltinOid_V71(Archive *fout, const char *);
234 static Oid      findLastBuiltinOid_V70(Archive *fout);
235 static void selectSourceSchema(Archive *fout, const char *schemaName);
236 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
237 static char *myFormatType(const char *typname, int32 typmod);
238 static const char *fmtQualifiedId(Archive *fout,
239                                                                   const char *schema, const char *id);
240 static void getBlobs(Archive *fout);
241 static void dumpBlob(Archive *fout, BlobInfo *binfo);
242 static int      dumpBlobs(Archive *fout, void *arg);
243 static void dumpDatabase(Archive *AH);
244 static void dumpEncoding(Archive *AH);
245 static void dumpStdStrings(Archive *AH);
246 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
247                                                                 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
248 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
249                                                                  PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
250 static void binary_upgrade_set_pg_class_oids(Archive *fout,
251                                                                  PQExpBuffer upgrade_buffer,
252                                                                  Oid pg_class_oid, bool is_index);
253 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
254                                                                 DumpableObject *dobj,
255                                                                 const char *objlabel);
256 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
257 static const char *fmtCopyColumnList(const TableInfo *ti);
258 static PGresult *ExecuteSqlQueryForSingleRow(Archive *fout, char *query);
259
260 int
261 main(int argc, char **argv)
262 {
263         int                     c;
264         const char *filename = NULL;
265         const char *format = "p";
266         const char *dbname = NULL;
267         const char *pghost = NULL;
268         const char *pgport = NULL;
269         const char *username = NULL;
270         const char *dumpencoding = NULL;
271         bool            oids = false;
272         TableInfo  *tblinfo;
273         int                     numTables;
274         DumpableObject **dobjs;
275         int                     numObjs;
276         int                     i;
277         enum trivalue prompt_password = TRI_DEFAULT;
278         int                     compressLevel = -1;
279         int                     plainText = 0;
280         int                     outputClean = 0;
281         int                     outputCreateDB = 0;
282         bool            outputBlobs = false;
283         int                     outputNoOwner = 0;
284         char       *outputSuperuser = NULL;
285         char       *use_role = NULL;
286         int                     my_version;
287         int                     optindex;
288         RestoreOptions *ropt;
289         ArchiveFormat archiveFormat = archUnknown;
290         ArchiveMode archiveMode;
291         Archive    *fout;                               /* the script file */
292
293         static int      disable_triggers = 0;
294         static int      outputNoTablespaces = 0;
295         static int      use_setsessauth = 0;
296
297         static struct option long_options[] = {
298                 {"data-only", no_argument, NULL, 'a'},
299                 {"blobs", no_argument, NULL, 'b'},
300                 {"clean", no_argument, NULL, 'c'},
301                 {"create", no_argument, NULL, 'C'},
302                 {"file", required_argument, NULL, 'f'},
303                 {"format", required_argument, NULL, 'F'},
304                 {"host", required_argument, NULL, 'h'},
305                 {"ignore-version", no_argument, NULL, 'i'},
306                 {"no-reconnect", no_argument, NULL, 'R'},
307                 {"oids", no_argument, NULL, 'o'},
308                 {"no-owner", no_argument, NULL, 'O'},
309                 {"port", required_argument, NULL, 'p'},
310                 {"schema", required_argument, NULL, 'n'},
311                 {"exclude-schema", required_argument, NULL, 'N'},
312                 {"schema-only", no_argument, NULL, 's'},
313                 {"superuser", required_argument, NULL, 'S'},
314                 {"table", required_argument, NULL, 't'},
315                 {"exclude-table", required_argument, NULL, 'T'},
316                 {"no-password", no_argument, NULL, 'w'},
317                 {"password", no_argument, NULL, 'W'},
318                 {"username", required_argument, NULL, 'U'},
319                 {"verbose", no_argument, NULL, 'v'},
320                 {"no-privileges", no_argument, NULL, 'x'},
321                 {"no-acl", no_argument, NULL, 'x'},
322                 {"compress", required_argument, NULL, 'Z'},
323                 {"encoding", required_argument, NULL, 'E'},
324                 {"help", no_argument, NULL, '?'},
325                 {"version", no_argument, NULL, 'V'},
326
327                 /*
328                  * the following options don't have an equivalent short option letter
329                  */
330                 {"attribute-inserts", no_argument, &column_inserts, 1},
331                 {"binary-upgrade", no_argument, &binary_upgrade, 1},
332                 {"column-inserts", no_argument, &column_inserts, 1},
333                 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
334                 {"disable-triggers", no_argument, &disable_triggers, 1},
335                 {"exclude-table-data", required_argument, NULL, 4},
336                 {"inserts", no_argument, &dump_inserts, 1},
337                 {"lock-wait-timeout", required_argument, NULL, 2},
338                 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
339                 {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
340                 {"role", required_argument, NULL, 3},
341                 {"section", required_argument, NULL, 5},
342                 {"serializable-deferrable", no_argument, &serializable_deferrable, 1},
343                 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
344                 {"no-security-labels", no_argument, &no_security_labels, 1},
345                 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
346
347                 {NULL, 0, NULL, 0}
348         };
349
350         set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
351
352         g_verbose = false;
353
354         strcpy(g_comment_start, "-- ");
355         g_comment_end[0] = '\0';
356         strcpy(g_opaque_type, "opaque");
357
358         dataOnly = schemaOnly = false;
359         dumpSections = DUMP_UNSECTIONED;
360         lockWaitTimeout = NULL;
361
362         progname = get_progname(argv[0]);
363
364         /* Set default options based on progname */
365         if (strcmp(progname, "pg_backup") == 0)
366                 format = "c";
367
368         if (argc > 1)
369         {
370                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
371                 {
372                         help(progname);
373                         exit_nicely(0);
374                 }
375                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
376                 {
377                         puts("pg_dump (PostgreSQL) " PG_VERSION);
378                         exit_nicely(0);
379                 }
380         }
381
382         while ((c = getopt_long(argc, argv, "abcCE:f:F:h:in:N:oOp:RsS:t:T:U:vwWxZ:",
383                                                         long_options, &optindex)) != -1)
384         {
385                 switch (c)
386                 {
387                         case 'a':                       /* Dump data only */
388                                 dataOnly = true;
389                                 break;
390
391                         case 'b':                       /* Dump blobs */
392                                 outputBlobs = true;
393                                 break;
394
395                         case 'c':                       /* clean (i.e., drop) schema prior to create */
396                                 outputClean = 1;
397                                 break;
398
399                         case 'C':                       /* Create DB */
400                                 outputCreateDB = 1;
401                                 break;
402
403                         case 'E':                       /* Dump encoding */
404                                 dumpencoding = optarg;
405                                 break;
406
407                         case 'f':
408                                 filename = optarg;
409                                 break;
410
411                         case 'F':
412                                 format = optarg;
413                                 break;
414
415                         case 'h':                       /* server host */
416                                 pghost = optarg;
417                                 break;
418
419                         case 'i':
420                                 /* ignored, deprecated option */
421                                 break;
422
423                         case 'n':                       /* include schema(s) */
424                                 simple_string_list_append(&schema_include_patterns, optarg);
425                                 include_everything = false;
426                                 break;
427
428                         case 'N':                       /* exclude schema(s) */
429                                 simple_string_list_append(&schema_exclude_patterns, optarg);
430                                 break;
431
432                         case 'o':                       /* Dump oids */
433                                 oids = true;
434                                 break;
435
436                         case 'O':                       /* Don't reconnect to match owner */
437                                 outputNoOwner = 1;
438                                 break;
439
440                         case 'p':                       /* server port */
441                                 pgport = optarg;
442                                 break;
443
444                         case 'R':
445                                 /* no-op, still accepted for backwards compatibility */
446                                 break;
447
448                         case 's':                       /* dump schema only */
449                                 schemaOnly = true;
450                                 break;
451
452                         case 'S':                       /* Username for superuser in plain text output */
453                                 outputSuperuser = pg_strdup(optarg);
454                                 break;
455
456                         case 't':                       /* include table(s) */
457                                 simple_string_list_append(&table_include_patterns, optarg);
458                                 include_everything = false;
459                                 break;
460
461                         case 'T':                       /* exclude table(s) */
462                                 simple_string_list_append(&table_exclude_patterns, optarg);
463                                 break;
464
465                         case 'U':
466                                 username = optarg;
467                                 break;
468
469                         case 'v':                       /* verbose */
470                                 g_verbose = true;
471                                 break;
472
473                         case 'w':
474                                 prompt_password = TRI_NO;
475                                 break;
476
477                         case 'W':
478                                 prompt_password = TRI_YES;
479                                 break;
480
481                         case 'x':                       /* skip ACL dump */
482                                 aclsSkip = true;
483                                 break;
484
485                         case 'Z':                       /* Compression Level */
486                                 compressLevel = atoi(optarg);
487                                 break;
488
489                         case 0:
490                                 /* This covers the long options. */
491                                 break;
492
493                         case 2:                         /* lock-wait-timeout */
494                                 lockWaitTimeout = optarg;
495                                 break;
496
497                         case 3:                         /* SET ROLE */
498                                 use_role = optarg;
499                                 break;
500
501                         case 4:                 /* exclude table(s) data */
502                                 simple_string_list_append(&tabledata_exclude_patterns, optarg);
503                                 break;
504
505                         case 5:                         /* section */
506                                 set_section(optarg, &dumpSections);
507                                 break;
508
509                         default:
510                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
511                                 exit_nicely(1);
512                 }
513         }
514
515         /* Get database name from command line */
516         if (optind < argc)
517                 dbname = argv[optind++];
518
519         /* Complain if any arguments remain */
520         if (optind < argc)
521         {
522                 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
523                                 progname, argv[optind]);
524                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
525                                 progname);
526                 exit_nicely(1);
527         }
528
529         /* --column-inserts implies --inserts */
530         if (column_inserts)
531                 dump_inserts = 1;
532
533         if (dataOnly && schemaOnly)
534                 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
535
536         if ((dataOnly || schemaOnly) && dumpSections != DUMP_UNSECTIONED)
537                 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used with --section\n");
538
539         if (dataOnly)
540                 dumpSections = DUMP_DATA;
541         else if (schemaOnly)
542                 dumpSections = DUMP_PRE_DATA | DUMP_POST_DATA;
543         else if ( dumpSections != DUMP_UNSECTIONED)
544         {
545                 dataOnly = dumpSections == DUMP_DATA;
546                 schemaOnly = !(dumpSections & DUMP_DATA);
547         }
548
549         if (dataOnly && outputClean)
550                 exit_horribly(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
551
552         if (dump_inserts && oids)
553         {
554                 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
555                 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
556                 exit_nicely(1);
557         }
558
559         /* Identify archive format to emit */
560         archiveFormat = parseArchiveFormat(format, &archiveMode);
561
562         /* archiveFormat specific setup */
563         if (archiveFormat == archNull)
564                 plainText = 1;
565
566         /* Custom and directory formats are compressed by default, others not */
567         if (compressLevel == -1)
568         {
569                 if (archiveFormat == archCustom || archiveFormat == archDirectory)
570                         compressLevel = Z_DEFAULT_COMPRESSION;
571                 else
572                         compressLevel = 0;
573         }
574
575         /* Open the output file */
576         fout = CreateArchive(filename, archiveFormat, compressLevel, archiveMode);
577
578         /* Register the cleanup hook */
579         on_exit_close_archive(fout);
580
581         if (fout == NULL)
582                 exit_horribly(NULL, "could not open output file \"%s\" for writing\n", filename);
583
584         /* Let the archiver know how noisy to be */
585         fout->verbose = g_verbose;
586
587         my_version = parse_version(PG_VERSION);
588         if (my_version < 0)
589                 exit_horribly(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
590
591         /*
592          * We allow the server to be back to 7.0, and up to any minor release of
593          * our own major version.  (See also version check in pg_dumpall.c.)
594          */
595         fout->minRemoteVersion = 70000;
596         fout->maxRemoteVersion = (my_version / 100) * 100 + 99;
597
598         /*
599          * Open the database using the Archiver, so it knows about it. Errors mean
600          * death.
601          */
602         ConnectDatabase(fout, dbname, pghost, pgport, username, prompt_password);
603         setup_connection(fout, dumpencoding, use_role);
604
605         /*
606          * Disable security label support if server version < v9.1.x (prevents
607          * access to nonexistent pg_seclabel catalog)
608          */
609         if (fout->remoteVersion < 90100)
610                 no_security_labels = 1;
611
612         /*
613          * Start transaction-snapshot mode transaction to dump consistent data.
614          */
615         ExecuteSqlStatement(fout, "BEGIN");
616         if (fout->remoteVersion >= 90100)
617         {
618                 if (serializable_deferrable)
619                         ExecuteSqlStatement(fout,
620                                                                 "SET TRANSACTION ISOLATION LEVEL "
621                                                                 "SERIALIZABLE, READ ONLY, DEFERRABLE");
622                 else
623                         ExecuteSqlStatement(fout,
624                                                                 "SET TRANSACTION ISOLATION LEVEL "
625                                                                 "REPEATABLE READ");
626         }
627         else
628                 ExecuteSqlStatement(fout,
629                                                         "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
630
631         /* Select the appropriate subquery to convert user IDs to names */
632         if (fout->remoteVersion >= 80100)
633                 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
634         else if (fout->remoteVersion >= 70300)
635                 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
636         else
637                 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
638
639         /* Find the last built-in OID, if needed */
640         if (fout->remoteVersion < 70300)
641         {
642                 if (fout->remoteVersion >= 70100)
643                         g_last_builtin_oid = findLastBuiltinOid_V71(fout,
644                                 PQdb(GetConnection(fout)));
645                 else
646                         g_last_builtin_oid = findLastBuiltinOid_V70(fout);
647                 if (g_verbose)
648                         write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
649         }
650
651         /* Expand schema selection patterns into OID lists */
652         if (schema_include_patterns.head != NULL)
653         {
654                 expand_schema_name_patterns(fout, &schema_include_patterns,
655                                                                         &schema_include_oids);
656                 if (schema_include_oids.head == NULL)
657                         exit_horribly(NULL, "No matching schemas were found\n");
658         }
659         expand_schema_name_patterns(fout, &schema_exclude_patterns,
660                                                                 &schema_exclude_oids);
661         /* non-matching exclusion patterns aren't an error */
662
663         /* Expand table selection patterns into OID lists */
664         if (table_include_patterns.head != NULL)
665         {
666                 expand_table_name_patterns(fout, &table_include_patterns,
667                                                                    &table_include_oids);
668                 if (table_include_oids.head == NULL)
669                         exit_horribly(NULL, "No matching tables were found\n");
670         }
671         expand_table_name_patterns(fout, &table_exclude_patterns,
672                                                            &table_exclude_oids);
673
674         expand_table_name_patterns(fout, &tabledata_exclude_patterns,
675                                                            &tabledata_exclude_oids);
676
677         /* non-matching exclusion patterns aren't an error */
678
679         /*
680          * Dumping blobs is now default unless we saw an inclusion switch or -s
681          * ... but even if we did see one of these, -b turns it back on.
682          */
683         if (include_everything && !schemaOnly)
684                 outputBlobs = true;
685
686         /*
687          * Now scan the database and create DumpableObject structs for all the
688          * objects we intend to dump.
689          */
690         tblinfo = getSchemaData(fout, &numTables);
691
692         if (fout->remoteVersion < 80400)
693                 guessConstraintInheritance(tblinfo, numTables);
694
695         if (!schemaOnly)
696         {
697                 getTableData(tblinfo, numTables, oids);
698                 if (dataOnly)
699                         getTableDataFKConstraints();
700         }
701
702         if (outputBlobs)
703                 getBlobs(fout);
704
705         /*
706          * Collect dependency data to assist in ordering the objects.
707          */
708         getDependencies(fout);
709
710         /*
711          * Sort the objects into a safe dump order (no forward references).
712          *
713          * In 7.3 or later, we can rely on dependency information to help us
714          * determine a safe order, so the initial sort is mostly for cosmetic
715          * purposes: we sort by name to ensure that logically identical schemas
716          * will dump identically.  Before 7.3 we don't have dependencies and we
717          * use OID ordering as an (unreliable) guide to creation order.
718          */
719         getDumpableObjects(&dobjs, &numObjs);
720
721         if (fout->remoteVersion >= 70300)
722                 sortDumpableObjectsByTypeName(dobjs, numObjs);
723         else
724                 sortDumpableObjectsByTypeOid(dobjs, numObjs);
725
726         sortDumpableObjects(dobjs, numObjs);
727
728         /*
729          * Create archive TOC entries for all the objects to be dumped, in a safe
730          * order.
731          */
732
733         /* First the special ENCODING and STDSTRINGS entries. */
734         dumpEncoding(fout);
735         dumpStdStrings(fout);
736
737         /* The database item is always next, unless we don't want it at all */
738         if (include_everything && !dataOnly)
739                 dumpDatabase(fout);
740
741         /* Now the rearrangeable objects. */
742         for (i = 0; i < numObjs; i++)
743                 dumpDumpableObject(fout, dobjs[i]);
744
745         /*
746          * And finally we can do the actual output.
747          */
748         if (plainText)
749         {
750                 ropt = NewRestoreOptions();
751                 ropt->filename = filename;
752                 ropt->dropSchema = outputClean;
753                 ropt->aclsSkip = aclsSkip;
754                 ropt->superuser = outputSuperuser;
755                 ropt->createDB = outputCreateDB;
756                 ropt->noOwner = outputNoOwner;
757                 ropt->noTablespace = outputNoTablespaces;
758                 ropt->disable_triggers = disable_triggers;
759                 ropt->use_setsessauth = use_setsessauth;
760                 ropt->dataOnly = dataOnly;
761
762                 if (compressLevel == -1)
763                         ropt->compression = 0;
764                 else
765                         ropt->compression = compressLevel;
766
767                 ropt->suppressDumpWarnings = true;              /* We've already shown them */
768
769                 RestoreArchive(fout, ropt);
770         }
771
772         CloseArchive(fout);
773
774         exit_nicely(0);
775 }
776
777
778 static void
779 help(const char *progname)
780 {
781         printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
782         printf(_("Usage:\n"));
783         printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
784
785         printf(_("\nGeneral options:\n"));
786         printf(_("  -f, --file=FILENAME         output file or directory name\n"));
787         printf(_("  -F, --format=c|d|t|p        output file format (custom, directory, tar,\n"
788                          "                              plain text (default))\n"));
789         printf(_("  -v, --verbose               verbose mode\n"));
790         printf(_("  -Z, --compress=0-9          compression level for compressed formats\n"));
791         printf(_("  --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
792         printf(_("  --help                      show this help, then exit\n"));
793         printf(_("  --version                   output version information, then exit\n"));
794
795         printf(_("\nOptions controlling the output content:\n"));
796         printf(_("  -a, --data-only             dump only the data, not the schema\n"));
797         printf(_("  -b, --blobs                 include large objects in dump\n"));
798         printf(_("  -c, --clean                 clean (drop) database objects before recreating\n"));
799         printf(_("  -C, --create                include commands to create database in dump\n"));
800         printf(_("  -E, --encoding=ENCODING     dump the data in encoding ENCODING\n"));
801         printf(_("  -n, --schema=SCHEMA         dump the named schema(s) only\n"));
802         printf(_("  -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
803         printf(_("  -o, --oids                  include OIDs in dump\n"));
804         printf(_("  -O, --no-owner              skip restoration of object ownership in\n"
805                          "                              plain-text format\n"));
806         printf(_("  -s, --schema-only           dump only the schema, no data\n"));
807         printf(_("  -S, --superuser=NAME        superuser user name to use in plain-text format\n"));
808         printf(_("  -t, --table=TABLE           dump the named table(s) only\n"));
809         printf(_("  -T, --exclude-table=TABLE   do NOT dump the named table(s)\n"));
810         printf(_("  -x, --no-privileges         do not dump privileges (grant/revoke)\n"));
811         printf(_("  --binary-upgrade            for use by upgrade utilities only\n"));
812         printf(_("  --column-inserts            dump data as INSERT commands with column names\n"));
813         printf(_("  --disable-dollar-quoting    disable dollar quoting, use SQL standard quoting\n"));
814         printf(_("  --disable-triggers          disable triggers during data-only restore\n"));
815         printf(_("  --exclude-table-data=TABLE  do NOT dump data for the named table(s)\n"));
816         printf(_("  --inserts                   dump data as INSERT commands, rather than COPY\n"));
817         printf(_("  --no-security-labels        do not dump security label assignments\n"));
818         printf(_("  --no-tablespaces            do not dump tablespace assignments\n"));
819         printf(_("  --no-unlogged-table-data    do not dump unlogged table data\n"));
820         printf(_("  --quote-all-identifiers     quote all identifiers, even if not key words\n"));
821         printf(_("  --section=SECTION           dump named section (pre-data, data, or post-data)\n"));
822         printf(_("  --serializable-deferrable   wait until the dump can run without anomalies\n"));
823         printf(_("  --use-set-session-authorization\n"
824                          "                              use SET SESSION AUTHORIZATION commands instead of\n"
825         "                              ALTER OWNER commands to set ownership\n"));
826
827         printf(_("\nConnection options:\n"));
828         printf(_("  -h, --host=HOSTNAME      database server host or socket directory\n"));
829         printf(_("  -p, --port=PORT          database server port number\n"));
830         printf(_("  -U, --username=NAME      connect as specified database user\n"));
831         printf(_("  -w, --no-password        never prompt for password\n"));
832         printf(_("  -W, --password           force password prompt (should happen automatically)\n"));
833         printf(_("  --role=ROLENAME          do SET ROLE before dump\n"));
834
835         printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
836                          "variable value is used.\n\n"));
837         printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
838 }
839
840 static void
841 setup_connection(Archive *AH, const char *dumpencoding, char *use_role)
842 {
843         PGconn     *conn = GetConnection(AH);
844         const char *std_strings;
845
846         /* Set the client encoding if requested */
847         if (dumpencoding)
848         {
849                 if (PQsetClientEncoding(conn, dumpencoding) < 0)
850                         exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
851                                                   dumpencoding);
852         }
853
854         /*
855          * Get the active encoding and the standard_conforming_strings setting, so
856          * we know how to escape strings.
857          */
858         AH->encoding = PQclientEncoding(conn);
859
860         std_strings = PQparameterStatus(conn, "standard_conforming_strings");
861         AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
862
863         /* Set the role if requested */
864         if (use_role && AH->remoteVersion >= 80100)
865         {
866                 PQExpBuffer query = createPQExpBuffer();
867
868                 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
869                 ExecuteSqlStatement(AH, query->data);
870                 destroyPQExpBuffer(query);
871         }
872
873         /* Set the datestyle to ISO to ensure the dump's portability */
874         ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
875
876         /* Likewise, avoid using sql_standard intervalstyle */
877         if (AH->remoteVersion >= 80400)
878                 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
879
880         /*
881          * If supported, set extra_float_digits so that we can dump float data
882          * exactly (given correctly implemented float I/O code, anyway)
883          */
884         if (AH->remoteVersion >= 90000)
885                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
886         else if (AH->remoteVersion >= 70400)
887                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
888
889         /*
890          * If synchronized scanning is supported, disable it, to prevent
891          * unpredictable changes in row ordering across a dump and reload.
892          */
893         if (AH->remoteVersion >= 80300)
894                 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
895
896         /*
897          * Disable timeouts if supported.
898          */
899         if (AH->remoteVersion >= 70300)
900                 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
901
902         /*
903          * Quote all identifiers, if requested.
904          */
905         if (quote_all_identifiers && AH->remoteVersion >= 90100)
906                 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
907 }
908
909 static ArchiveFormat
910 parseArchiveFormat(const char *format, ArchiveMode *mode)
911 {
912         ArchiveFormat archiveFormat;
913
914         *mode = archModeWrite;
915
916         if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
917         {
918                 /* This is used by pg_dumpall, and is not documented */
919                 archiveFormat = archNull;
920                 *mode = archModeAppend;
921         }
922         else if (pg_strcasecmp(format, "c") == 0)
923                 archiveFormat = archCustom;
924         else if (pg_strcasecmp(format, "custom") == 0)
925                 archiveFormat = archCustom;
926         else if (pg_strcasecmp(format, "d") == 0)
927                 archiveFormat = archDirectory;
928         else if (pg_strcasecmp(format, "directory") == 0)
929                 archiveFormat = archDirectory;
930         else if (pg_strcasecmp(format, "p") == 0)
931                 archiveFormat = archNull;
932         else if (pg_strcasecmp(format, "plain") == 0)
933                 archiveFormat = archNull;
934         else if (pg_strcasecmp(format, "t") == 0)
935                 archiveFormat = archTar;
936         else if (pg_strcasecmp(format, "tar") == 0)
937                 archiveFormat = archTar;
938         else
939                 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
940         return archiveFormat;
941 }
942
943 /*
944  * Find the OIDs of all schemas matching the given list of patterns,
945  * and append them to the given OID list.
946  */
947 static void
948 expand_schema_name_patterns(Archive *fout,
949                                                         SimpleStringList *patterns,
950                                                         SimpleOidList *oids)
951 {
952         PQExpBuffer query;
953         PGresult   *res;
954         SimpleStringListCell *cell;
955         int                     i;
956
957         if (patterns->head == NULL)
958                 return;                                 /* nothing to do */
959
960         if (fout->remoteVersion < 70300)
961                 exit_horribly(NULL, "server version must be at least 7.3 to use schema selection switches\n");
962
963         query = createPQExpBuffer();
964
965         /*
966          * We use UNION ALL rather than UNION; this might sometimes result in
967          * duplicate entries in the OID list, but we don't care.
968          */
969
970         for (cell = patterns->head; cell; cell = cell->next)
971         {
972                 if (cell != patterns->head)
973                         appendPQExpBuffer(query, "UNION ALL\n");
974                 appendPQExpBuffer(query,
975                                                   "SELECT oid FROM pg_catalog.pg_namespace n\n");
976                 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
977                                                           false, NULL, "n.nspname", NULL, NULL);
978         }
979
980         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
981
982         for (i = 0; i < PQntuples(res); i++)
983         {
984                 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
985         }
986
987         PQclear(res);
988         destroyPQExpBuffer(query);
989 }
990
991 /*
992  * Find the OIDs of all tables matching the given list of patterns,
993  * and append them to the given OID list.
994  */
995 static void
996 expand_table_name_patterns(Archive *fout,
997                                                    SimpleStringList *patterns, 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         query = createPQExpBuffer();
1008
1009         /*
1010          * We use UNION ALL rather than UNION; this might sometimes result in
1011          * duplicate entries in the OID list, but we don't care.
1012          */
1013
1014         for (cell = patterns->head; cell; cell = cell->next)
1015         {
1016                 if (cell != patterns->head)
1017                         appendPQExpBuffer(query, "UNION ALL\n");
1018                 appendPQExpBuffer(query,
1019                                                   "SELECT c.oid"
1020                                                   "\nFROM pg_catalog.pg_class c"
1021                 "\n     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1022                                                   "\nWHERE c.relkind in ('%c', '%c', '%c', '%c')\n",
1023                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1024                                                   RELKIND_FOREIGN_TABLE);
1025                 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1026                                                           false, "n.nspname", "c.relname", NULL,
1027                                                           "pg_catalog.pg_table_is_visible(c.oid)");
1028         }
1029
1030         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1031
1032         for (i = 0; i < PQntuples(res); i++)
1033         {
1034                 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1035         }
1036
1037         PQclear(res);
1038         destroyPQExpBuffer(query);
1039 }
1040
1041 /*
1042  * selectDumpableNamespace: policy-setting subroutine
1043  *              Mark a namespace as to be dumped or not
1044  */
1045 static void
1046 selectDumpableNamespace(NamespaceInfo *nsinfo)
1047 {
1048         /*
1049          * If specific tables are being dumped, do not dump any complete
1050          * namespaces. If specific namespaces are being dumped, dump just those
1051          * namespaces. Otherwise, dump all non-system namespaces.
1052          */
1053         if (table_include_oids.head != NULL)
1054                 nsinfo->dobj.dump = false;
1055         else if (schema_include_oids.head != NULL)
1056                 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
1057                                                                                                    nsinfo->dobj.catId.oid);
1058         else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1059                          strcmp(nsinfo->dobj.name, "information_schema") == 0)
1060                 nsinfo->dobj.dump = false;
1061         else
1062                 nsinfo->dobj.dump = true;
1063
1064         /*
1065          * In any case, a namespace can be excluded by an exclusion switch
1066          */
1067         if (nsinfo->dobj.dump &&
1068                 simple_oid_list_member(&schema_exclude_oids,
1069                                                            nsinfo->dobj.catId.oid))
1070                 nsinfo->dobj.dump = false;
1071 }
1072
1073 /*
1074  * selectDumpableTable: policy-setting subroutine
1075  *              Mark a table as to be dumped or not
1076  */
1077 static void
1078 selectDumpableTable(TableInfo *tbinfo)
1079 {
1080         /*
1081          * If specific tables are being dumped, dump just those tables; else, dump
1082          * according to the parent namespace's dump flag.
1083          */
1084         if (table_include_oids.head != NULL)
1085                 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1086                                                                                                    tbinfo->dobj.catId.oid);
1087         else
1088                 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1089
1090         /*
1091          * In any case, a table can be excluded by an exclusion switch
1092          */
1093         if (tbinfo->dobj.dump &&
1094                 simple_oid_list_member(&table_exclude_oids,
1095                                                            tbinfo->dobj.catId.oid))
1096                 tbinfo->dobj.dump = false;
1097 }
1098
1099 /*
1100  * selectDumpableType: policy-setting subroutine
1101  *              Mark a type as to be dumped or not
1102  *
1103  * If it's a table's rowtype or an autogenerated array type, we also apply a
1104  * special type code to facilitate sorting into the desired order.      (We don't
1105  * want to consider those to be ordinary types because that would bring tables
1106  * up into the datatype part of the dump order.)  We still set the object's
1107  * dump flag; that's not going to cause the dummy type to be dumped, but we
1108  * need it so that casts involving such types will be dumped correctly -- see
1109  * dumpCast.  This means the flag should be set the same as for the underlying
1110  * object (the table or base type).
1111  */
1112 static void
1113 selectDumpableType(TypeInfo *tyinfo)
1114 {
1115         /* skip complex types, except for standalone composite types */
1116         if (OidIsValid(tyinfo->typrelid) &&
1117                 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1118         {
1119                 TableInfo  *tytable = findTableByOid(tyinfo->typrelid);
1120
1121                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1122                 if (tytable != NULL)
1123                         tyinfo->dobj.dump = tytable->dobj.dump;
1124                 else
1125                         tyinfo->dobj.dump = false;
1126                 return;
1127         }
1128
1129         /* skip auto-generated array types */
1130         if (tyinfo->isArray)
1131         {
1132                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1133                 /*
1134                  * Fall through to set the dump flag; we assume that the subsequent
1135                  * rules will do the same thing as they would for the array's base
1136                  * type.  (We cannot reliably look up the base type here, since
1137                  * getTypes may not have processed it yet.)
1138                  */
1139         }
1140
1141         /* dump only types in dumpable namespaces */
1142         if (!tyinfo->dobj.namespace->dobj.dump)
1143                 tyinfo->dobj.dump = false;
1144
1145         /* skip undefined placeholder types */
1146         else if (!tyinfo->isDefined)
1147                 tyinfo->dobj.dump = false;
1148
1149         else
1150                 tyinfo->dobj.dump = true;
1151 }
1152
1153 /*
1154  * selectDumpableDefaultACL: policy-setting subroutine
1155  *              Mark a default ACL as to be dumped or not
1156  *
1157  * For per-schema default ACLs, dump if the schema is to be dumped.
1158  * Otherwise dump if we are dumping "everything".  Note that dataOnly
1159  * and aclsSkip are checked separately.
1160  */
1161 static void
1162 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1163 {
1164         if (dinfo->dobj.namespace)
1165                 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1166         else
1167                 dinfo->dobj.dump = include_everything;
1168 }
1169
1170 /*
1171  * selectDumpableExtension: policy-setting subroutine
1172  *              Mark an extension as to be dumped or not
1173  *
1174  * Normally, we dump all extensions, or none of them if include_everything
1175  * is false (i.e., a --schema or --table switch was given).  However, in
1176  * binary-upgrade mode it's necessary to skip built-in extensions, since we
1177  * assume those will already be installed in the target database.  We identify
1178  * such extensions by their having OIDs in the range reserved for initdb.
1179  */
1180 static void
1181 selectDumpableExtension(ExtensionInfo *extinfo)
1182 {
1183         if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1184                 extinfo->dobj.dump = false;
1185         else
1186                 extinfo->dobj.dump = include_everything;
1187 }
1188
1189 /*
1190  * selectDumpableObject: policy-setting subroutine
1191  *              Mark a generic dumpable object as to be dumped or not
1192  *
1193  * Use this only for object types without a special-case routine above.
1194  */
1195 static void
1196 selectDumpableObject(DumpableObject *dobj)
1197 {
1198         /*
1199          * Default policy is to dump if parent namespace is dumpable, or always
1200          * for non-namespace-associated items.
1201          */
1202         if (dobj->namespace)
1203                 dobj->dump = dobj->namespace->dobj.dump;
1204         else
1205                 dobj->dump = true;
1206 }
1207
1208 /*
1209  *      Dump a table's contents for loading using the COPY command
1210  *      - this routine is called by the Archiver when it wants the table
1211  *        to be dumped.
1212  */
1213
1214 static int
1215 dumpTableData_copy(Archive *fout, void *dcontext)
1216 {
1217         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1218         TableInfo  *tbinfo = tdinfo->tdtable;
1219         const char *classname = tbinfo->dobj.name;
1220         const bool      hasoids = tbinfo->hasoids;
1221         const bool      oids = tdinfo->oids;
1222         PQExpBuffer q = createPQExpBuffer();
1223         PGconn     *conn = GetConnection(fout);
1224         PGresult   *res;
1225         int                     ret;
1226         char       *copybuf;
1227         const char *column_list;
1228
1229         if (g_verbose)
1230                 write_msg(NULL, "dumping contents of table %s\n", classname);
1231
1232         /*
1233          * Make sure we are in proper schema.  We will qualify the table name
1234          * below anyway (in case its name conflicts with a pg_catalog table); but
1235          * this ensures reproducible results in case the table contains regproc,
1236          * regclass, etc columns.
1237          */
1238         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1239
1240         /*
1241          * If possible, specify the column list explicitly so that we have no
1242          * possibility of retrieving data in the wrong column order.  (The default
1243          * column ordering of COPY will not be what we want in certain corner
1244          * cases involving ADD COLUMN and inheritance.)
1245          */
1246         if (fout->remoteVersion >= 70300)
1247                 column_list = fmtCopyColumnList(tbinfo);
1248         else
1249                 column_list = "";               /* can't select columns in COPY */
1250
1251         if (oids && hasoids)
1252         {
1253                 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1254                                                   fmtQualifiedId(fout,
1255                                                                                  tbinfo->dobj.namespace->dobj.name,
1256                                                                                  classname),
1257                                                   column_list);
1258         }
1259         else if (tdinfo->filtercond)
1260         {
1261                 /* Note: this syntax is only supported in 8.2 and up */
1262                 appendPQExpBufferStr(q, "COPY (SELECT ");
1263                 /* klugery to get rid of parens in column list */
1264                 if (strlen(column_list) > 2)
1265                 {
1266                         appendPQExpBufferStr(q, column_list + 1);
1267                         q->data[q->len - 1] = ' ';
1268                 }
1269                 else
1270                         appendPQExpBufferStr(q, "* ");
1271                 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1272                                                   fmtQualifiedId(fout,
1273                                                                                  tbinfo->dobj.namespace->dobj.name,
1274                                                                                  classname),
1275                                                   tdinfo->filtercond);
1276         }
1277         else
1278         {
1279                 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1280                                                   fmtQualifiedId(fout,
1281                                                                                  tbinfo->dobj.namespace->dobj.name,
1282                                                                                  classname),
1283                                                   column_list);
1284         }
1285         res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1286         PQclear(res);
1287
1288         for (;;)
1289         {
1290                 ret = PQgetCopyData(conn, &copybuf, 0);
1291
1292                 if (ret < 0)
1293                         break;                          /* done or error */
1294
1295                 if (copybuf)
1296                 {
1297                         WriteData(fout, copybuf, ret);
1298                         PQfreemem(copybuf);
1299                 }
1300
1301                 /* ----------
1302                  * THROTTLE:
1303                  *
1304                  * There was considerable discussion in late July, 2000 regarding
1305                  * slowing down pg_dump when backing up large tables. Users with both
1306                  * slow & fast (multi-processor) machines experienced performance
1307                  * degradation when doing a backup.
1308                  *
1309                  * Initial attempts based on sleeping for a number of ms for each ms
1310                  * of work were deemed too complex, then a simple 'sleep in each loop'
1311                  * implementation was suggested. The latter failed because the loop
1312                  * was too tight. Finally, the following was implemented:
1313                  *
1314                  * If throttle is non-zero, then
1315                  *              See how long since the last sleep.
1316                  *              Work out how long to sleep (based on ratio).
1317                  *              If sleep is more than 100ms, then
1318                  *                      sleep
1319                  *                      reset timer
1320                  *              EndIf
1321                  * EndIf
1322                  *
1323                  * where the throttle value was the number of ms to sleep per ms of
1324                  * work. The calculation was done in each loop.
1325                  *
1326                  * Most of the hard work is done in the backend, and this solution
1327                  * still did not work particularly well: on slow machines, the ratio
1328                  * was 50:1, and on medium paced machines, 1:1, and on fast
1329                  * multi-processor machines, it had little or no effect, for reasons
1330                  * that were unclear.
1331                  *
1332                  * Further discussion ensued, and the proposal was dropped.
1333                  *
1334                  * For those people who want this feature, it can be implemented using
1335                  * gettimeofday in each loop, calculating the time since last sleep,
1336                  * multiplying that by the sleep ratio, then if the result is more
1337                  * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1338                  * function to sleep for a subsecond period ie.
1339                  *
1340                  * select(0, NULL, NULL, NULL, &tvi);
1341                  *
1342                  * This will return after the interval specified in the structure tvi.
1343                  * Finally, call gettimeofday again to save the 'last sleep time'.
1344                  * ----------
1345                  */
1346         }
1347         archprintf(fout, "\\.\n\n\n");
1348
1349         if (ret == -2)
1350         {
1351                 /* copy data transfer failed */
1352                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1353                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1354                 write_msg(NULL, "The command was: %s\n", q->data);
1355                 exit_nicely(1);
1356         }
1357
1358         /* Check command status and return to normal libpq state */
1359         res = PQgetResult(conn);
1360         if (PQresultStatus(res) != PGRES_COMMAND_OK)
1361         {
1362                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1363                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1364                 write_msg(NULL, "The command was: %s\n", q->data);
1365                 exit_nicely(1);
1366         }
1367         PQclear(res);
1368
1369         destroyPQExpBuffer(q);
1370         return 1;
1371 }
1372
1373 /*
1374  * Dump table data using INSERT commands.
1375  *
1376  * Caution: when we restore from an archive file direct to database, the
1377  * INSERT commands emitted by this function have to be parsed by
1378  * pg_backup_db.c's ExecuteInsertCommands(), which will not handle comments,
1379  * E'' strings, or dollar-quoted strings.  So don't emit anything like that.
1380  */
1381 static int
1382 dumpTableData_insert(Archive *fout, void *dcontext)
1383 {
1384         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1385         TableInfo  *tbinfo = tdinfo->tdtable;
1386         const char *classname = tbinfo->dobj.name;
1387         PQExpBuffer q = createPQExpBuffer();
1388         PGresult   *res;
1389         int                     tuple;
1390         int                     nfields;
1391         int                     field;
1392
1393         /*
1394          * Make sure we are in proper schema.  We will qualify the table name
1395          * below anyway (in case its name conflicts with a pg_catalog table); but
1396          * this ensures reproducible results in case the table contains regproc,
1397          * regclass, etc columns.
1398          */
1399         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1400
1401         if (fout->remoteVersion >= 70100)
1402         {
1403                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1404                                                   "SELECT * FROM ONLY %s",
1405                                                   fmtQualifiedId(fout,
1406                                                                                  tbinfo->dobj.namespace->dobj.name,
1407                                                                                  classname));
1408         }
1409         else
1410         {
1411                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1412                                                   "SELECT * FROM %s",
1413                                                   fmtQualifiedId(fout,
1414                                                                                  tbinfo->dobj.namespace->dobj.name,
1415                                                                                  classname));
1416         }
1417         if (tdinfo->filtercond)
1418                 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1419
1420         ExecuteSqlStatement(fout, q->data);
1421
1422         while (1)
1423         {
1424                 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1425                                                           PGRES_TUPLES_OK);
1426                 nfields = PQnfields(res);
1427                 for (tuple = 0; tuple < PQntuples(res); tuple++)
1428                 {
1429                         archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1430                         if (nfields == 0)
1431                         {
1432                                 /* corner case for zero-column table */
1433                                 archprintf(fout, "DEFAULT VALUES;\n");
1434                                 continue;
1435                         }
1436                         if (column_inserts)
1437                         {
1438                                 resetPQExpBuffer(q);
1439                                 appendPQExpBuffer(q, "(");
1440                                 for (field = 0; field < nfields; field++)
1441                                 {
1442                                         if (field > 0)
1443                                                 appendPQExpBuffer(q, ", ");
1444                                         appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1445                                 }
1446                                 appendPQExpBuffer(q, ") ");
1447                                 archputs(q->data, fout);
1448                         }
1449                         archprintf(fout, "VALUES (");
1450                         for (field = 0; field < nfields; field++)
1451                         {
1452                                 if (field > 0)
1453                                         archprintf(fout, ", ");
1454                                 if (PQgetisnull(res, tuple, field))
1455                                 {
1456                                         archprintf(fout, "NULL");
1457                                         continue;
1458                                 }
1459
1460                                 /* XXX This code is partially duplicated in ruleutils.c */
1461                                 switch (PQftype(res, field))
1462                                 {
1463                                         case INT2OID:
1464                                         case INT4OID:
1465                                         case INT8OID:
1466                                         case OIDOID:
1467                                         case FLOAT4OID:
1468                                         case FLOAT8OID:
1469                                         case NUMERICOID:
1470                                                 {
1471                                                         /*
1472                                                          * These types are printed without quotes unless
1473                                                          * they contain values that aren't accepted by the
1474                                                          * scanner unquoted (e.g., 'NaN').      Note that
1475                                                          * strtod() and friends might accept NaN, so we
1476                                                          * can't use that to test.
1477                                                          *
1478                                                          * In reality we only need to defend against
1479                                                          * infinity and NaN, so we need not get too crazy
1480                                                          * about pattern matching here.
1481                                                          */
1482                                                         const char *s = PQgetvalue(res, tuple, field);
1483
1484                                                         if (strspn(s, "0123456789 +-eE.") == strlen(s))
1485                                                                 archprintf(fout, "%s", s);
1486                                                         else
1487                                                                 archprintf(fout, "'%s'", s);
1488                                                 }
1489                                                 break;
1490
1491                                         case BITOID:
1492                                         case VARBITOID:
1493                                                 archprintf(fout, "B'%s'",
1494                                                                    PQgetvalue(res, tuple, field));
1495                                                 break;
1496
1497                                         case BOOLOID:
1498                                                 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1499                                                         archprintf(fout, "true");
1500                                                 else
1501                                                         archprintf(fout, "false");
1502                                                 break;
1503
1504                                         default:
1505                                                 /* All other types are printed as string literals. */
1506                                                 resetPQExpBuffer(q);
1507                                                 appendStringLiteralAH(q,
1508                                                                                           PQgetvalue(res, tuple, field),
1509                                                                                           fout);
1510                                                 archputs(q->data, fout);
1511                                                 break;
1512                                 }
1513                         }
1514                         archprintf(fout, ");\n");
1515                 }
1516
1517                 if (PQntuples(res) <= 0)
1518                 {
1519                         PQclear(res);
1520                         break;
1521                 }
1522                 PQclear(res);
1523         }
1524
1525         archprintf(fout, "\n\n");
1526
1527         ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
1528
1529         destroyPQExpBuffer(q);
1530         return 1;
1531 }
1532
1533
1534 /*
1535  * dumpTableData -
1536  *        dump the contents of a single table
1537  *
1538  * Actually, this just makes an ArchiveEntry for the table contents.
1539  */
1540 static void
1541 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1542 {
1543         TableInfo  *tbinfo = tdinfo->tdtable;
1544         PQExpBuffer copyBuf = createPQExpBuffer();
1545         DataDumperPtr dumpFn;
1546         char       *copyStmt;
1547
1548         if (!dump_inserts)
1549         {
1550                 /* Dump/restore using COPY */
1551                 dumpFn = dumpTableData_copy;
1552                 /* must use 2 steps here 'cause fmtId is nonreentrant */
1553                 appendPQExpBuffer(copyBuf, "COPY %s ",
1554                                                   fmtId(tbinfo->dobj.name));
1555                 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1556                                                   fmtCopyColumnList(tbinfo),
1557                                           (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1558                 copyStmt = copyBuf->data;
1559         }
1560         else
1561         {
1562                 /* Restore using INSERT */
1563                 dumpFn = dumpTableData_insert;
1564                 copyStmt = NULL;
1565         }
1566
1567         ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1568                                  tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1569                                  NULL, tbinfo->rolname,
1570                                  false, "TABLE DATA", SECTION_DATA,
1571                                  "", "", copyStmt,
1572                                  tdinfo->dobj.dependencies, tdinfo->dobj.nDeps,
1573                                  dumpFn, tdinfo);
1574
1575         destroyPQExpBuffer(copyBuf);
1576 }
1577
1578 /*
1579  * getTableData -
1580  *        set up dumpable objects representing the contents of tables
1581  */
1582 static void
1583 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1584 {
1585         int                     i;
1586
1587         for (i = 0; i < numTables; i++)
1588         {
1589                 if (tblinfo[i].dobj.dump)
1590                         makeTableDataInfo(&(tblinfo[i]), oids);
1591         }
1592 }
1593
1594 /*
1595  * Make a dumpable object for the data of this specific table
1596  *
1597  * Note: we make a TableDataInfo if and only if we are going to dump the
1598  * table data; the "dump" flag in such objects isn't used.
1599  */
1600 static void
1601 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1602 {
1603         TableDataInfo *tdinfo;
1604
1605         /*
1606          * Nothing to do if we already decided to dump the table.  This will
1607          * happen for "config" tables.
1608          */
1609         if (tbinfo->dataObj != NULL)
1610                 return;
1611
1612         /* Skip VIEWs (no data to dump) */
1613         if (tbinfo->relkind == RELKIND_VIEW)
1614                 return;
1615         /* Skip SEQUENCEs (handled elsewhere) */
1616         if (tbinfo->relkind == RELKIND_SEQUENCE)
1617                 return;
1618         /* Skip FOREIGN TABLEs (no data to dump) */
1619         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
1620                 return;
1621
1622         /* Don't dump data in unlogged tables, if so requested */
1623         if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
1624                 no_unlogged_table_data)
1625                 return;
1626
1627         /* Check that the data is not explicitly excluded */
1628         if (simple_oid_list_member(&tabledata_exclude_oids,
1629                                                            tbinfo->dobj.catId.oid))
1630                 return;
1631
1632         /* OK, let's dump it */
1633         tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
1634
1635         tdinfo->dobj.objType = DO_TABLE_DATA;
1636
1637         /*
1638          * Note: use tableoid 0 so that this object won't be mistaken for
1639          * something that pg_depend entries apply to.
1640          */
1641         tdinfo->dobj.catId.tableoid = 0;
1642         tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
1643         AssignDumpId(&tdinfo->dobj);
1644         tdinfo->dobj.name = tbinfo->dobj.name;
1645         tdinfo->dobj.namespace = tbinfo->dobj.namespace;
1646         tdinfo->tdtable = tbinfo;
1647         tdinfo->oids = oids;
1648         tdinfo->filtercond = NULL;      /* might get set later */
1649         addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
1650
1651         tbinfo->dataObj = tdinfo;
1652 }
1653
1654 /*
1655  * getTableDataFKConstraints -
1656  *        add dump-order dependencies reflecting foreign key constraints
1657  *
1658  * This code is executed only in a data-only dump --- in schema+data dumps
1659  * we handle foreign key issues by not creating the FK constraints until
1660  * after the data is loaded.  In a data-only dump, however, we want to
1661  * order the table data objects in such a way that a table's referenced
1662  * tables are restored first.  (In the presence of circular references or
1663  * self-references this may be impossible; we'll detect and complain about
1664  * that during the dependency sorting step.)
1665  */
1666 static void
1667 getTableDataFKConstraints(void)
1668 {
1669         DumpableObject **dobjs;
1670         int                     numObjs;
1671         int                     i;
1672
1673         /* Search through all the dumpable objects for FK constraints */
1674         getDumpableObjects(&dobjs, &numObjs);
1675         for (i = 0; i < numObjs; i++)
1676         {
1677                 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
1678                 {
1679                         ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
1680                         TableInfo  *ftable;
1681
1682                         /* Not interesting unless both tables are to be dumped */
1683                         if (cinfo->contable == NULL ||
1684                                 cinfo->contable->dataObj == NULL)
1685                                 continue;
1686                         ftable = findTableByOid(cinfo->confrelid);
1687                         if (ftable == NULL ||
1688                                 ftable->dataObj == NULL)
1689                                 continue;
1690
1691                         /*
1692                          * Okay, make referencing table's TABLE_DATA object depend on the
1693                          * referenced table's TABLE_DATA object.
1694                          */
1695                         addObjectDependency(&cinfo->contable->dataObj->dobj,
1696                                                                 ftable->dataObj->dobj.dumpId);
1697                 }
1698         }
1699         free(dobjs);
1700 }
1701
1702
1703 /*
1704  * guessConstraintInheritance:
1705  *      In pre-8.4 databases, we can't tell for certain which constraints
1706  *      are inherited.  We assume a CHECK constraint is inherited if its name
1707  *      matches the name of any constraint in the parent.  Originally this code
1708  *      tried to compare the expression texts, but that can fail for various
1709  *      reasons --- for example, if the parent and child tables are in different
1710  *      schemas, reverse-listing of function calls may produce different text
1711  *      (schema-qualified or not) depending on search path.
1712  *
1713  *      In 8.4 and up we can rely on the conislocal field to decide which
1714  *      constraints must be dumped; much safer.
1715  *
1716  *      This function assumes all conislocal flags were initialized to TRUE.
1717  *      It clears the flag on anything that seems to be inherited.
1718  */
1719 static void
1720 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
1721 {
1722         int                     i,
1723                                 j,
1724                                 k;
1725
1726         for (i = 0; i < numTables; i++)
1727         {
1728                 TableInfo  *tbinfo = &(tblinfo[i]);
1729                 int                     numParents;
1730                 TableInfo **parents;
1731                 TableInfo  *parent;
1732
1733                 /* Sequences and views never have parents */
1734                 if (tbinfo->relkind == RELKIND_SEQUENCE ||
1735                         tbinfo->relkind == RELKIND_VIEW)
1736                         continue;
1737
1738                 /* Don't bother computing anything for non-target tables, either */
1739                 if (!tbinfo->dobj.dump)
1740                         continue;
1741
1742                 numParents = tbinfo->numParents;
1743                 parents = tbinfo->parents;
1744
1745                 if (numParents == 0)
1746                         continue;                       /* nothing to see here, move along */
1747
1748                 /* scan for inherited CHECK constraints */
1749                 for (j = 0; j < tbinfo->ncheck; j++)
1750                 {
1751                         ConstraintInfo *constr;
1752
1753                         constr = &(tbinfo->checkexprs[j]);
1754
1755                         for (k = 0; k < numParents; k++)
1756                         {
1757                                 int                     l;
1758
1759                                 parent = parents[k];
1760                                 for (l = 0; l < parent->ncheck; l++)
1761                                 {
1762                                         ConstraintInfo *pconstr = &(parent->checkexprs[l]);
1763
1764                                         if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
1765                                         {
1766                                                 constr->conislocal = false;
1767                                                 break;
1768                                         }
1769                                 }
1770                                 if (!constr->conislocal)
1771                                         break;
1772                         }
1773                 }
1774         }
1775 }
1776
1777
1778 /*
1779  * dumpDatabase:
1780  *      dump the database definition
1781  */
1782 static void
1783 dumpDatabase(Archive *fout)
1784 {
1785         PQExpBuffer dbQry = createPQExpBuffer();
1786         PQExpBuffer delQry = createPQExpBuffer();
1787         PQExpBuffer creaQry = createPQExpBuffer();
1788         PGconn     *conn = GetConnection(fout);
1789         PGresult   *res;
1790         int                     i_tableoid,
1791                                 i_oid,
1792                                 i_dba,
1793                                 i_encoding,
1794                                 i_collate,
1795                                 i_ctype,
1796                                 i_frozenxid,
1797                                 i_tablespace;
1798         CatalogId       dbCatId;
1799         DumpId          dbDumpId;
1800         const char *datname,
1801                            *dba,
1802                            *encoding,
1803                            *collate,
1804                            *ctype,
1805                            *tablespace;
1806         uint32          frozenxid;
1807
1808         datname = PQdb(conn);
1809
1810         if (g_verbose)
1811                 write_msg(NULL, "saving database definition\n");
1812
1813         /* Make sure we are in proper schema */
1814         selectSourceSchema(fout, "pg_catalog");
1815
1816         /* Get the database owner and parameters from pg_database */
1817         if (fout->remoteVersion >= 80400)
1818         {
1819                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1820                                                   "(%s datdba) AS dba, "
1821                                                   "pg_encoding_to_char(encoding) AS encoding, "
1822                                                   "datcollate, datctype, datfrozenxid, "
1823                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1824                                           "shobj_description(oid, 'pg_database') AS description "
1825
1826                                                   "FROM pg_database "
1827                                                   "WHERE datname = ",
1828                                                   username_subquery);
1829                 appendStringLiteralAH(dbQry, datname, fout);
1830         }
1831         else if (fout->remoteVersion >= 80200)
1832         {
1833                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1834                                                   "(%s datdba) AS dba, "
1835                                                   "pg_encoding_to_char(encoding) AS encoding, "
1836                                            "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1837                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1838                                           "shobj_description(oid, 'pg_database') AS description "
1839
1840                                                   "FROM pg_database "
1841                                                   "WHERE datname = ",
1842                                                   username_subquery);
1843                 appendStringLiteralAH(dbQry, datname, fout);
1844         }
1845         else if (fout->remoteVersion >= 80000)
1846         {
1847                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1848                                                   "(%s datdba) AS dba, "
1849                                                   "pg_encoding_to_char(encoding) AS encoding, "
1850                                            "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1851                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
1852                                                   "FROM pg_database "
1853                                                   "WHERE datname = ",
1854                                                   username_subquery);
1855                 appendStringLiteralAH(dbQry, datname, fout);
1856         }
1857         else if (fout->remoteVersion >= 70100)
1858         {
1859                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1860                                                   "(%s datdba) AS dba, "
1861                                                   "pg_encoding_to_char(encoding) AS encoding, "
1862                                                   "NULL AS datcollate, NULL AS datctype, "
1863                                                   "0 AS datfrozenxid, "
1864                                                   "NULL AS tablespace "
1865                                                   "FROM pg_database "
1866                                                   "WHERE datname = ",
1867                                                   username_subquery);
1868                 appendStringLiteralAH(dbQry, datname, fout);
1869         }
1870         else
1871         {
1872                 appendPQExpBuffer(dbQry, "SELECT "
1873                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1874                                                   "oid, "
1875                                                   "(%s datdba) AS dba, "
1876                                                   "pg_encoding_to_char(encoding) AS encoding, "
1877                                                   "NULL AS datcollate, NULL AS datctype, "
1878                                                   "0 AS datfrozenxid, "
1879                                                   "NULL AS tablespace "
1880                                                   "FROM pg_database "
1881                                                   "WHERE datname = ",
1882                                                   username_subquery);
1883                 appendStringLiteralAH(dbQry, datname, fout);
1884         }
1885
1886         res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
1887
1888         i_tableoid = PQfnumber(res, "tableoid");
1889         i_oid = PQfnumber(res, "oid");
1890         i_dba = PQfnumber(res, "dba");
1891         i_encoding = PQfnumber(res, "encoding");
1892         i_collate = PQfnumber(res, "datcollate");
1893         i_ctype = PQfnumber(res, "datctype");
1894         i_frozenxid = PQfnumber(res, "datfrozenxid");
1895         i_tablespace = PQfnumber(res, "tablespace");
1896
1897         dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1898         dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1899         dba = PQgetvalue(res, 0, i_dba);
1900         encoding = PQgetvalue(res, 0, i_encoding);
1901         collate = PQgetvalue(res, 0, i_collate);
1902         ctype = PQgetvalue(res, 0, i_ctype);
1903         frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
1904         tablespace = PQgetvalue(res, 0, i_tablespace);
1905
1906         appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1907                                           fmtId(datname));
1908         if (strlen(encoding) > 0)
1909         {
1910                 appendPQExpBuffer(creaQry, " ENCODING = ");
1911                 appendStringLiteralAH(creaQry, encoding, fout);
1912         }
1913         if (strlen(collate) > 0)
1914         {
1915                 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
1916                 appendStringLiteralAH(creaQry, collate, fout);
1917         }
1918         if (strlen(ctype) > 0)
1919         {
1920                 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
1921                 appendStringLiteralAH(creaQry, ctype, fout);
1922         }
1923         if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1924                 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1925                                                   fmtId(tablespace));
1926         appendPQExpBuffer(creaQry, ";\n");
1927
1928         if (binary_upgrade)
1929         {
1930                 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
1931                 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
1932                                                   "SET datfrozenxid = '%u'\n"
1933                                                   "WHERE        datname = ",
1934                                                   frozenxid);
1935                 appendStringLiteralAH(creaQry, datname, fout);
1936                 appendPQExpBuffer(creaQry, ";\n");
1937
1938         }
1939
1940         appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1941                                           fmtId(datname));
1942
1943         dbDumpId = createDumpId();
1944
1945         ArchiveEntry(fout,
1946                                  dbCatId,               /* catalog ID */
1947                                  dbDumpId,              /* dump ID */
1948                                  datname,               /* Name */
1949                                  NULL,                  /* Namespace */
1950                                  NULL,                  /* Tablespace */
1951                                  dba,                   /* Owner */
1952                                  false,                 /* with oids */
1953                                  "DATABASE",    /* Desc */
1954                                  SECTION_PRE_DATA,              /* Section */
1955                                  creaQry->data, /* Create */
1956                                  delQry->data,  /* Del */
1957                                  NULL,                  /* Copy */
1958                                  NULL,                  /* Deps */
1959                                  0,                             /* # Deps */
1960                                  NULL,                  /* Dumper */
1961                                  NULL);                 /* Dumper Arg */
1962
1963         /*
1964          * pg_largeobject and pg_largeobject_metadata come from the old system
1965          * intact, so set their relfrozenxids.
1966          */
1967         if (binary_upgrade)
1968         {
1969                 PGresult   *lo_res;
1970                 PQExpBuffer loFrozenQry = createPQExpBuffer();
1971                 PQExpBuffer loOutQry = createPQExpBuffer();
1972                 int                     i_relfrozenxid;
1973
1974                 /*
1975                  * pg_largeobject
1976                  */
1977                 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
1978                                                   "FROM pg_catalog.pg_class\n"
1979                                                   "WHERE oid = %u;\n",
1980                                                   LargeObjectRelationId);
1981
1982                 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
1983
1984                 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
1985
1986                 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject.relfrozenxid\n");
1987                 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
1988                                                   "SET relfrozenxid = '%u'\n"
1989                                                   "WHERE oid = %u;\n",
1990                                                   atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
1991                                                   LargeObjectRelationId);
1992                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
1993                                          "pg_largeobject", NULL, NULL, "",
1994                                          false, "pg_largeobject", SECTION_PRE_DATA,
1995                                          loOutQry->data, "", NULL,
1996                                          NULL, 0,
1997                                          NULL, NULL);
1998
1999                 PQclear(lo_res);
2000
2001                 /*
2002                  * pg_largeobject_metadata
2003                  */
2004                 if (fout->remoteVersion >= 90000)
2005                 {
2006                         resetPQExpBuffer(loFrozenQry);
2007                         resetPQExpBuffer(loOutQry);
2008
2009                         appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2010                                                           "FROM pg_catalog.pg_class\n"
2011                                                           "WHERE oid = %u;\n",
2012                                                           LargeObjectMetadataRelationId);
2013
2014                         lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2015
2016                         i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2017
2018                         appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata.relfrozenxid\n");
2019                         appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2020                                                           "SET relfrozenxid = '%u'\n"
2021                                                           "WHERE oid = %u;\n",
2022                                                           atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2023                                                           LargeObjectMetadataRelationId);
2024                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2025                                                  "pg_largeobject_metadata", NULL, NULL, "",
2026                                                  false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2027                                                  loOutQry->data, "", NULL,
2028                                                  NULL, 0,
2029                                                  NULL, NULL);
2030
2031                         PQclear(lo_res);
2032                 }
2033
2034                 destroyPQExpBuffer(loFrozenQry);
2035                 destroyPQExpBuffer(loOutQry);
2036         }
2037
2038         /* Dump DB comment if any */
2039         if (fout->remoteVersion >= 80200)
2040         {
2041                 /*
2042                  * 8.2 keeps comments on shared objects in a shared table, so we
2043                  * cannot use the dumpComment used for other database objects.
2044                  */
2045                 char       *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2046
2047                 if (comment && strlen(comment))
2048                 {
2049                         resetPQExpBuffer(dbQry);
2050
2051                         /*
2052                          * Generates warning when loaded into a differently-named
2053                          * database.
2054                          */
2055                         appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2056                         appendStringLiteralAH(dbQry, comment, fout);
2057                         appendPQExpBuffer(dbQry, ";\n");
2058
2059                         ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2060                                                  dba, false, "COMMENT", SECTION_NONE,
2061                                                  dbQry->data, "", NULL,
2062                                                  &dbDumpId, 1, NULL, NULL);
2063                 }
2064         }
2065         else
2066         {
2067                 resetPQExpBuffer(dbQry);
2068                 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2069                 dumpComment(fout, dbQry->data, NULL, "",
2070                                         dbCatId, 0, dbDumpId);
2071         }
2072
2073         PQclear(res);
2074
2075         /* Dump shared security label. */
2076         if (!no_security_labels && fout->remoteVersion >= 90200)
2077         {
2078                 PQExpBuffer seclabelQry = createPQExpBuffer();
2079
2080                 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2081                 res = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2082                 resetPQExpBuffer(seclabelQry);
2083                 emitShSecLabels(conn, res, seclabelQry, "DATABASE", datname);
2084                 if (strlen(seclabelQry->data))
2085                         ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2086                                                  dba, false, "SECURITY LABEL", SECTION_NONE,
2087                                                  seclabelQry->data, "", NULL,
2088                                                  &dbDumpId, 1, NULL, NULL);
2089                 destroyPQExpBuffer(seclabelQry);
2090         }
2091
2092         destroyPQExpBuffer(dbQry);
2093         destroyPQExpBuffer(delQry);
2094         destroyPQExpBuffer(creaQry);
2095 }
2096
2097
2098 /*
2099  * dumpEncoding: put the correct encoding into the archive
2100  */
2101 static void
2102 dumpEncoding(Archive *AH)
2103 {
2104         const char *encname = pg_encoding_to_char(AH->encoding);
2105         PQExpBuffer qry = createPQExpBuffer();
2106
2107         if (g_verbose)
2108                 write_msg(NULL, "saving encoding = %s\n", encname);
2109
2110         appendPQExpBuffer(qry, "SET client_encoding = ");
2111         appendStringLiteralAH(qry, encname, AH);
2112         appendPQExpBuffer(qry, ";\n");
2113
2114         ArchiveEntry(AH, nilCatalogId, createDumpId(),
2115                                  "ENCODING", NULL, NULL, "",
2116                                  false, "ENCODING", SECTION_PRE_DATA,
2117                                  qry->data, "", NULL,
2118                                  NULL, 0,
2119                                  NULL, NULL);
2120
2121         destroyPQExpBuffer(qry);
2122 }
2123
2124
2125 /*
2126  * dumpStdStrings: put the correct escape string behavior into the archive
2127  */
2128 static void
2129 dumpStdStrings(Archive *AH)
2130 {
2131         const char *stdstrings = AH->std_strings ? "on" : "off";
2132         PQExpBuffer qry = createPQExpBuffer();
2133
2134         if (g_verbose)
2135                 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2136                                   stdstrings);
2137
2138         appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2139                                           stdstrings);
2140
2141         ArchiveEntry(AH, nilCatalogId, createDumpId(),
2142                                  "STDSTRINGS", NULL, NULL, "",
2143                                  false, "STDSTRINGS", SECTION_PRE_DATA,
2144                                  qry->data, "", NULL,
2145                                  NULL, 0,
2146                                  NULL, NULL);
2147
2148         destroyPQExpBuffer(qry);
2149 }
2150
2151
2152 /*
2153  * getBlobs:
2154  *      Collect schema-level data about large objects
2155  */
2156 static void
2157 getBlobs(Archive *fout)
2158 {
2159         PQExpBuffer blobQry = createPQExpBuffer();
2160         BlobInfo   *binfo;
2161         DumpableObject *bdata;
2162         PGresult   *res;
2163         int                     ntups;
2164         int                     i;
2165
2166         /* Verbose message */
2167         if (g_verbose)
2168                 write_msg(NULL, "reading large objects\n");
2169
2170         /* Make sure we are in proper schema */
2171         selectSourceSchema(fout, "pg_catalog");
2172
2173         /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2174         if (fout->remoteVersion >= 90000)
2175                 appendPQExpBuffer(blobQry,
2176                                                   "SELECT oid, (%s lomowner) AS rolname, lomacl"
2177                                                   " FROM pg_largeobject_metadata",
2178                                                   username_subquery);
2179         else if (fout->remoteVersion >= 70100)
2180                 appendPQExpBuffer(blobQry,
2181                                                   "SELECT DISTINCT loid, NULL::oid, NULL::oid"
2182                                                   " FROM pg_largeobject");
2183         else
2184                 appendPQExpBuffer(blobQry,
2185                                                   "SELECT oid, NULL::oid, NULL::oid"
2186                                                   " FROM pg_class WHERE relkind = 'l'");
2187
2188         res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
2189
2190         ntups = PQntuples(res);
2191         if (ntups > 0)
2192         {
2193                 /*
2194                  * Each large object has its own BLOB archive entry.
2195                  */
2196                 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2197
2198                 for (i = 0; i < ntups; i++)
2199                 {
2200                         binfo[i].dobj.objType = DO_BLOB;
2201                         binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2202                         binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
2203                         AssignDumpId(&binfo[i].dobj);
2204
2205                         binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, 0));
2206                         if (!PQgetisnull(res, i, 1))
2207                                 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, 1));
2208                         else
2209                                 binfo[i].rolname = "";
2210                         if (!PQgetisnull(res, i, 2))
2211                                 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, 2));
2212                         else
2213                                 binfo[i].blobacl = NULL;
2214                 }
2215
2216                 /*
2217                  * If we have any large objects, a "BLOBS" archive entry is needed.
2218                  * This is just a placeholder for sorting; it carries no data now.
2219                  */
2220                 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2221                 bdata->objType = DO_BLOB_DATA;
2222                 bdata->catId = nilCatalogId;
2223                 AssignDumpId(bdata);
2224                 bdata->name = pg_strdup("BLOBS");
2225         }
2226
2227         PQclear(res);
2228         destroyPQExpBuffer(blobQry);
2229 }
2230
2231 /*
2232  * dumpBlob
2233  *
2234  * dump the definition (metadata) of the given large object
2235  */
2236 static void
2237 dumpBlob(Archive *fout, BlobInfo *binfo)
2238 {
2239         PQExpBuffer cquery = createPQExpBuffer();
2240         PQExpBuffer dquery = createPQExpBuffer();
2241
2242         appendPQExpBuffer(cquery,
2243                                           "SELECT pg_catalog.lo_create('%s');\n",
2244                                           binfo->dobj.name);
2245
2246         appendPQExpBuffer(dquery,
2247                                           "SELECT pg_catalog.lo_unlink('%s');\n",
2248                                           binfo->dobj.name);
2249
2250         ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
2251                                  binfo->dobj.name,
2252                                  NULL, NULL,
2253                                  binfo->rolname, false,
2254                                  "BLOB", SECTION_PRE_DATA,
2255                                  cquery->data, dquery->data, NULL,
2256                                  binfo->dobj.dependencies, binfo->dobj.nDeps,
2257                                  NULL, NULL);
2258
2259         /* set up tag for comment and/or ACL */
2260         resetPQExpBuffer(cquery);
2261         appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2262
2263         /* Dump comment if any */
2264         dumpComment(fout, cquery->data,
2265                                 NULL, binfo->rolname,
2266                                 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2267
2268         /* Dump security label if any */
2269         dumpSecLabel(fout, cquery->data,
2270                                  NULL, binfo->rolname,
2271                                  binfo->dobj.catId, 0, binfo->dobj.dumpId);
2272
2273         /* Dump ACL if any */
2274         if (binfo->blobacl)
2275                 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2276                                 binfo->dobj.name, NULL, cquery->data,
2277                                 NULL, binfo->rolname, binfo->blobacl);
2278
2279         destroyPQExpBuffer(cquery);
2280         destroyPQExpBuffer(dquery);
2281 }
2282
2283 /*
2284  * dumpBlobs:
2285  *      dump the data contents of all large objects
2286  */
2287 static int
2288 dumpBlobs(Archive *fout, void *arg)
2289 {
2290         const char *blobQry;
2291         const char *blobFetchQry;
2292         PGconn     *conn = GetConnection(fout);
2293         PGresult   *res;
2294         char            buf[LOBBUFSIZE];
2295         int                     ntups;
2296         int                     i;
2297         int                     cnt;
2298
2299         if (g_verbose)
2300                 write_msg(NULL, "saving large objects\n");
2301
2302         /* Make sure we are in proper schema */
2303         selectSourceSchema(fout, "pg_catalog");
2304
2305         /*
2306          * Currently, we re-fetch all BLOB OIDs using a cursor.  Consider scanning
2307          * the already-in-memory dumpable objects instead...
2308          */
2309         if (fout->remoteVersion >= 90000)
2310                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2311         else if (fout->remoteVersion >= 70100)
2312                 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2313         else
2314                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2315
2316         ExecuteSqlStatement(fout, blobQry);
2317
2318         /* Command to fetch from cursor */
2319         blobFetchQry = "FETCH 1000 IN bloboid";
2320
2321         do
2322         {
2323                 /* Do a fetch */
2324                 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
2325
2326                 /* Process the tuples, if any */
2327                 ntups = PQntuples(res);
2328                 for (i = 0; i < ntups; i++)
2329                 {
2330                         Oid                     blobOid;
2331                         int                     loFd;
2332
2333                         blobOid = atooid(PQgetvalue(res, i, 0));
2334                         /* Open the BLOB */
2335                         loFd = lo_open(conn, blobOid, INV_READ);
2336                         if (loFd == -1)
2337                                 exit_horribly(NULL, "could not open large object %u: %s",
2338                                                           blobOid, PQerrorMessage(conn));
2339
2340                         StartBlob(fout, blobOid);
2341
2342                         /* Now read it in chunks, sending data to archive */
2343                         do
2344                         {
2345                                 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
2346                                 if (cnt < 0)
2347                                         exit_horribly(NULL, "error reading large object %u: %s",
2348                                                                   blobOid, PQerrorMessage(conn));
2349
2350                                 WriteData(fout, buf, cnt);
2351                         } while (cnt > 0);
2352
2353                         lo_close(conn, loFd);
2354
2355                         EndBlob(fout, blobOid);
2356                 }
2357
2358                 PQclear(res);
2359         } while (ntups > 0);
2360
2361         return 1;
2362 }
2363
2364 static void
2365 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
2366                                                                                  PQExpBuffer upgrade_buffer,
2367                                                                                  Oid pg_type_oid)
2368 {
2369         PQExpBuffer upgrade_query = createPQExpBuffer();
2370         PGresult   *upgrade_res;
2371         Oid                     pg_type_array_oid;
2372
2373         appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2374         appendPQExpBuffer(upgrade_buffer,
2375          "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2376                                           pg_type_oid);
2377
2378         /* we only support old >= 8.3 for binary upgrades */
2379         appendPQExpBuffer(upgrade_query,
2380                                           "SELECT typarray "
2381                                           "FROM pg_catalog.pg_type "
2382                                           "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2383                                           pg_type_oid);
2384
2385         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2386
2387         pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2388
2389         if (OidIsValid(pg_type_array_oid))
2390         {
2391                 appendPQExpBuffer(upgrade_buffer,
2392                            "\n-- For binary upgrade, must preserve pg_type array oid\n");
2393                 appendPQExpBuffer(upgrade_buffer,
2394                                                   "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2395                                                   pg_type_array_oid);
2396         }
2397
2398         PQclear(upgrade_res);
2399         destroyPQExpBuffer(upgrade_query);
2400 }
2401
2402 static bool
2403 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
2404                                                                                 PQExpBuffer upgrade_buffer,
2405                                                                                 Oid pg_rel_oid)
2406 {
2407         PQExpBuffer upgrade_query = createPQExpBuffer();
2408         PGresult   *upgrade_res;
2409         Oid                     pg_type_oid;
2410         bool            toast_set = false;
2411
2412         /* we only support old >= 8.3 for binary upgrades */
2413         appendPQExpBuffer(upgrade_query,
2414                                           "SELECT c.reltype AS crel, t.reltype AS trel "
2415                                           "FROM pg_catalog.pg_class c "
2416                                           "LEFT JOIN pg_catalog.pg_class t ON "
2417                                           "  (c.reltoastrelid = t.oid) "
2418                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
2419                                           pg_rel_oid);
2420
2421         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2422
2423         pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2424
2425         binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
2426                                                                                          pg_type_oid);
2427
2428         if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2429         {
2430                 /* Toast tables do not have pg_type array rows */
2431                 Oid                     pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2432                                                                                         PQfnumber(upgrade_res, "trel")));
2433
2434                 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2435                 appendPQExpBuffer(upgrade_buffer,
2436                                                   "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2437                                                   pg_type_toast_oid);
2438
2439                 toast_set = true;
2440         }
2441
2442         PQclear(upgrade_res);
2443         destroyPQExpBuffer(upgrade_query);
2444
2445         return toast_set;
2446 }
2447
2448 static void
2449 binary_upgrade_set_pg_class_oids(Archive *fout,
2450                                                                  PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2451                                                                  bool is_index)
2452 {
2453         PQExpBuffer upgrade_query = createPQExpBuffer();
2454         PGresult   *upgrade_res;
2455         Oid                     pg_class_reltoastrelid;
2456         Oid                     pg_class_reltoastidxid;
2457
2458         appendPQExpBuffer(upgrade_query,
2459                                           "SELECT c.reltoastrelid, t.reltoastidxid "
2460                                           "FROM pg_catalog.pg_class c LEFT JOIN "
2461                                           "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2462                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
2463                                           pg_class_oid);
2464
2465         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2466
2467         pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2468         pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2469
2470         appendPQExpBuffer(upgrade_buffer,
2471                                    "\n-- For binary upgrade, must preserve pg_class oids\n");
2472
2473         if (!is_index)
2474         {
2475                 appendPQExpBuffer(upgrade_buffer,
2476                                                   "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2477                                                   pg_class_oid);
2478                 /* only tables have toast tables, not indexes */
2479                 if (OidIsValid(pg_class_reltoastrelid))
2480                 {
2481                         /*
2482                          * One complexity is that the table definition might not require
2483                          * the creation of a TOAST table, and the TOAST table might have
2484                          * been created long after table creation, when the table was
2485                          * loaded with wide data.  By setting the TOAST oid we force
2486                          * creation of the TOAST heap and TOAST index by the backend so we
2487                          * can cleanly copy the files during binary upgrade.
2488                          */
2489
2490                         appendPQExpBuffer(upgrade_buffer,
2491                                                           "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2492                                                           pg_class_reltoastrelid);
2493
2494                         /* every toast table has an index */
2495                         appendPQExpBuffer(upgrade_buffer,
2496                                                           "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2497                                                           pg_class_reltoastidxid);
2498                 }
2499         }
2500         else
2501                 appendPQExpBuffer(upgrade_buffer,
2502                                                   "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2503                                                   pg_class_oid);
2504
2505         appendPQExpBuffer(upgrade_buffer, "\n");
2506
2507         PQclear(upgrade_res);
2508         destroyPQExpBuffer(upgrade_query);
2509 }
2510
2511 /*
2512  * If the DumpableObject is a member of an extension, add a suitable
2513  * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2514  */
2515 static void
2516 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2517                                                                 DumpableObject *dobj,
2518                                                                 const char *objlabel)
2519 {
2520         DumpableObject *extobj = NULL;
2521         int                     i;
2522
2523         if (!dobj->ext_member)
2524                 return;
2525
2526         /*
2527          * Find the parent extension.  We could avoid this search if we wanted to
2528          * add a link field to DumpableObject, but the space costs of that would
2529          * be considerable.  We assume that member objects could only have a
2530          * direct dependency on their own extension, not any others.
2531          */
2532         for (i = 0; i < dobj->nDeps; i++)
2533         {
2534                 extobj = findObjectByDumpId(dobj->dependencies[i]);
2535                 if (extobj && extobj->objType == DO_EXTENSION)
2536                         break;
2537                 extobj = NULL;
2538         }
2539         if (extobj == NULL)
2540                 exit_horribly(NULL, "could not find parent extension for %s", objlabel);
2541
2542         appendPQExpBuffer(upgrade_buffer,
2543           "\n-- For binary upgrade, handle extension membership the hard way\n");
2544         appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2545                                           fmtId(extobj->name),
2546                                           objlabel);
2547 }
2548
2549 /*
2550  * getNamespaces:
2551  *        read all namespaces in the system catalogs and return them in the
2552  * NamespaceInfo* structure
2553  *
2554  *      numNamespaces is set to the number of namespaces read in
2555  */
2556 NamespaceInfo *
2557 getNamespaces(Archive *fout, int *numNamespaces)
2558 {
2559         PGresult   *res;
2560         int                     ntups;
2561         int                     i;
2562         PQExpBuffer query;
2563         NamespaceInfo *nsinfo;
2564         int                     i_tableoid;
2565         int                     i_oid;
2566         int                     i_nspname;
2567         int                     i_rolname;
2568         int                     i_nspacl;
2569
2570         /*
2571          * Before 7.3, there are no real namespaces; create two dummy entries, one
2572          * for user stuff and one for system stuff.
2573          */
2574         if (fout->remoteVersion < 70300)
2575         {
2576                 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2577
2578                 nsinfo[0].dobj.objType = DO_NAMESPACE;
2579                 nsinfo[0].dobj.catId.tableoid = 0;
2580                 nsinfo[0].dobj.catId.oid = 0;
2581                 AssignDumpId(&nsinfo[0].dobj);
2582                 nsinfo[0].dobj.name = pg_strdup("public");
2583                 nsinfo[0].rolname = pg_strdup("");
2584                 nsinfo[0].nspacl = pg_strdup("");
2585
2586                 selectDumpableNamespace(&nsinfo[0]);
2587
2588                 nsinfo[1].dobj.objType = DO_NAMESPACE;
2589                 nsinfo[1].dobj.catId.tableoid = 0;
2590                 nsinfo[1].dobj.catId.oid = 1;
2591                 AssignDumpId(&nsinfo[1].dobj);
2592                 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2593                 nsinfo[1].rolname = pg_strdup("");
2594                 nsinfo[1].nspacl = pg_strdup("");
2595
2596                 selectDumpableNamespace(&nsinfo[1]);
2597
2598                 g_namespaces = nsinfo;
2599                 g_numNamespaces = *numNamespaces = 2;
2600
2601                 return nsinfo;
2602         }
2603
2604         query = createPQExpBuffer();
2605
2606         /* Make sure we are in proper schema */
2607         selectSourceSchema(fout, "pg_catalog");
2608
2609         /*
2610          * we fetch all namespaces including system ones, so that every object we
2611          * read in can be linked to a containing namespace.
2612          */
2613         appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2614                                           "(%s nspowner) AS rolname, "
2615                                           "nspacl FROM pg_namespace",
2616                                           username_subquery);
2617
2618         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2619
2620         ntups = PQntuples(res);
2621
2622         nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2623
2624         i_tableoid = PQfnumber(res, "tableoid");
2625         i_oid = PQfnumber(res, "oid");
2626         i_nspname = PQfnumber(res, "nspname");
2627         i_rolname = PQfnumber(res, "rolname");
2628         i_nspacl = PQfnumber(res, "nspacl");
2629
2630         for (i = 0; i < ntups; i++)
2631         {
2632                 nsinfo[i].dobj.objType = DO_NAMESPACE;
2633                 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2634                 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2635                 AssignDumpId(&nsinfo[i].dobj);
2636                 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2637                 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2638                 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2639
2640                 /* Decide whether to dump this namespace */
2641                 selectDumpableNamespace(&nsinfo[i]);
2642
2643                 if (strlen(nsinfo[i].rolname) == 0)
2644                         write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2645                                           nsinfo[i].dobj.name);
2646         }
2647
2648         PQclear(res);
2649         destroyPQExpBuffer(query);
2650
2651         g_namespaces = nsinfo;
2652         g_numNamespaces = *numNamespaces = ntups;
2653
2654         return nsinfo;
2655 }
2656
2657 /*
2658  * findNamespace:
2659  *              given a namespace OID and an object OID, look up the info read by
2660  *              getNamespaces
2661  *
2662  * NB: for pre-7.3 source database, we use object OID to guess whether it's
2663  * a system object or not.      In 7.3 and later there is no guessing.
2664  */
2665 static NamespaceInfo *
2666 findNamespace(Archive *fout, Oid nsoid, Oid objoid)
2667 {
2668         int                     i;
2669
2670         if (fout->remoteVersion >= 70300)
2671         {
2672                 for (i = 0; i < g_numNamespaces; i++)
2673                 {
2674                         NamespaceInfo *nsinfo = &g_namespaces[i];
2675
2676                         if (nsoid == nsinfo->dobj.catId.oid)
2677                                 return nsinfo;
2678                 }
2679                 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
2680         }
2681         else
2682         {
2683                 /* This code depends on the layout set up by getNamespaces. */
2684                 if (objoid > g_last_builtin_oid)
2685                         i = 0;                          /* user object */
2686                 else
2687                         i = 1;                          /* system object */
2688                 return &g_namespaces[i];
2689         }
2690
2691         return NULL;                            /* keep compiler quiet */
2692 }
2693
2694 /*
2695  * getExtensions:
2696  *        read all extensions in the system catalogs and return them in the
2697  * ExtensionInfo* structure
2698  *
2699  *      numExtensions is set to the number of extensions read in
2700  */
2701 ExtensionInfo *
2702 getExtensions(Archive *fout, int *numExtensions)
2703 {
2704         PGresult   *res;
2705         int                     ntups;
2706         int                     i;
2707         PQExpBuffer query;
2708         ExtensionInfo *extinfo;
2709         int                     i_tableoid;
2710         int                     i_oid;
2711         int                     i_extname;
2712         int                     i_nspname;
2713         int                     i_extrelocatable;
2714         int                     i_extversion;
2715         int                     i_extconfig;
2716         int                     i_extcondition;
2717
2718         /*
2719          * Before 9.1, there are no extensions.
2720          */
2721         if (fout->remoteVersion < 90100)
2722         {
2723                 *numExtensions = 0;
2724                 return NULL;
2725         }
2726
2727         query = createPQExpBuffer();
2728
2729         /* Make sure we are in proper schema */
2730         selectSourceSchema(fout, "pg_catalog");
2731
2732         appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
2733                                           "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
2734                                           "FROM pg_extension x "
2735                                           "JOIN pg_namespace n ON n.oid = x.extnamespace");
2736
2737         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2738
2739         ntups = PQntuples(res);
2740
2741         extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
2742
2743         i_tableoid = PQfnumber(res, "tableoid");
2744         i_oid = PQfnumber(res, "oid");
2745         i_extname = PQfnumber(res, "extname");
2746         i_nspname = PQfnumber(res, "nspname");
2747         i_extrelocatable = PQfnumber(res, "extrelocatable");
2748         i_extversion = PQfnumber(res, "extversion");
2749         i_extconfig = PQfnumber(res, "extconfig");
2750         i_extcondition = PQfnumber(res, "extcondition");
2751
2752         for (i = 0; i < ntups; i++)
2753         {
2754                 extinfo[i].dobj.objType = DO_EXTENSION;
2755                 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2756                 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2757                 AssignDumpId(&extinfo[i].dobj);
2758                 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
2759                 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
2760                 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
2761                 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
2762                 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
2763                 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
2764
2765                 /* Decide whether we want to dump it */
2766                 selectDumpableExtension(&(extinfo[i]));
2767         }
2768
2769         PQclear(res);
2770         destroyPQExpBuffer(query);
2771
2772         *numExtensions = ntups;
2773
2774         return extinfo;
2775 }
2776
2777 /*
2778  * getTypes:
2779  *        read all types in the system catalogs and return them in the
2780  * TypeInfo* structure
2781  *
2782  *      numTypes is set to the number of types read in
2783  *
2784  * NB: this must run after getFuncs() because we assume we can do
2785  * findFuncByOid().
2786  */
2787 TypeInfo *
2788 getTypes(Archive *fout, int *numTypes)
2789 {
2790         PGresult   *res;
2791         int                     ntups;
2792         int                     i;
2793         PQExpBuffer query = createPQExpBuffer();
2794         TypeInfo   *tyinfo;
2795         ShellTypeInfo *stinfo;
2796         int                     i_tableoid;
2797         int                     i_oid;
2798         int                     i_typname;
2799         int                     i_typnamespace;
2800         int                     i_rolname;
2801         int                     i_typinput;
2802         int                     i_typoutput;
2803         int                     i_typelem;
2804         int                     i_typrelid;
2805         int                     i_typrelkind;
2806         int                     i_typtype;
2807         int                     i_typisdefined;
2808         int                     i_isarray;
2809
2810         /*
2811          * we include even the built-in types because those may be used as array
2812          * elements by user-defined types
2813          *
2814          * we filter out the built-in types when we dump out the types
2815          *
2816          * same approach for undefined (shell) types and array types
2817          *
2818          * Note: as of 8.3 we can reliably detect whether a type is an
2819          * auto-generated array type by checking the element type's typarray.
2820          * (Before that the test is capable of generating false positives.) We
2821          * still check for name beginning with '_', though, so as to avoid the
2822          * cost of the subselect probe for all standard types.  This would have to
2823          * be revisited if the backend ever allows renaming of array types.
2824          */
2825
2826         /* Make sure we are in proper schema */
2827         selectSourceSchema(fout, "pg_catalog");
2828
2829         if (fout->remoteVersion >= 80300)
2830         {
2831                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2832                                                   "typnamespace, "
2833                                                   "(%s typowner) AS rolname, "
2834                                                   "typinput::oid AS typinput, "
2835                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2836                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2837                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2838                                                   "typtype, typisdefined, "
2839                                                   "typname[0] = '_' AND typelem != 0 AND "
2840                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2841                                                   "FROM pg_type",
2842                                                   username_subquery);
2843         }
2844         else if (fout->remoteVersion >= 70300)
2845         {
2846                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2847                                                   "typnamespace, "
2848                                                   "(%s typowner) AS rolname, "
2849                                                   "typinput::oid AS typinput, "
2850                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2851                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2852                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2853                                                   "typtype, typisdefined, "
2854                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2855                                                   "FROM pg_type",
2856                                                   username_subquery);
2857         }
2858         else if (fout->remoteVersion >= 70100)
2859         {
2860                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2861                                                   "0::oid AS typnamespace, "
2862                                                   "(%s typowner) AS rolname, "
2863                                                   "typinput::oid AS typinput, "
2864                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2865                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2866                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2867                                                   "typtype, typisdefined, "
2868                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2869                                                   "FROM pg_type",
2870                                                   username_subquery);
2871         }
2872         else
2873         {
2874                 appendPQExpBuffer(query, "SELECT "
2875                  "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
2876                                                   "oid, typname, "
2877                                                   "0::oid AS typnamespace, "
2878                                                   "(%s typowner) AS rolname, "
2879                                                   "typinput::oid AS typinput, "
2880                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2881                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2882                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2883                                                   "typtype, typisdefined, "
2884                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2885                                                   "FROM pg_type",
2886                                                   username_subquery);
2887         }
2888
2889         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2890
2891         ntups = PQntuples(res);
2892
2893         tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
2894
2895         i_tableoid = PQfnumber(res, "tableoid");
2896         i_oid = PQfnumber(res, "oid");
2897         i_typname = PQfnumber(res, "typname");
2898         i_typnamespace = PQfnumber(res, "typnamespace");
2899         i_rolname = PQfnumber(res, "rolname");
2900         i_typinput = PQfnumber(res, "typinput");
2901         i_typoutput = PQfnumber(res, "typoutput");
2902         i_typelem = PQfnumber(res, "typelem");
2903         i_typrelid = PQfnumber(res, "typrelid");
2904         i_typrelkind = PQfnumber(res, "typrelkind");
2905         i_typtype = PQfnumber(res, "typtype");
2906         i_typisdefined = PQfnumber(res, "typisdefined");
2907         i_isarray = PQfnumber(res, "isarray");
2908
2909         for (i = 0; i < ntups; i++)
2910         {
2911                 tyinfo[i].dobj.objType = DO_TYPE;
2912                 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2913                 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2914                 AssignDumpId(&tyinfo[i].dobj);
2915                 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
2916                 tyinfo[i].dobj.namespace =
2917                         findNamespace(fout,
2918                                                   atooid(PQgetvalue(res, i, i_typnamespace)),
2919                                                   tyinfo[i].dobj.catId.oid);
2920                 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2921                 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
2922                 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
2923                 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
2924                 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
2925                 tyinfo[i].shellType = NULL;
2926
2927                 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
2928                         tyinfo[i].isDefined = true;
2929                 else
2930                         tyinfo[i].isDefined = false;
2931
2932                 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
2933                         tyinfo[i].isArray = true;
2934                 else
2935                         tyinfo[i].isArray = false;
2936
2937                 /* Decide whether we want to dump it */
2938                 selectDumpableType(&tyinfo[i]);
2939
2940                 /*
2941                  * If it's a domain, fetch info about its constraints, if any
2942                  */
2943                 tyinfo[i].nDomChecks = 0;
2944                 tyinfo[i].domChecks = NULL;
2945                 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
2946                         getDomainConstraints(fout, &(tyinfo[i]));
2947
2948                 /*
2949                  * If it's a base type, make a DumpableObject representing a shell
2950                  * definition of the type.      We will need to dump that ahead of the I/O
2951                  * functions for the type.  Similarly, range types need a shell
2952                  * definition in case they have a canonicalize function.
2953                  *
2954                  * Note: the shell type doesn't have a catId.  You might think it
2955                  * should copy the base type's catId, but then it might capture the
2956                  * pg_depend entries for the type, which we don't want.
2957                  */
2958                 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
2959                                                                         tyinfo[i].typtype == TYPTYPE_RANGE))
2960                 {
2961                         stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
2962                         stinfo->dobj.objType = DO_SHELL_TYPE;
2963                         stinfo->dobj.catId = nilCatalogId;
2964                         AssignDumpId(&stinfo->dobj);
2965                         stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
2966                         stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
2967                         stinfo->baseType = &(tyinfo[i]);
2968                         tyinfo[i].shellType = stinfo;
2969
2970                         /*
2971                          * Initially mark the shell type as not to be dumped.  We'll only
2972                          * dump it if the I/O or canonicalize functions need to be dumped;
2973                          * this is taken care of while sorting dependencies.
2974                          */
2975                         stinfo->dobj.dump = false;
2976
2977                         /*
2978                          * However, if dumping from pre-7.3, there will be no dependency
2979                          * info so we have to fake it here.  We only need to worry about
2980                          * typinput and typoutput since the other functions only exist
2981                          * post-7.3.
2982                          */
2983                         if (fout->remoteVersion < 70300)
2984                         {
2985                                 Oid                     typinput;
2986                                 Oid                     typoutput;
2987                                 FuncInfo   *funcInfo;
2988
2989                                 typinput = atooid(PQgetvalue(res, i, i_typinput));
2990                                 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
2991
2992                                 funcInfo = findFuncByOid(typinput);
2993                                 if (funcInfo && funcInfo->dobj.dump)
2994                                 {
2995                                         /* base type depends on function */
2996                                         addObjectDependency(&tyinfo[i].dobj,
2997                                                                                 funcInfo->dobj.dumpId);
2998                                         /* function depends on shell type */
2999                                         addObjectDependency(&funcInfo->dobj,
3000                                                                                 stinfo->dobj.dumpId);
3001                                         /* mark shell type as to be dumped */
3002                                         stinfo->dobj.dump = true;
3003                                 }
3004
3005                                 funcInfo = findFuncByOid(typoutput);
3006                                 if (funcInfo && funcInfo->dobj.dump)
3007                                 {
3008                                         /* base type depends on function */
3009                                         addObjectDependency(&tyinfo[i].dobj,
3010                                                                                 funcInfo->dobj.dumpId);
3011                                         /* function depends on shell type */
3012                                         addObjectDependency(&funcInfo->dobj,
3013                                                                                 stinfo->dobj.dumpId);
3014                                         /* mark shell type as to be dumped */
3015                                         stinfo->dobj.dump = true;
3016                                 }
3017                         }
3018                 }
3019
3020                 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3021                         write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3022                                           tyinfo[i].dobj.name);
3023         }
3024
3025         *numTypes = ntups;
3026
3027         PQclear(res);
3028
3029         destroyPQExpBuffer(query);
3030
3031         return tyinfo;
3032 }
3033
3034 /*
3035  * getOperators:
3036  *        read all operators in the system catalogs and return them in the
3037  * OprInfo* structure
3038  *
3039  *      numOprs is set to the number of operators read in
3040  */
3041 OprInfo *
3042 getOperators(Archive *fout, int *numOprs)
3043 {
3044         PGresult   *res;
3045         int                     ntups;
3046         int                     i;
3047         PQExpBuffer query = createPQExpBuffer();
3048         OprInfo    *oprinfo;
3049         int                     i_tableoid;
3050         int                     i_oid;
3051         int                     i_oprname;
3052         int                     i_oprnamespace;
3053         int                     i_rolname;
3054         int                     i_oprkind;
3055         int                     i_oprcode;
3056
3057         /*
3058          * find all operators, including builtin operators; we filter out
3059          * system-defined operators at dump-out time.
3060          */
3061
3062         /* Make sure we are in proper schema */
3063         selectSourceSchema(fout, "pg_catalog");
3064
3065         if (fout->remoteVersion >= 70300)
3066         {
3067                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3068                                                   "oprnamespace, "
3069                                                   "(%s oprowner) AS rolname, "
3070                                                   "oprkind, "
3071                                                   "oprcode::oid AS oprcode "
3072                                                   "FROM pg_operator",
3073                                                   username_subquery);
3074         }
3075         else if (fout->remoteVersion >= 70100)
3076         {
3077                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3078                                                   "0::oid AS oprnamespace, "
3079                                                   "(%s oprowner) AS rolname, "
3080                                                   "oprkind, "
3081                                                   "oprcode::oid AS oprcode "
3082                                                   "FROM pg_operator",
3083                                                   username_subquery);
3084         }
3085         else
3086         {
3087                 appendPQExpBuffer(query, "SELECT "
3088                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3089                                                   "oid, oprname, "
3090                                                   "0::oid AS oprnamespace, "
3091                                                   "(%s oprowner) AS rolname, "
3092                                                   "oprkind, "
3093                                                   "oprcode::oid AS oprcode "
3094                                                   "FROM pg_operator",
3095                                                   username_subquery);
3096         }
3097
3098         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3099
3100         ntups = PQntuples(res);
3101         *numOprs = ntups;
3102
3103         oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3104
3105         i_tableoid = PQfnumber(res, "tableoid");
3106         i_oid = PQfnumber(res, "oid");
3107         i_oprname = PQfnumber(res, "oprname");
3108         i_oprnamespace = PQfnumber(res, "oprnamespace");
3109         i_rolname = PQfnumber(res, "rolname");
3110         i_oprkind = PQfnumber(res, "oprkind");
3111         i_oprcode = PQfnumber(res, "oprcode");
3112
3113         for (i = 0; i < ntups; i++)
3114         {
3115                 oprinfo[i].dobj.objType = DO_OPERATOR;
3116                 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3117                 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3118                 AssignDumpId(&oprinfo[i].dobj);
3119                 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3120                 oprinfo[i].dobj.namespace =
3121                         findNamespace(fout,
3122                                                   atooid(PQgetvalue(res, i, i_oprnamespace)),
3123                                                   oprinfo[i].dobj.catId.oid);
3124                 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3125                 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3126                 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3127
3128                 /* Decide whether we want to dump it */
3129                 selectDumpableObject(&(oprinfo[i].dobj));
3130
3131                 if (strlen(oprinfo[i].rolname) == 0)
3132                         write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3133                                           oprinfo[i].dobj.name);
3134         }
3135
3136         PQclear(res);
3137
3138         destroyPQExpBuffer(query);
3139
3140         return oprinfo;
3141 }
3142
3143 /*
3144  * getCollations:
3145  *        read all collations in the system catalogs and return them in the
3146  * CollInfo* structure
3147  *
3148  *      numCollations is set to the number of collations read in
3149  */
3150 CollInfo *
3151 getCollations(Archive *fout, int *numCollations)
3152 {
3153         PGresult   *res;
3154         int                     ntups;
3155         int                     i;
3156         PQExpBuffer query;
3157         CollInfo   *collinfo;
3158         int                     i_tableoid;
3159         int                     i_oid;
3160         int                     i_collname;
3161         int                     i_collnamespace;
3162         int                     i_rolname;
3163
3164         /* Collations didn't exist pre-9.1 */
3165         if (fout->remoteVersion < 90100)
3166         {
3167                 *numCollations = 0;
3168                 return NULL;
3169         }
3170
3171         query = createPQExpBuffer();
3172
3173         /*
3174          * find all collations, including builtin collations; we filter out
3175          * system-defined collations at dump-out time.
3176          */
3177
3178         /* Make sure we are in proper schema */
3179         selectSourceSchema(fout, "pg_catalog");
3180
3181         appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3182                                           "collnamespace, "
3183                                           "(%s collowner) AS rolname "
3184                                           "FROM pg_collation",
3185                                           username_subquery);
3186
3187         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3188
3189         ntups = PQntuples(res);
3190         *numCollations = ntups;
3191
3192         collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3193
3194         i_tableoid = PQfnumber(res, "tableoid");
3195         i_oid = PQfnumber(res, "oid");
3196         i_collname = PQfnumber(res, "collname");
3197         i_collnamespace = PQfnumber(res, "collnamespace");
3198         i_rolname = PQfnumber(res, "rolname");
3199
3200         for (i = 0; i < ntups; i++)
3201         {
3202                 collinfo[i].dobj.objType = DO_COLLATION;
3203                 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3204                 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3205                 AssignDumpId(&collinfo[i].dobj);
3206                 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3207                 collinfo[i].dobj.namespace =
3208                         findNamespace(fout,
3209                                                   atooid(PQgetvalue(res, i, i_collnamespace)),
3210                                                   collinfo[i].dobj.catId.oid);
3211                 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3212
3213                 /* Decide whether we want to dump it */
3214                 selectDumpableObject(&(collinfo[i].dobj));
3215         }
3216
3217         PQclear(res);
3218
3219         destroyPQExpBuffer(query);
3220
3221         return collinfo;
3222 }
3223
3224 /*
3225  * getConversions:
3226  *        read all conversions in the system catalogs and return them in the
3227  * ConvInfo* structure
3228  *
3229  *      numConversions is set to the number of conversions read in
3230  */
3231 ConvInfo *
3232 getConversions(Archive *fout, int *numConversions)
3233 {
3234         PGresult   *res;
3235         int                     ntups;
3236         int                     i;
3237         PQExpBuffer query = createPQExpBuffer();
3238         ConvInfo   *convinfo;
3239         int                     i_tableoid;
3240         int                     i_oid;
3241         int                     i_conname;
3242         int                     i_connamespace;
3243         int                     i_rolname;
3244
3245         /* Conversions didn't exist pre-7.3 */
3246         if (fout->remoteVersion < 70300)
3247         {
3248                 *numConversions = 0;
3249                 return NULL;
3250         }
3251
3252         /*
3253          * find all conversions, including builtin conversions; we filter out
3254          * system-defined conversions at dump-out time.
3255          */
3256
3257         /* Make sure we are in proper schema */
3258         selectSourceSchema(fout, "pg_catalog");
3259
3260         appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3261                                           "connamespace, "
3262                                           "(%s conowner) AS rolname "
3263                                           "FROM pg_conversion",
3264                                           username_subquery);
3265
3266         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3267
3268         ntups = PQntuples(res);
3269         *numConversions = ntups;
3270
3271         convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3272
3273         i_tableoid = PQfnumber(res, "tableoid");
3274         i_oid = PQfnumber(res, "oid");
3275         i_conname = PQfnumber(res, "conname");
3276         i_connamespace = PQfnumber(res, "connamespace");
3277         i_rolname = PQfnumber(res, "rolname");
3278
3279         for (i = 0; i < ntups; i++)
3280         {
3281                 convinfo[i].dobj.objType = DO_CONVERSION;
3282                 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3283                 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3284                 AssignDumpId(&convinfo[i].dobj);
3285                 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3286                 convinfo[i].dobj.namespace =
3287                         findNamespace(fout,
3288                                                   atooid(PQgetvalue(res, i, i_connamespace)),
3289                                                   convinfo[i].dobj.catId.oid);
3290                 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3291
3292                 /* Decide whether we want to dump it */
3293                 selectDumpableObject(&(convinfo[i].dobj));
3294         }
3295
3296         PQclear(res);
3297
3298         destroyPQExpBuffer(query);
3299
3300         return convinfo;
3301 }
3302
3303 /*
3304  * getOpclasses:
3305  *        read all opclasses in the system catalogs and return them in the
3306  * OpclassInfo* structure
3307  *
3308  *      numOpclasses is set to the number of opclasses read in
3309  */
3310 OpclassInfo *
3311 getOpclasses(Archive *fout, int *numOpclasses)
3312 {
3313         PGresult   *res;
3314         int                     ntups;
3315         int                     i;
3316         PQExpBuffer query = createPQExpBuffer();
3317         OpclassInfo *opcinfo;
3318         int                     i_tableoid;
3319         int                     i_oid;
3320         int                     i_opcname;
3321         int                     i_opcnamespace;
3322         int                     i_rolname;
3323
3324         /*
3325          * find all opclasses, including builtin opclasses; we filter out
3326          * system-defined opclasses at dump-out time.
3327          */
3328
3329         /* Make sure we are in proper schema */
3330         selectSourceSchema(fout, "pg_catalog");
3331
3332         if (fout->remoteVersion >= 70300)
3333         {
3334                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3335                                                   "opcnamespace, "
3336                                                   "(%s opcowner) AS rolname "
3337                                                   "FROM pg_opclass",
3338                                                   username_subquery);
3339         }
3340         else if (fout->remoteVersion >= 70100)
3341         {
3342                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3343                                                   "0::oid AS opcnamespace, "
3344                                                   "''::name AS rolname "
3345                                                   "FROM pg_opclass");
3346         }
3347         else
3348         {
3349                 appendPQExpBuffer(query, "SELECT "
3350                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3351                                                   "oid, opcname, "
3352                                                   "0::oid AS opcnamespace, "
3353                                                   "''::name AS rolname "
3354                                                   "FROM pg_opclass");
3355         }
3356
3357         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3358
3359         ntups = PQntuples(res);
3360         *numOpclasses = ntups;
3361
3362         opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3363
3364         i_tableoid = PQfnumber(res, "tableoid");
3365         i_oid = PQfnumber(res, "oid");
3366         i_opcname = PQfnumber(res, "opcname");
3367         i_opcnamespace = PQfnumber(res, "opcnamespace");
3368         i_rolname = PQfnumber(res, "rolname");
3369
3370         for (i = 0; i < ntups; i++)
3371         {
3372                 opcinfo[i].dobj.objType = DO_OPCLASS;
3373                 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3374                 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3375                 AssignDumpId(&opcinfo[i].dobj);
3376                 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3377                 opcinfo[i].dobj.namespace =
3378                         findNamespace(fout,
3379                                                   atooid(PQgetvalue(res, i, i_opcnamespace)),
3380                                                   opcinfo[i].dobj.catId.oid);
3381                 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3382
3383                 /* Decide whether we want to dump it */
3384                 selectDumpableObject(&(opcinfo[i].dobj));
3385
3386                 if (fout->remoteVersion >= 70300)
3387                 {
3388                         if (strlen(opcinfo[i].rolname) == 0)
3389                                 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3390                                                   opcinfo[i].dobj.name);
3391                 }
3392         }
3393
3394         PQclear(res);
3395
3396         destroyPQExpBuffer(query);
3397
3398         return opcinfo;
3399 }
3400
3401 /*
3402  * getOpfamilies:
3403  *        read all opfamilies in the system catalogs and return them in the
3404  * OpfamilyInfo* structure
3405  *
3406  *      numOpfamilies is set to the number of opfamilies read in
3407  */
3408 OpfamilyInfo *
3409 getOpfamilies(Archive *fout, int *numOpfamilies)
3410 {
3411         PGresult   *res;
3412         int                     ntups;
3413         int                     i;
3414         PQExpBuffer query;
3415         OpfamilyInfo *opfinfo;
3416         int                     i_tableoid;
3417         int                     i_oid;
3418         int                     i_opfname;
3419         int                     i_opfnamespace;
3420         int                     i_rolname;
3421
3422         /* Before 8.3, there is no separate concept of opfamilies */
3423         if (fout->remoteVersion < 80300)
3424         {
3425                 *numOpfamilies = 0;
3426                 return NULL;
3427         }
3428
3429         query = createPQExpBuffer();
3430
3431         /*
3432          * find all opfamilies, including builtin opfamilies; we filter out
3433          * system-defined opfamilies at dump-out time.
3434          */
3435
3436         /* Make sure we are in proper schema */
3437         selectSourceSchema(fout, "pg_catalog");
3438
3439         appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3440                                           "opfnamespace, "
3441                                           "(%s opfowner) AS rolname "
3442                                           "FROM pg_opfamily",
3443                                           username_subquery);
3444
3445         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3446
3447         ntups = PQntuples(res);
3448         *numOpfamilies = ntups;
3449
3450         opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3451
3452         i_tableoid = PQfnumber(res, "tableoid");
3453         i_oid = PQfnumber(res, "oid");
3454         i_opfname = PQfnumber(res, "opfname");
3455         i_opfnamespace = PQfnumber(res, "opfnamespace");
3456         i_rolname = PQfnumber(res, "rolname");
3457
3458         for (i = 0; i < ntups; i++)
3459         {
3460                 opfinfo[i].dobj.objType = DO_OPFAMILY;
3461                 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3462                 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3463                 AssignDumpId(&opfinfo[i].dobj);
3464                 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3465                 opfinfo[i].dobj.namespace =
3466                         findNamespace(fout,
3467                                                   atooid(PQgetvalue(res, i, i_opfnamespace)),
3468                                                   opfinfo[i].dobj.catId.oid);
3469                 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3470
3471                 /* Decide whether we want to dump it */
3472                 selectDumpableObject(&(opfinfo[i].dobj));
3473
3474                 if (fout->remoteVersion >= 70300)
3475                 {
3476                         if (strlen(opfinfo[i].rolname) == 0)
3477                                 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3478                                                   opfinfo[i].dobj.name);
3479                 }
3480         }
3481
3482         PQclear(res);
3483
3484         destroyPQExpBuffer(query);
3485
3486         return opfinfo;
3487 }
3488
3489 /*
3490  * getAggregates:
3491  *        read all the user-defined aggregates in the system catalogs and
3492  * return them in the AggInfo* structure
3493  *
3494  * numAggs is set to the number of aggregates read in
3495  */
3496 AggInfo *
3497 getAggregates(Archive *fout, int *numAggs)
3498 {
3499         PGresult   *res;
3500         int                     ntups;
3501         int                     i;
3502         PQExpBuffer query = createPQExpBuffer();
3503         AggInfo    *agginfo;
3504         int                     i_tableoid;
3505         int                     i_oid;
3506         int                     i_aggname;
3507         int                     i_aggnamespace;
3508         int                     i_pronargs;
3509         int                     i_proargtypes;
3510         int                     i_rolname;
3511         int                     i_aggacl;
3512
3513         /* Make sure we are in proper schema */
3514         selectSourceSchema(fout, "pg_catalog");
3515
3516         /*
3517          * Find all user-defined aggregates.  See comment in getFuncs() for the
3518          * rationale behind the filtering logic.
3519          */
3520
3521         if (fout->remoteVersion >= 80200)
3522         {
3523                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3524                                                   "pronamespace AS aggnamespace, "
3525                                                   "pronargs, proargtypes, "
3526                                                   "(%s proowner) AS rolname, "
3527                                                   "proacl AS aggacl "
3528                                                   "FROM pg_proc p "
3529                                                   "WHERE proisagg AND ("
3530                                                   "pronamespace != "
3531                                                   "(SELECT oid FROM pg_namespace "
3532                                                   "WHERE nspname = 'pg_catalog')",
3533                                                   username_subquery);
3534                 if (binary_upgrade && fout->remoteVersion >= 90100)
3535                         appendPQExpBuffer(query,
3536                                                           " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3537                                                           "classid = 'pg_proc'::regclass AND "
3538                                                           "objid = p.oid AND "
3539                                                           "refclassid = 'pg_extension'::regclass AND "
3540                                                           "deptype = 'e')");
3541                 appendPQExpBuffer(query, ")");
3542         }
3543         else if (fout->remoteVersion >= 70300)
3544         {
3545                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3546                                                   "pronamespace AS aggnamespace, "
3547                                                   "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3548                                                   "proargtypes, "
3549                                                   "(%s proowner) AS rolname, "
3550                                                   "proacl AS aggacl "
3551                                                   "FROM pg_proc "
3552                                                   "WHERE proisagg "
3553                                                   "AND pronamespace != "
3554                            "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3555                                                   username_subquery);
3556         }
3557         else if (fout->remoteVersion >= 70100)
3558         {
3559                 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3560                                                   "0::oid AS aggnamespace, "
3561                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3562                                                   "aggbasetype AS proargtypes, "
3563                                                   "(%s aggowner) AS rolname, "
3564                                                   "'{=X}' AS aggacl "
3565                                                   "FROM pg_aggregate "
3566                                                   "where oid > '%u'::oid",
3567                                                   username_subquery,
3568                                                   g_last_builtin_oid);
3569         }
3570         else
3571         {
3572                 appendPQExpBuffer(query, "SELECT "
3573                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3574                                                   "oid, aggname, "
3575                                                   "0::oid AS aggnamespace, "
3576                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3577                                                   "aggbasetype AS proargtypes, "
3578                                                   "(%s aggowner) AS rolname, "
3579                                                   "'{=X}' AS aggacl "
3580                                                   "FROM pg_aggregate "
3581                                                   "where oid > '%u'::oid",
3582                                                   username_subquery,
3583                                                   g_last_builtin_oid);
3584         }
3585
3586         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3587
3588         ntups = PQntuples(res);
3589         *numAggs = ntups;
3590
3591         agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3592
3593         i_tableoid = PQfnumber(res, "tableoid");
3594         i_oid = PQfnumber(res, "oid");
3595         i_aggname = PQfnumber(res, "aggname");
3596         i_aggnamespace = PQfnumber(res, "aggnamespace");
3597         i_pronargs = PQfnumber(res, "pronargs");
3598         i_proargtypes = PQfnumber(res, "proargtypes");
3599         i_rolname = PQfnumber(res, "rolname");
3600         i_aggacl = PQfnumber(res, "aggacl");
3601
3602         for (i = 0; i < ntups; i++)
3603         {
3604                 agginfo[i].aggfn.dobj.objType = DO_AGG;
3605                 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3606                 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3607                 AssignDumpId(&agginfo[i].aggfn.dobj);
3608                 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3609                 agginfo[i].aggfn.dobj.namespace =
3610                         findNamespace(fout,
3611                                                   atooid(PQgetvalue(res, i, i_aggnamespace)),
3612                                                   agginfo[i].aggfn.dobj.catId.oid);
3613                 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3614                 if (strlen(agginfo[i].aggfn.rolname) == 0)
3615                         write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3616                                           agginfo[i].aggfn.dobj.name);
3617                 agginfo[i].aggfn.lang = InvalidOid;             /* not currently interesting */
3618                 agginfo[i].aggfn.prorettype = InvalidOid;               /* not saved */
3619                 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3620                 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3621                 if (agginfo[i].aggfn.nargs == 0)
3622                         agginfo[i].aggfn.argtypes = NULL;
3623                 else
3624                 {
3625                         agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3626                         if (fout->remoteVersion >= 70300)
3627                                 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3628                                                           agginfo[i].aggfn.argtypes,
3629                                                           agginfo[i].aggfn.nargs);
3630                         else
3631                                 /* it's just aggbasetype */
3632                                 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3633                 }
3634
3635                 /* Decide whether we want to dump it */
3636                 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3637         }
3638
3639         PQclear(res);
3640
3641         destroyPQExpBuffer(query);
3642
3643         return agginfo;
3644 }
3645
3646 /*
3647  * getFuncs:
3648  *        read all the user-defined functions in the system catalogs and
3649  * return them in the FuncInfo* structure
3650  *
3651  * numFuncs is set to the number of functions read in
3652  */
3653 FuncInfo *
3654 getFuncs(Archive *fout, int *numFuncs)
3655 {
3656         PGresult   *res;
3657         int                     ntups;
3658         int                     i;
3659         PQExpBuffer query = createPQExpBuffer();
3660         FuncInfo   *finfo;
3661         int                     i_tableoid;
3662         int                     i_oid;
3663         int                     i_proname;
3664         int                     i_pronamespace;
3665         int                     i_rolname;
3666         int                     i_prolang;
3667         int                     i_pronargs;
3668         int                     i_proargtypes;
3669         int                     i_prorettype;
3670         int                     i_proacl;
3671
3672         /* Make sure we are in proper schema */
3673         selectSourceSchema(fout, "pg_catalog");
3674
3675         /*
3676          * Find all user-defined functions.  Normally we can exclude functions in
3677          * pg_catalog, which is worth doing since there are several thousand of
3678          * 'em.  However, there are some extensions that create functions in
3679          * pg_catalog.  In normal dumps we can still ignore those --- but in
3680          * binary-upgrade mode, we must dump the member objects of the extension,
3681          * so be sure to fetch any such functions.
3682          *
3683          * Also, in 9.2 and up, exclude functions that are internally dependent on
3684          * something else, since presumably those will be created as a result of
3685          * creating the something else.  This currently only acts to suppress
3686          * constructor functions for range types.  Note that this is OK only
3687          * because the constructors don't have any dependencies the range type
3688          * doesn't have; otherwise we might not get creation ordering correct.
3689          */
3690
3691         if (fout->remoteVersion >= 70300)
3692         {
3693                 appendPQExpBuffer(query,
3694                                                   "SELECT tableoid, oid, proname, prolang, "
3695                                                   "pronargs, proargtypes, prorettype, proacl, "
3696                                                   "pronamespace, "
3697                                                   "(%s proowner) AS rolname "
3698                                                   "FROM pg_proc p "
3699                                                   "WHERE NOT proisagg AND ("
3700                                                   "pronamespace != "
3701                                                   "(SELECT oid FROM pg_namespace "
3702                                                   "WHERE nspname = 'pg_catalog')",
3703                                                   username_subquery);
3704                 if (fout->remoteVersion >= 90200)
3705                         appendPQExpBuffer(query,
3706                                                           "\n  AND NOT EXISTS (SELECT 1 FROM pg_depend "
3707                                                           "WHERE classid = 'pg_proc'::regclass AND "
3708                                                           "objid = p.oid AND deptype = 'i')");
3709                 if (binary_upgrade && fout->remoteVersion >= 90100)
3710                         appendPQExpBuffer(query,
3711                                                           "\n  OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3712                                                           "classid = 'pg_proc'::regclass AND "
3713                                                           "objid = p.oid AND "
3714                                                           "refclassid = 'pg_extension'::regclass AND "
3715                                                           "deptype = 'e')");
3716                 appendPQExpBuffer(query, ")");
3717         }
3718         else if (fout->remoteVersion >= 70100)
3719         {
3720                 appendPQExpBuffer(query,
3721                                                   "SELECT tableoid, oid, proname, prolang, "
3722                                                   "pronargs, proargtypes, prorettype, "
3723                                                   "'{=X}' AS proacl, "
3724                                                   "0::oid AS pronamespace, "
3725                                                   "(%s proowner) AS rolname "
3726                                                   "FROM pg_proc "
3727                                                   "WHERE pg_proc.oid > '%u'::oid",
3728                                                   username_subquery,
3729                                                   g_last_builtin_oid);
3730         }
3731         else
3732         {
3733                 appendPQExpBuffer(query,
3734                                                   "SELECT "
3735                                                   "(SELECT oid FROM pg_class "
3736                                                   " WHERE relname = 'pg_proc') AS tableoid, "
3737                                                   "oid, proname, prolang, "
3738                                                   "pronargs, proargtypes, prorettype, "
3739                                                   "'{=X}' AS proacl, "
3740                                                   "0::oid AS pronamespace, "
3741                                                   "(%s proowner) AS rolname "
3742                                                   "FROM pg_proc "
3743                                                   "where pg_proc.oid > '%u'::oid",
3744                                                   username_subquery,
3745                                                   g_last_builtin_oid);
3746         }
3747
3748         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3749
3750         ntups = PQntuples(res);
3751
3752         *numFuncs = ntups;
3753
3754         finfo = (FuncInfo *) pg_calloc(ntups, sizeof(FuncInfo));
3755
3756         i_tableoid = PQfnumber(res, "tableoid");
3757         i_oid = PQfnumber(res, "oid");
3758         i_proname = PQfnumber(res, "proname");
3759         i_pronamespace = PQfnumber(res, "pronamespace");
3760         i_rolname = PQfnumber(res, "rolname");
3761         i_prolang = PQfnumber(res, "prolang");
3762         i_pronargs = PQfnumber(res, "pronargs");
3763         i_proargtypes = PQfnumber(res, "proargtypes");
3764         i_prorettype = PQfnumber(res, "prorettype");
3765         i_proacl = PQfnumber(res, "proacl");
3766
3767         for (i = 0; i < ntups; i++)
3768         {
3769                 finfo[i].dobj.objType = DO_FUNC;
3770                 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3771                 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3772                 AssignDumpId(&finfo[i].dobj);
3773                 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
3774                 finfo[i].dobj.namespace =
3775                         findNamespace(fout,
3776                                                   atooid(PQgetvalue(res, i, i_pronamespace)),
3777                                                   finfo[i].dobj.catId.oid);
3778                 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3779                 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
3780                 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
3781                 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
3782                 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
3783                 if (finfo[i].nargs == 0)
3784                         finfo[i].argtypes = NULL;
3785                 else
3786                 {
3787                         finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
3788                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
3789                                                   finfo[i].argtypes, finfo[i].nargs);
3790                 }
3791
3792                 /* Decide whether we want to dump it */
3793                 selectDumpableObject(&(finfo[i].dobj));
3794
3795                 if (strlen(finfo[i].rolname) == 0)
3796                         write_msg(NULL,
3797                                  "WARNING: owner of function \"%s\" appears to be invalid\n",
3798                                           finfo[i].dobj.name);
3799         }
3800
3801         PQclear(res);
3802
3803         destroyPQExpBuffer(query);
3804
3805         return finfo;
3806 }
3807
3808 /*
3809  * getTables
3810  *        read all the user-defined tables (no indexes, no catalogs)
3811  * in the system catalogs return them in the TableInfo* structure
3812  *
3813  * numTables is set to the number of tables read in
3814  */
3815 TableInfo *
3816 getTables(Archive *fout, int *numTables)
3817 {
3818         PGresult   *res;
3819         int                     ntups;
3820         int                     i;
3821         PQExpBuffer query = createPQExpBuffer();
3822         TableInfo  *tblinfo;
3823         int                     i_reltableoid;
3824         int                     i_reloid;
3825         int                     i_relname;
3826         int                     i_relnamespace;
3827         int                     i_relkind;
3828         int                     i_relacl;
3829         int                     i_rolname;
3830         int                     i_relchecks;
3831         int                     i_relhastriggers;
3832         int                     i_relhasindex;
3833         int                     i_relhasrules;
3834         int                     i_relhasoids;
3835         int                     i_relfrozenxid;
3836         int                     i_toastoid;
3837         int                     i_toastfrozenxid;
3838         int                     i_relpersistence;
3839         int                     i_owning_tab;
3840         int                     i_owning_col;
3841         int                     i_reltablespace;
3842         int                     i_reloptions;
3843         int                     i_toastreloptions;
3844         int                     i_reloftype;
3845
3846         /* Make sure we are in proper schema */
3847         selectSourceSchema(fout, "pg_catalog");
3848
3849         /*
3850          * Find all the tables (including views and sequences).
3851          *
3852          * We include system catalogs, so that we can work if a user table is
3853          * defined to inherit from a system catalog (pretty weird, but...)
3854          *
3855          * We ignore tables that are not type 'r' (ordinary relation), 'S'
3856          * (sequence), 'v' (view), or 'c' (composite type).
3857          *
3858          * Composite-type table entries won't be dumped as such, but we have to
3859          * make a DumpableObject for them so that we can track dependencies of the
3860          * composite type (pg_depend entries for columns of the composite type
3861          * link to the pg_class entry not the pg_type entry).
3862          *
3863          * Note: in this phase we should collect only a minimal amount of
3864          * information about each table, basically just enough to decide if it is
3865          * interesting. We must fetch all tables in this phase because otherwise
3866          * we cannot correctly identify inherited columns, owned sequences, etc.
3867          */
3868
3869         if (fout->remoteVersion >= 90100)
3870         {
3871                 /*
3872                  * Left join to pick up dependency info linking sequences to their
3873                  * owning column, if any (note this dependency is AUTO as of 8.2)
3874                  */
3875                 appendPQExpBuffer(query,
3876                                                   "SELECT c.tableoid, c.oid, c.relname, "
3877                                                   "c.relacl, c.relkind, c.relnamespace, "
3878                                                   "(%s c.relowner) AS rolname, "
3879                                                   "c.relchecks, c.relhastriggers, "
3880                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3881                                                   "c.relfrozenxid, tc.oid AS toid, "
3882                                                   "tc.relfrozenxid AS tfrozenxid, "
3883                                                   "c.relpersistence, "
3884                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3885                                                   "d.refobjid AS owning_tab, "
3886                                                   "d.refobjsubid AS owning_col, "
3887                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3888                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3889                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3890                                                   "FROM pg_class c "
3891                                                   "LEFT JOIN pg_depend d ON "
3892                                                   "(c.relkind = '%c' AND "
3893                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3894                                                   "d.objsubid = 0 AND "
3895                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
3896                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3897                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c') "
3898                                                   "ORDER BY c.oid",
3899                                                   username_subquery,
3900                                                   RELKIND_SEQUENCE,
3901                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3902                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
3903                                                   RELKIND_FOREIGN_TABLE);
3904         }
3905         else if (fout->remoteVersion >= 90000)
3906         {
3907                 /*
3908                  * Left join to pick up dependency info linking sequences to their
3909                  * owning column, if any (note this dependency is AUTO as of 8.2)
3910                  */
3911                 appendPQExpBuffer(query,
3912                                                   "SELECT c.tableoid, c.oid, c.relname, "
3913                                                   "c.relacl, c.relkind, c.relnamespace, "
3914                                                   "(%s c.relowner) AS rolname, "
3915                                                   "c.relchecks, c.relhastriggers, "
3916                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3917                                                   "c.relfrozenxid, tc.oid AS toid, "
3918                                                   "tc.relfrozenxid AS tfrozenxid, "
3919                                                   "'p' AS relpersistence, "
3920                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3921                                                   "d.refobjid AS owning_tab, "
3922                                                   "d.refobjsubid AS owning_col, "
3923                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3924                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3925                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3926                                                   "FROM pg_class c "
3927                                                   "LEFT JOIN pg_depend d ON "
3928                                                   "(c.relkind = '%c' AND "
3929                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3930                                                   "d.objsubid = 0 AND "
3931                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
3932                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3933                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3934                                                   "ORDER BY c.oid",
3935                                                   username_subquery,
3936                                                   RELKIND_SEQUENCE,
3937                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3938                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3939         }
3940         else if (fout->remoteVersion >= 80400)
3941         {
3942                 /*
3943                  * Left join to pick up dependency info linking sequences to their
3944                  * owning column, if any (note this dependency is AUTO as of 8.2)
3945                  */
3946                 appendPQExpBuffer(query,
3947                                                   "SELECT c.tableoid, c.oid, c.relname, "
3948                                                   "c.relacl, c.relkind, c.relnamespace, "
3949                                                   "(%s c.relowner) AS rolname, "
3950                                                   "c.relchecks, c.relhastriggers, "
3951                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3952                                                   "c.relfrozenxid, tc.oid AS toid, "
3953                                                   "tc.relfrozenxid AS tfrozenxid, "
3954                                                   "'p' AS relpersistence, "
3955                                                   "NULL AS reloftype, "
3956                                                   "d.refobjid AS owning_tab, "
3957                                                   "d.refobjsubid AS owning_col, "
3958                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3959                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3960                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3961                                                   "FROM pg_class c "
3962                                                   "LEFT JOIN pg_depend d ON "
3963                                                   "(c.relkind = '%c' AND "
3964                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3965                                                   "d.objsubid = 0 AND "
3966                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
3967                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3968                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3969                                                   "ORDER BY c.oid",
3970                                                   username_subquery,
3971                                                   RELKIND_SEQUENCE,
3972                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3973                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3974         }
3975         else if (fout->remoteVersion >= 80200)
3976         {
3977                 /*
3978                  * Left join to pick up dependency info linking sequences to their
3979                  * owning column, if any (note this dependency is AUTO as of 8.2)
3980                  */
3981                 appendPQExpBuffer(query,
3982                                                   "SELECT c.tableoid, c.oid, c.relname, "
3983                                                   "c.relacl, c.relkind, c.relnamespace, "
3984                                                   "(%s c.relowner) AS rolname, "
3985                                                   "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
3986                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3987                                                   "c.relfrozenxid, tc.oid AS toid, "
3988                                                   "tc.relfrozenxid AS tfrozenxid, "
3989                                                   "'p' AS relpersistence, "
3990                                                   "NULL AS reloftype, "
3991                                                   "d.refobjid AS owning_tab, "
3992                                                   "d.refobjsubid AS owning_col, "
3993                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3994                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3995                                                   "NULL AS toast_reloptions "
3996                                                   "FROM pg_class c "
3997                                                   "LEFT JOIN pg_depend d ON "
3998                                                   "(c.relkind = '%c' AND "
3999                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4000                                                   "d.objsubid = 0 AND "
4001                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4002                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4003                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4004                                                   "ORDER BY c.oid",
4005                                                   username_subquery,
4006                                                   RELKIND_SEQUENCE,
4007                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4008                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4009         }
4010         else if (fout->remoteVersion >= 80000)
4011         {
4012                 /*
4013                  * Left join to pick up dependency info linking sequences to their
4014                  * owning column, if any
4015                  */
4016                 appendPQExpBuffer(query,
4017                                                   "SELECT c.tableoid, c.oid, relname, "
4018                                                   "relacl, relkind, relnamespace, "
4019                                                   "(%s relowner) AS rolname, "
4020                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4021                                                   "relhasindex, relhasrules, relhasoids, "
4022                                                   "0 AS relfrozenxid, "
4023                                                   "0 AS toid, "
4024                                                   "0 AS tfrozenxid, "
4025                                                   "'p' AS relpersistence, "
4026                                                   "NULL AS reloftype, "
4027                                                   "d.refobjid AS owning_tab, "
4028                                                   "d.refobjsubid AS owning_col, "
4029                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4030                                                   "NULL AS reloptions, "
4031                                                   "NULL AS toast_reloptions "
4032                                                   "FROM pg_class c "
4033                                                   "LEFT JOIN pg_depend d ON "
4034                                                   "(c.relkind = '%c' AND "
4035                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4036                                                   "d.objsubid = 0 AND "
4037                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4038                                                   "WHERE relkind in ('%c', '%c', '%c', '%c') "
4039                                                   "ORDER BY c.oid",
4040                                                   username_subquery,
4041                                                   RELKIND_SEQUENCE,
4042                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4043                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4044         }
4045         else if (fout->remoteVersion >= 70300)
4046         {
4047                 /*
4048                  * Left join to pick up dependency info linking sequences to their
4049                  * owning column, if any
4050                  */
4051                 appendPQExpBuffer(query,
4052                                                   "SELECT c.tableoid, c.oid, relname, "
4053                                                   "relacl, relkind, relnamespace, "
4054                                                   "(%s relowner) AS rolname, "
4055                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4056                                                   "relhasindex, relhasrules, relhasoids, "
4057                                                   "0 AS relfrozenxid, "
4058                                                   "0 AS toid, "
4059                                                   "0 AS tfrozenxid, "
4060                                                   "'p' AS relpersistence, "
4061                                                   "NULL AS reloftype, "
4062                                                   "d.refobjid AS owning_tab, "
4063                                                   "d.refobjsubid AS owning_col, "
4064                                                   "NULL AS reltablespace, "
4065                                                   "NULL AS reloptions, "
4066                                                   "NULL AS toast_reloptions "
4067                                                   "FROM pg_class c "
4068                                                   "LEFT JOIN pg_depend d ON "
4069                                                   "(c.relkind = '%c' AND "
4070                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4071                                                   "d.objsubid = 0 AND "
4072                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4073                                                   "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4074                                                   "ORDER BY c.oid",
4075                                                   username_subquery,
4076                                                   RELKIND_SEQUENCE,
4077                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4078                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4079         }
4080         else if (fout->remoteVersion >= 70200)
4081         {
4082                 appendPQExpBuffer(query,
4083                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4084                                                   "0::oid AS relnamespace, "
4085                                                   "(%s relowner) AS rolname, "
4086                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4087                                                   "relhasindex, relhasrules, relhasoids, "
4088                                                   "0 AS relfrozenxid, "
4089                                                   "0 AS toid, "
4090                                                   "0 AS tfrozenxid, "
4091                                                   "'p' AS relpersistence, "
4092                                                   "NULL AS reloftype, "
4093                                                   "NULL::oid AS owning_tab, "
4094                                                   "NULL::int4 AS owning_col, "
4095                                                   "NULL AS reltablespace, "
4096                                                   "NULL AS reloptions, "
4097                                                   "NULL AS toast_reloptions "
4098                                                   "FROM pg_class "
4099                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4100                                                   "ORDER BY oid",
4101                                                   username_subquery,
4102                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4103         }
4104         else if (fout->remoteVersion >= 70100)
4105         {
4106                 /* all tables have oids in 7.1 */
4107                 appendPQExpBuffer(query,
4108                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4109                                                   "0::oid AS relnamespace, "
4110                                                   "(%s relowner) AS rolname, "
4111                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4112                                                   "relhasindex, relhasrules, "
4113                                                   "'t'::bool AS relhasoids, "
4114                                                   "0 AS relfrozenxid, "
4115                                                   "0 AS toid, "
4116                                                   "0 AS tfrozenxid, "
4117                                                   "'p' AS relpersistence, "
4118                                                   "NULL AS reloftype, "
4119                                                   "NULL::oid AS owning_tab, "
4120                                                   "NULL::int4 AS owning_col, "
4121                                                   "NULL AS reltablespace, "
4122                                                   "NULL AS reloptions, "
4123                                                   "NULL AS toast_reloptions "
4124                                                   "FROM pg_class "
4125                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4126                                                   "ORDER BY oid",
4127                                                   username_subquery,
4128                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4129         }
4130         else
4131         {
4132                 /*
4133                  * Before 7.1, view relkind was not set to 'v', so we must check if we
4134                  * have a view by looking for a rule in pg_rewrite.
4135                  */
4136                 appendPQExpBuffer(query,
4137                                                   "SELECT "
4138                 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4139                                                   "oid, relname, relacl, "
4140                                                   "CASE WHEN relhasrules and relkind = 'r' "
4141                                           "  and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4142                                           "             r.ev_class = c.oid AND r.ev_type = '1') "
4143                                                   "THEN '%c'::\"char\" "
4144                                                   "ELSE relkind END AS relkind,"
4145                                                   "0::oid AS relnamespace, "
4146                                                   "(%s relowner) AS rolname, "
4147                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4148                                                   "relhasindex, relhasrules, "
4149                                                   "'t'::bool AS relhasoids, "
4150                                                   "0 as relfrozenxid, "
4151                                                   "0 AS toid, "
4152                                                   "0 AS tfrozenxid, "
4153                                                   "'p' AS relpersistence, "
4154                                                   "NULL AS reloftype, "
4155                                                   "NULL::oid AS owning_tab, "
4156                                                   "NULL::int4 AS owning_col, "
4157                                                   "NULL AS reltablespace, "
4158                                                   "NULL AS reloptions, "
4159                                                   "NULL AS toast_reloptions "
4160                                                   "FROM pg_class c "
4161                                                   "WHERE relkind IN ('%c', '%c') "
4162                                                   "ORDER BY oid",
4163                                                   RELKIND_VIEW,
4164                                                   username_subquery,
4165                                                   RELKIND_RELATION, RELKIND_SEQUENCE);
4166         }
4167
4168         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4169
4170         ntups = PQntuples(res);
4171
4172         *numTables = ntups;
4173
4174         /*
4175          * Extract data from result and lock dumpable tables.  We do the locking
4176          * before anything else, to minimize the window wherein a table could
4177          * disappear under us.
4178          *
4179          * Note that we have to save info about all tables here, even when dumping
4180          * only one, because we don't yet know which tables might be inheritance
4181          * ancestors of the target table.
4182          */
4183         tblinfo = (TableInfo *) pg_calloc(ntups, sizeof(TableInfo));
4184
4185         i_reltableoid = PQfnumber(res, "tableoid");
4186         i_reloid = PQfnumber(res, "oid");
4187         i_relname = PQfnumber(res, "relname");
4188         i_relnamespace = PQfnumber(res, "relnamespace");
4189         i_relacl = PQfnumber(res, "relacl");
4190         i_relkind = PQfnumber(res, "relkind");
4191         i_rolname = PQfnumber(res, "rolname");
4192         i_relchecks = PQfnumber(res, "relchecks");
4193         i_relhastriggers = PQfnumber(res, "relhastriggers");
4194         i_relhasindex = PQfnumber(res, "relhasindex");
4195         i_relhasrules = PQfnumber(res, "relhasrules");
4196         i_relhasoids = PQfnumber(res, "relhasoids");
4197         i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4198         i_toastoid = PQfnumber(res, "toid");
4199         i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4200         i_relpersistence = PQfnumber(res, "relpersistence");
4201         i_owning_tab = PQfnumber(res, "owning_tab");
4202         i_owning_col = PQfnumber(res, "owning_col");
4203         i_reltablespace = PQfnumber(res, "reltablespace");
4204         i_reloptions = PQfnumber(res, "reloptions");
4205         i_toastreloptions = PQfnumber(res, "toast_reloptions");
4206         i_reloftype = PQfnumber(res, "reloftype");
4207
4208         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4209         {
4210                 /*
4211                  * Arrange to fail instead of waiting forever for a table lock.
4212                  *
4213                  * NB: this coding assumes that the only queries issued within the
4214                  * following loop are LOCK TABLEs; else the timeout may be undesirably
4215                  * applied to other things too.
4216                  */
4217                 resetPQExpBuffer(query);
4218                 appendPQExpBuffer(query, "SET statement_timeout = ");
4219                 appendStringLiteralConn(query, lockWaitTimeout, GetConnection(fout));
4220                 ExecuteSqlStatement(fout, query->data);
4221         }
4222
4223         for (i = 0; i < ntups; i++)
4224         {
4225                 tblinfo[i].dobj.objType = DO_TABLE;
4226                 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4227                 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4228                 AssignDumpId(&tblinfo[i].dobj);
4229                 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4230                 tblinfo[i].dobj.namespace =
4231                         findNamespace(fout,
4232                                                   atooid(PQgetvalue(res, i, i_relnamespace)),
4233                                                   tblinfo[i].dobj.catId.oid);
4234                 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4235                 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4236                 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4237                 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4238                 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4239                 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4240                 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4241                 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4242                 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4243                 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4244                 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4245                 if (PQgetisnull(res, i, i_reloftype))
4246                         tblinfo[i].reloftype = NULL;
4247                 else
4248                         tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4249                 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4250                 if (PQgetisnull(res, i, i_owning_tab))
4251                 {
4252                         tblinfo[i].owning_tab = InvalidOid;
4253                         tblinfo[i].owning_col = 0;
4254                 }
4255                 else
4256                 {
4257                         tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4258                         tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4259                 }
4260                 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4261                 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4262                 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4263
4264                 /* other fields were zeroed above */
4265
4266                 /*
4267                  * Decide whether we want to dump this table.
4268                  */
4269                 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4270                         tblinfo[i].dobj.dump = false;
4271                 else
4272                         selectDumpableTable(&tblinfo[i]);
4273                 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4274
4275                 /*
4276                  * Read-lock target tables to make sure they aren't DROPPED or altered
4277                  * in schema before we get around to dumping them.
4278                  *
4279                  * Note that we don't explicitly lock parents of the target tables; we
4280                  * assume our lock on the child is enough to prevent schema
4281                  * alterations to parent tables.
4282                  *
4283                  * NOTE: it'd be kinda nice to lock other relations too, not only
4284                  * plain tables, but the backend doesn't presently allow that.
4285                  */
4286                 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4287                 {
4288                         resetPQExpBuffer(query);
4289                         appendPQExpBuffer(query,
4290                                                           "LOCK TABLE %s IN ACCESS SHARE MODE",
4291                                                  fmtQualifiedId(fout,
4292                                                                                 tblinfo[i].dobj.namespace->dobj.name,
4293                                                                                 tblinfo[i].dobj.name));
4294                         ExecuteSqlStatement(fout, query->data);
4295                 }
4296
4297                 /* Emit notice if join for owner failed */
4298                 if (strlen(tblinfo[i].rolname) == 0)
4299                         write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4300                                           tblinfo[i].dobj.name);
4301         }
4302
4303         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4304         {
4305                 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4306         }
4307
4308         PQclear(res);
4309
4310         destroyPQExpBuffer(query);
4311
4312         return tblinfo;
4313 }
4314
4315 /*
4316  * getOwnedSeqs
4317  *        identify owned sequences and mark them as dumpable if owning table is
4318  *
4319  * We used to do this in getTables(), but it's better to do it after the
4320  * index used by findTableByOid() has been set up.
4321  */
4322 void
4323 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
4324 {
4325         int                     i;
4326
4327         /*
4328          * Force sequences that are "owned" by table columns to be dumped whenever
4329          * their owning table is being dumped.
4330          */
4331         for (i = 0; i < numTables; i++)
4332         {
4333                 TableInfo  *seqinfo = &tblinfo[i];
4334                 TableInfo  *owning_tab;
4335
4336                 if (!OidIsValid(seqinfo->owning_tab))
4337                         continue;                       /* not an owned sequence */
4338                 if (seqinfo->dobj.dump)
4339                         continue;                       /* no need to search */
4340                 owning_tab = findTableByOid(seqinfo->owning_tab);
4341                 if (owning_tab && owning_tab->dobj.dump)
4342                 {
4343                         seqinfo->interesting = true;
4344                         seqinfo->dobj.dump = true;
4345                 }
4346         }
4347 }
4348
4349 /*
4350  * getInherits
4351  *        read all the inheritance information
4352  * from the system catalogs return them in the InhInfo* structure
4353  *
4354  * numInherits is set to the number of pairs read in
4355  */
4356 InhInfo *
4357 getInherits(Archive *fout, int *numInherits)
4358 {
4359         PGresult   *res;
4360         int                     ntups;
4361         int                     i;
4362         PQExpBuffer query = createPQExpBuffer();
4363         InhInfo    *inhinfo;
4364
4365         int                     i_inhrelid;
4366         int                     i_inhparent;
4367
4368         /* Make sure we are in proper schema */
4369         selectSourceSchema(fout, "pg_catalog");
4370
4371         /* find all the inheritance information */
4372
4373         appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4374
4375         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4376
4377         ntups = PQntuples(res);
4378
4379         *numInherits = ntups;
4380
4381         inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4382
4383         i_inhrelid = PQfnumber(res, "inhrelid");
4384         i_inhparent = PQfnumber(res, "inhparent");
4385
4386         for (i = 0; i < ntups; i++)
4387         {
4388                 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4389                 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4390         }
4391
4392         PQclear(res);
4393
4394         destroyPQExpBuffer(query);
4395
4396         return inhinfo;
4397 }
4398
4399 /*
4400  * getIndexes
4401  *        get information about every index on a dumpable table
4402  *
4403  * Note: index data is not returned directly to the caller, but it
4404  * does get entered into the DumpableObject tables.
4405  */
4406 void
4407 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4408 {
4409         int                     i,
4410                                 j;
4411         PQExpBuffer query = createPQExpBuffer();
4412         PGresult   *res;
4413         IndxInfo   *indxinfo;
4414         ConstraintInfo *constrinfo;
4415         int                     i_tableoid,
4416                                 i_oid,
4417                                 i_indexname,
4418                                 i_indexdef,
4419                                 i_indnkeys,
4420                                 i_indkey,
4421                                 i_indisclustered,
4422                                 i_contype,
4423                                 i_conname,
4424                                 i_condeferrable,
4425                                 i_condeferred,
4426                                 i_contableoid,
4427                                 i_conoid,
4428                                 i_condef,
4429                                 i_tablespace,
4430                                 i_options;
4431         int                     ntups;
4432
4433         for (i = 0; i < numTables; i++)
4434         {
4435                 TableInfo  *tbinfo = &tblinfo[i];
4436
4437                 /* Only plain tables have indexes */
4438                 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
4439                         continue;
4440
4441                 /* Ignore indexes of tables not to be dumped */
4442                 if (!tbinfo->dobj.dump)
4443                         continue;
4444
4445                 if (g_verbose)
4446                         write_msg(NULL, "reading indexes for table \"%s\"\n",
4447                                           tbinfo->dobj.name);
4448
4449                 /* Make sure we are in proper schema so indexdef is right */
4450                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4451
4452                 /*
4453                  * The point of the messy-looking outer join is to find a constraint
4454                  * that is related by an internal dependency link to the index. If we
4455                  * find one, create a CONSTRAINT entry linked to the INDEX entry.  We
4456                  * assume an index won't have more than one internal dependency.
4457                  *
4458                  * As of 9.0 we don't need to look at pg_depend but can check for a
4459                  * match to pg_constraint.conindid.  The check on conrelid is
4460                  * redundant but useful because that column is indexed while conindid
4461                  * is not.
4462                  */
4463                 resetPQExpBuffer(query);
4464                 if (fout->remoteVersion >= 90000)
4465                 {
4466                         appendPQExpBuffer(query,
4467                                                           "SELECT t.tableoid, t.oid, "
4468                                                           "t.relname AS indexname, "
4469                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4470                                                           "t.relnatts AS indnkeys, "
4471                                                           "i.indkey, i.indisclustered, "
4472                                                           "c.contype, c.conname, "
4473                                                           "c.condeferrable, c.condeferred, "
4474                                                           "c.tableoid AS contableoid, "
4475                                                           "c.oid AS conoid, "
4476                                   "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4477                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4478                                                         "array_to_string(t.reloptions, ', ') AS options "
4479                                                           "FROM pg_catalog.pg_index i "
4480                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4481                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4482                                                           "ON (i.indrelid = c.conrelid AND "
4483                                                           "i.indexrelid = c.conindid AND "
4484                                                           "c.contype IN ('p','u','x')) "
4485                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4486                                                           "ORDER BY indexname",
4487                                                           tbinfo->dobj.catId.oid);
4488                 }
4489                 else if (fout->remoteVersion >= 80200)
4490                 {
4491                         appendPQExpBuffer(query,
4492                                                           "SELECT t.tableoid, t.oid, "
4493                                                           "t.relname AS indexname, "
4494                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4495                                                           "t.relnatts AS indnkeys, "
4496                                                           "i.indkey, i.indisclustered, "
4497                                                           "c.contype, c.conname, "
4498                                                           "c.condeferrable, c.condeferred, "
4499                                                           "c.tableoid AS contableoid, "
4500                                                           "c.oid AS conoid, "
4501                                                           "null AS condef, "
4502                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4503                                                         "array_to_string(t.reloptions, ', ') AS options "
4504                                                           "FROM pg_catalog.pg_index i "
4505                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4506                                                           "LEFT JOIN pg_catalog.pg_depend d "
4507                                                           "ON (d.classid = t.tableoid "
4508                                                           "AND d.objid = t.oid "
4509                                                           "AND d.deptype = 'i') "
4510                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4511                                                           "ON (d.refclassid = c.tableoid "
4512                                                           "AND d.refobjid = c.oid) "
4513                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4514                                                           "ORDER BY indexname",
4515                                                           tbinfo->dobj.catId.oid);
4516                 }
4517                 else if (fout->remoteVersion >= 80000)
4518                 {
4519                         appendPQExpBuffer(query,
4520                                                           "SELECT t.tableoid, t.oid, "
4521                                                           "t.relname AS indexname, "
4522                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4523                                                           "t.relnatts AS indnkeys, "
4524                                                           "i.indkey, i.indisclustered, "
4525                                                           "c.contype, c.conname, "
4526                                                           "c.condeferrable, c.condeferred, "
4527                                                           "c.tableoid AS contableoid, "
4528                                                           "c.oid AS conoid, "
4529                                                           "null AS condef, "
4530                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4531                                                           "null AS options "
4532                                                           "FROM pg_catalog.pg_index i "
4533                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4534                                                           "LEFT JOIN pg_catalog.pg_depend d "
4535                                                           "ON (d.classid = t.tableoid "
4536                                                           "AND d.objid = t.oid "
4537                                                           "AND d.deptype = 'i') "
4538                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4539                                                           "ON (d.refclassid = c.tableoid "
4540                                                           "AND d.refobjid = c.oid) "
4541                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4542                                                           "ORDER BY indexname",
4543                                                           tbinfo->dobj.catId.oid);
4544                 }
4545                 else if (fout->remoteVersion >= 70300)
4546                 {
4547                         appendPQExpBuffer(query,
4548                                                           "SELECT t.tableoid, t.oid, "
4549                                                           "t.relname AS indexname, "
4550                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4551                                                           "t.relnatts AS indnkeys, "
4552                                                           "i.indkey, i.indisclustered, "
4553                                                           "c.contype, c.conname, "
4554                                                           "c.condeferrable, c.condeferred, "
4555                                                           "c.tableoid AS contableoid, "
4556                                                           "c.oid AS conoid, "
4557                                                           "null AS condef, "
4558                                                           "NULL AS tablespace, "
4559                                                           "null AS options "
4560                                                           "FROM pg_catalog.pg_index i "
4561                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4562                                                           "LEFT JOIN pg_catalog.pg_depend d "
4563                                                           "ON (d.classid = t.tableoid "
4564                                                           "AND d.objid = t.oid "
4565                                                           "AND d.deptype = 'i') "
4566                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4567                                                           "ON (d.refclassid = c.tableoid "
4568                                                           "AND d.refobjid = c.oid) "
4569                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4570                                                           "ORDER BY indexname",
4571                                                           tbinfo->dobj.catId.oid);
4572                 }
4573                 else if (fout->remoteVersion >= 70100)
4574                 {
4575                         appendPQExpBuffer(query,
4576                                                           "SELECT t.tableoid, t.oid, "
4577                                                           "t.relname AS indexname, "
4578                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
4579                                                           "t.relnatts AS indnkeys, "
4580                                                           "i.indkey, false AS indisclustered, "
4581                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
4582                                                           "ELSE '0'::char END AS contype, "
4583                                                           "t.relname AS conname, "
4584                                                           "false AS condeferrable, "
4585                                                           "false AS condeferred, "
4586                                                           "0::oid AS contableoid, "
4587                                                           "t.oid AS conoid, "
4588                                                           "null AS condef, "
4589                                                           "NULL AS tablespace, "
4590                                                           "null AS options "
4591                                                           "FROM pg_index i, pg_class t "
4592                                                           "WHERE t.oid = i.indexrelid "
4593                                                           "AND i.indrelid = '%u'::oid "
4594                                                           "ORDER BY indexname",
4595                                                           tbinfo->dobj.catId.oid);
4596                 }
4597                 else
4598                 {
4599                         appendPQExpBuffer(query,
4600                                                           "SELECT "
4601                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4602                                                           "t.oid, "
4603                                                           "t.relname AS indexname, "
4604                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
4605                                                           "t.relnatts AS indnkeys, "
4606                                                           "i.indkey, false AS indisclustered, "
4607                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
4608                                                           "ELSE '0'::char END AS contype, "
4609                                                           "t.relname AS conname, "
4610                                                           "false AS condeferrable, "
4611                                                           "false AS condeferred, "
4612                                                           "0::oid AS contableoid, "
4613                                                           "t.oid AS conoid, "
4614                                                           "null AS condef, "
4615                                                           "NULL AS tablespace, "
4616                                                           "null AS options "
4617                                                           "FROM pg_index i, pg_class t "
4618                                                           "WHERE t.oid = i.indexrelid "
4619                                                           "AND i.indrelid = '%u'::oid "
4620                                                           "ORDER BY indexname",
4621                                                           tbinfo->dobj.catId.oid);
4622                 }
4623
4624                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4625
4626                 ntups = PQntuples(res);
4627
4628                 i_tableoid = PQfnumber(res, "tableoid");
4629                 i_oid = PQfnumber(res, "oid");
4630                 i_indexname = PQfnumber(res, "indexname");
4631                 i_indexdef = PQfnumber(res, "indexdef");
4632                 i_indnkeys = PQfnumber(res, "indnkeys");
4633                 i_indkey = PQfnumber(res, "indkey");
4634                 i_indisclustered = PQfnumber(res, "indisclustered");
4635                 i_contype = PQfnumber(res, "contype");
4636                 i_conname = PQfnumber(res, "conname");
4637                 i_condeferrable = PQfnumber(res, "condeferrable");
4638                 i_condeferred = PQfnumber(res, "condeferred");
4639                 i_contableoid = PQfnumber(res, "contableoid");
4640                 i_conoid = PQfnumber(res, "conoid");
4641                 i_condef = PQfnumber(res, "condef");
4642                 i_tablespace = PQfnumber(res, "tablespace");
4643                 i_options = PQfnumber(res, "options");
4644
4645                 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
4646                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4647
4648                 for (j = 0; j < ntups; j++)
4649                 {
4650                         char            contype;
4651
4652                         indxinfo[j].dobj.objType = DO_INDEX;
4653                         indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4654                         indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4655                         AssignDumpId(&indxinfo[j].dobj);
4656                         indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
4657                         indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4658                         indxinfo[j].indextable = tbinfo;
4659                         indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
4660                         indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4661                         indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
4662                         indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
4663
4664                         /*
4665                          * In pre-7.4 releases, indkeys may contain more entries than
4666                          * indnkeys says (since indnkeys will be 1 for a functional
4667                          * index).      We don't actually care about this case since we don't
4668                          * examine indkeys except for indexes associated with PRIMARY and
4669                          * UNIQUE constraints, which are never functional indexes. But we
4670                          * have to allocate enough space to keep parseOidArray from
4671                          * complaining.
4672                          */
4673                         indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
4674                         parseOidArray(PQgetvalue(res, j, i_indkey),
4675                                                   indxinfo[j].indkeys, INDEX_MAX_KEYS);
4676                         indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4677                         contype = *(PQgetvalue(res, j, i_contype));
4678
4679                         if (contype == 'p' || contype == 'u' || contype == 'x')
4680                         {
4681                                 /*
4682                                  * If we found a constraint matching the index, create an
4683                                  * entry for it.
4684                                  *
4685                                  * In a pre-7.3 database, we take this path iff the index was
4686                                  * marked indisprimary.
4687                                  */
4688                                 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4689                                 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4690                                 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4691                                 AssignDumpId(&constrinfo[j].dobj);
4692                                 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4693                                 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4694                                 constrinfo[j].contable = tbinfo;
4695                                 constrinfo[j].condomain = NULL;
4696                                 constrinfo[j].contype = contype;
4697                                 if (contype == 'x')
4698                                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4699                                 else
4700                                         constrinfo[j].condef = NULL;
4701                                 constrinfo[j].confrelid = InvalidOid;
4702                                 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4703                                 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4704                                 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4705                                 constrinfo[j].conislocal = true;
4706                                 constrinfo[j].separate = true;
4707
4708                                 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4709
4710                                 /* If pre-7.3 DB, better make sure table comes first */
4711                                 addObjectDependency(&constrinfo[j].dobj,
4712                                                                         tbinfo->dobj.dumpId);
4713                         }
4714                         else
4715                         {
4716                                 /* Plain secondary index */
4717                                 indxinfo[j].indexconstraint = 0;
4718                         }
4719                 }
4720
4721                 PQclear(res);
4722         }
4723
4724         destroyPQExpBuffer(query);
4725 }
4726
4727 /*
4728  * getConstraints
4729  *
4730  * Get info about constraints on dumpable tables.
4731  *
4732  * Currently handles foreign keys only.
4733  * Unique and primary key constraints are handled with indexes,
4734  * while check constraints are processed in getTableAttrs().
4735  */
4736 void
4737 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
4738 {
4739         int                     i,
4740                                 j;
4741         ConstraintInfo *constrinfo;
4742         PQExpBuffer query;
4743         PGresult   *res;
4744         int                     i_contableoid,
4745                                 i_conoid,
4746                                 i_conname,
4747                                 i_confrelid,
4748                                 i_condef;
4749         int                     ntups;
4750
4751         /* pg_constraint was created in 7.3, so nothing to do if older */
4752         if (fout->remoteVersion < 70300)
4753                 return;
4754
4755         query = createPQExpBuffer();
4756
4757         for (i = 0; i < numTables; i++)
4758         {
4759                 TableInfo  *tbinfo = &tblinfo[i];
4760
4761                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4762                         continue;
4763
4764                 if (g_verbose)
4765                         write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
4766                                           tbinfo->dobj.name);
4767
4768                 /*
4769                  * select table schema to ensure constraint expr is qualified if
4770                  * needed
4771                  */
4772                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4773
4774                 resetPQExpBuffer(query);
4775                 appendPQExpBuffer(query,
4776                                                   "SELECT tableoid, oid, conname, confrelid, "
4777                                                   "pg_catalog.pg_get_constraintdef(oid) AS condef "
4778                                                   "FROM pg_catalog.pg_constraint "
4779                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
4780                                                   "AND contype = 'f'",
4781                                                   tbinfo->dobj.catId.oid);
4782                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4783
4784                 ntups = PQntuples(res);
4785
4786                 i_contableoid = PQfnumber(res, "tableoid");
4787                 i_conoid = PQfnumber(res, "oid");
4788                 i_conname = PQfnumber(res, "conname");
4789                 i_confrelid = PQfnumber(res, "confrelid");
4790                 i_condef = PQfnumber(res, "condef");
4791
4792                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4793
4794                 for (j = 0; j < ntups; j++)
4795                 {
4796                         constrinfo[j].dobj.objType = DO_FK_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 = 'f';
4805                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4806                         constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
4807                         constrinfo[j].conindex = 0;
4808                         constrinfo[j].condeferrable = false;
4809                         constrinfo[j].condeferred = false;
4810                         constrinfo[j].conislocal = true;
4811                         constrinfo[j].separate = true;
4812                 }
4813
4814                 PQclear(res);
4815         }
4816
4817         destroyPQExpBuffer(query);
4818 }
4819
4820 /*
4821  * getDomainConstraints
4822  *
4823  * Get info about constraints on a domain.
4824  */
4825 static void
4826 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
4827 {
4828         int                     i;
4829         ConstraintInfo *constrinfo;
4830         PQExpBuffer query;
4831         PGresult   *res;
4832         int                     i_tableoid,
4833                                 i_oid,
4834                                 i_conname,
4835                                 i_consrc;
4836         int                     ntups;
4837
4838         /* pg_constraint was created in 7.3, so nothing to do if older */
4839         if (fout->remoteVersion < 70300)
4840                 return;
4841
4842         /*
4843          * select appropriate schema to ensure names in constraint are properly
4844          * qualified
4845          */
4846         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
4847
4848         query = createPQExpBuffer();
4849
4850         if (fout->remoteVersion >= 90100)
4851                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4852                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4853                                                   "convalidated "
4854                                                   "FROM pg_catalog.pg_constraint "
4855                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4856                                                   "ORDER BY conname",
4857                                                   tyinfo->dobj.catId.oid);
4858
4859         else if (fout->remoteVersion >= 70400)
4860                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4861                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4862                                                   "true as convalidated "
4863                                                   "FROM pg_catalog.pg_constraint "
4864                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4865                                                   "ORDER BY conname",
4866                                                   tyinfo->dobj.catId.oid);
4867         else
4868                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4869                                                   "'CHECK (' || consrc || ')' AS consrc, "
4870                                                   "true as convalidated "
4871                                                   "FROM pg_catalog.pg_constraint "
4872                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4873                                                   "ORDER BY conname",
4874                                                   tyinfo->dobj.catId.oid);
4875
4876         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4877
4878         ntups = PQntuples(res);
4879
4880         i_tableoid = PQfnumber(res, "tableoid");
4881         i_oid = PQfnumber(res, "oid");
4882         i_conname = PQfnumber(res, "conname");
4883         i_consrc = PQfnumber(res, "consrc");
4884
4885         constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4886
4887         tyinfo->nDomChecks = ntups;
4888         tyinfo->domChecks = constrinfo;
4889
4890         for (i = 0; i < ntups; i++)
4891         {
4892                 bool    validated = PQgetvalue(res, i, 4)[0] == 't';
4893
4894                 constrinfo[i].dobj.objType = DO_CONSTRAINT;
4895                 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4896                 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4897                 AssignDumpId(&constrinfo[i].dobj);
4898                 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
4899                 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
4900                 constrinfo[i].contable = NULL;
4901                 constrinfo[i].condomain = tyinfo;
4902                 constrinfo[i].contype = 'c';
4903                 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
4904                 constrinfo[i].confrelid = InvalidOid;
4905                 constrinfo[i].conindex = 0;
4906                 constrinfo[i].condeferrable = false;
4907                 constrinfo[i].condeferred = false;
4908                 constrinfo[i].conislocal = true;
4909
4910                 constrinfo[i].separate = !validated;
4911
4912                 /*
4913                  * Make the domain depend on the constraint, ensuring it won't be
4914                  * output till any constraint dependencies are OK.  If the constraint
4915                  * has not been validated, it's going to be dumped after the domain
4916                  * anyway, so this doesn't matter.
4917                  */
4918                 if (validated)
4919                         addObjectDependency(&tyinfo->dobj,
4920                                                                 constrinfo[i].dobj.dumpId);
4921         }
4922
4923         PQclear(res);
4924
4925         destroyPQExpBuffer(query);
4926 }
4927
4928 /*
4929  * getRules
4930  *        get basic information about every rule in the system
4931  *
4932  * numRules is set to the number of rules read in
4933  */
4934 RuleInfo *
4935 getRules(Archive *fout, int *numRules)
4936 {
4937         PGresult   *res;
4938         int                     ntups;
4939         int                     i;
4940         PQExpBuffer query = createPQExpBuffer();
4941         RuleInfo   *ruleinfo;
4942         int                     i_tableoid;
4943         int                     i_oid;
4944         int                     i_rulename;
4945         int                     i_ruletable;
4946         int                     i_ev_type;
4947         int                     i_is_instead;
4948         int                     i_ev_enabled;
4949
4950         /* Make sure we are in proper schema */
4951         selectSourceSchema(fout, "pg_catalog");
4952
4953         if (fout->remoteVersion >= 80300)
4954         {
4955                 appendPQExpBuffer(query, "SELECT "
4956                                                   "tableoid, oid, rulename, "
4957                                                   "ev_class AS ruletable, ev_type, is_instead, "
4958                                                   "ev_enabled "
4959                                                   "FROM pg_rewrite "
4960                                                   "ORDER BY oid");
4961         }
4962         else if (fout->remoteVersion >= 70100)
4963         {
4964                 appendPQExpBuffer(query, "SELECT "
4965                                                   "tableoid, oid, rulename, "
4966                                                   "ev_class AS ruletable, ev_type, is_instead, "
4967                                                   "'O'::char AS ev_enabled "
4968                                                   "FROM pg_rewrite "
4969                                                   "ORDER BY oid");
4970         }
4971         else
4972         {
4973                 appendPQExpBuffer(query, "SELECT "
4974                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
4975                                                   "oid, rulename, "
4976                                                   "ev_class AS ruletable, ev_type, is_instead, "
4977                                                   "'O'::char AS ev_enabled "
4978                                                   "FROM pg_rewrite "
4979                                                   "ORDER BY oid");
4980         }
4981
4982         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4983
4984         ntups = PQntuples(res);
4985
4986         *numRules = ntups;
4987
4988         ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
4989
4990         i_tableoid = PQfnumber(res, "tableoid");
4991         i_oid = PQfnumber(res, "oid");
4992         i_rulename = PQfnumber(res, "rulename");
4993         i_ruletable = PQfnumber(res, "ruletable");
4994         i_ev_type = PQfnumber(res, "ev_type");
4995         i_is_instead = PQfnumber(res, "is_instead");
4996         i_ev_enabled = PQfnumber(res, "ev_enabled");
4997
4998         for (i = 0; i < ntups; i++)
4999         {
5000                 Oid                     ruletableoid;
5001
5002                 ruleinfo[i].dobj.objType = DO_RULE;
5003                 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5004                 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5005                 AssignDumpId(&ruleinfo[i].dobj);
5006                 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5007                 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5008                 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5009                 if (ruleinfo[i].ruletable == NULL)
5010                         exit_horribly(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5011                                                   ruletableoid, ruleinfo[i].dobj.catId.oid);
5012                 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5013                 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5014                 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5015                 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5016                 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5017                 if (ruleinfo[i].ruletable)
5018                 {
5019                         /*
5020                          * If the table is a view, force its ON SELECT rule to be sorted
5021                          * before the view itself --- this ensures that any dependencies
5022                          * for the rule affect the table's positioning. Other rules are
5023                          * forced to appear after their table.
5024                          */
5025                         if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
5026                                 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5027                         {
5028                                 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5029                                                                         ruleinfo[i].dobj.dumpId);
5030                                 /* We'll merge the rule into CREATE VIEW, if possible */
5031                                 ruleinfo[i].separate = false;
5032                         }
5033                         else
5034                         {
5035                                 addObjectDependency(&ruleinfo[i].dobj,
5036                                                                         ruleinfo[i].ruletable->dobj.dumpId);
5037                                 ruleinfo[i].separate = true;
5038                         }
5039                 }
5040                 else
5041                         ruleinfo[i].separate = true;
5042         }
5043
5044         PQclear(res);
5045
5046         destroyPQExpBuffer(query);
5047
5048         return ruleinfo;
5049 }
5050
5051 /*
5052  * getTriggers
5053  *        get information about every trigger on a dumpable table
5054  *
5055  * Note: trigger data is not returned directly to the caller, but it
5056  * does get entered into the DumpableObject tables.
5057  */
5058 void
5059 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5060 {
5061         int                     i,
5062                                 j;
5063         PQExpBuffer query = createPQExpBuffer();
5064         PGresult   *res;
5065         TriggerInfo *tginfo;
5066         int                     i_tableoid,
5067                                 i_oid,
5068                                 i_tgname,
5069                                 i_tgfname,
5070                                 i_tgtype,
5071                                 i_tgnargs,
5072                                 i_tgargs,
5073                                 i_tgisconstraint,
5074                                 i_tgconstrname,
5075                                 i_tgconstrrelid,
5076                                 i_tgconstrrelname,
5077                                 i_tgenabled,
5078                                 i_tgdeferrable,
5079                                 i_tginitdeferred,
5080                                 i_tgdef;
5081         int                     ntups;
5082
5083         for (i = 0; i < numTables; i++)
5084         {
5085                 TableInfo  *tbinfo = &tblinfo[i];
5086
5087                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5088                         continue;
5089
5090                 if (g_verbose)
5091                         write_msg(NULL, "reading triggers for table \"%s\"\n",
5092                                           tbinfo->dobj.name);
5093
5094                 /*
5095                  * select table schema to ensure regproc name is qualified if needed
5096                  */
5097                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5098
5099                 resetPQExpBuffer(query);
5100                 if (fout->remoteVersion >= 90000)
5101                 {
5102                         /*
5103                          * NB: think not to use pretty=true in pg_get_triggerdef.  It
5104                          * could result in non-forward-compatible dumps of WHEN clauses
5105                          * due to under-parenthesization.
5106                          */
5107                         appendPQExpBuffer(query,
5108                                                           "SELECT tgname, "
5109                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5110                                                 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5111                                                           "tgenabled, tableoid, oid "
5112                                                           "FROM pg_catalog.pg_trigger t "
5113                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5114                                                           "AND NOT tgisinternal",
5115                                                           tbinfo->dobj.catId.oid);
5116                 }
5117                 else if (fout->remoteVersion >= 80300)
5118                 {
5119                         /*
5120                          * We ignore triggers that are tied to a foreign-key constraint
5121                          */
5122                         appendPQExpBuffer(query,
5123                                                           "SELECT tgname, "
5124                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5125                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5126                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5127                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5128                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5129                                                           "FROM pg_catalog.pg_trigger t "
5130                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5131                                                           "AND tgconstraint = 0",
5132                                                           tbinfo->dobj.catId.oid);
5133                 }
5134                 else if (fout->remoteVersion >= 70300)
5135                 {
5136                         /*
5137                          * We ignore triggers that are tied to a foreign-key constraint,
5138                          * but in these versions we have to grovel through pg_constraint
5139                          * to find out
5140                          */
5141                         appendPQExpBuffer(query,
5142                                                           "SELECT tgname, "
5143                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5144                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5145                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5146                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5147                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5148                                                           "FROM pg_catalog.pg_trigger t "
5149                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5150                                                           "AND (NOT tgisconstraint "
5151                                                           " OR NOT EXISTS"
5152                                                           "  (SELECT 1 FROM pg_catalog.pg_depend d "
5153                                                           "   JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5154                                                           "   WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5155                                                           tbinfo->dobj.catId.oid);
5156                 }
5157                 else if (fout->remoteVersion >= 70100)
5158                 {
5159                         appendPQExpBuffer(query,
5160                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5161                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5162                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5163                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5164                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5165                                                           "             AS tgconstrrelname "
5166                                                           "FROM pg_trigger "
5167                                                           "WHERE tgrelid = '%u'::oid",
5168                                                           tbinfo->dobj.catId.oid);
5169                 }
5170                 else
5171                 {
5172                         appendPQExpBuffer(query,
5173                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5174                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5175                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5176                                                           "tgconstrrelid, tginitdeferred, "
5177                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5178                                                           "oid, "
5179                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5180                                                           "             AS tgconstrrelname "
5181                                                           "FROM pg_trigger "
5182                                                           "WHERE tgrelid = '%u'::oid",
5183                                                           tbinfo->dobj.catId.oid);
5184                 }
5185                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5186
5187                 ntups = PQntuples(res);
5188
5189                 i_tableoid = PQfnumber(res, "tableoid");
5190                 i_oid = PQfnumber(res, "oid");
5191                 i_tgname = PQfnumber(res, "tgname");
5192                 i_tgfname = PQfnumber(res, "tgfname");
5193                 i_tgtype = PQfnumber(res, "tgtype");
5194                 i_tgnargs = PQfnumber(res, "tgnargs");
5195                 i_tgargs = PQfnumber(res, "tgargs");
5196                 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5197                 i_tgconstrname = PQfnumber(res, "tgconstrname");
5198                 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5199                 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5200                 i_tgenabled = PQfnumber(res, "tgenabled");
5201                 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5202                 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5203                 i_tgdef = PQfnumber(res, "tgdef");
5204
5205                 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5206
5207                 for (j = 0; j < ntups; j++)
5208                 {
5209                         tginfo[j].dobj.objType = DO_TRIGGER;
5210                         tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5211                         tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5212                         AssignDumpId(&tginfo[j].dobj);
5213                         tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5214                         tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5215                         tginfo[j].tgtable = tbinfo;
5216                         tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5217                         if (i_tgdef >= 0)
5218                         {
5219                                 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5220
5221                                 /* remaining fields are not valid if we have tgdef */
5222                                 tginfo[j].tgfname = NULL;
5223                                 tginfo[j].tgtype = 0;
5224                                 tginfo[j].tgnargs = 0;
5225                                 tginfo[j].tgargs = NULL;
5226                                 tginfo[j].tgisconstraint = false;
5227                                 tginfo[j].tgdeferrable = false;
5228                                 tginfo[j].tginitdeferred = false;
5229                                 tginfo[j].tgconstrname = NULL;
5230                                 tginfo[j].tgconstrrelid = InvalidOid;
5231                                 tginfo[j].tgconstrrelname = NULL;
5232                         }
5233                         else
5234                         {
5235                                 tginfo[j].tgdef = NULL;
5236
5237                                 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5238                                 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5239                                 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5240                                 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5241                                 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5242                                 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5243                                 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5244
5245                                 if (tginfo[j].tgisconstraint)
5246                                 {
5247                                         tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5248                                         tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5249                                         if (OidIsValid(tginfo[j].tgconstrrelid))
5250                                         {
5251                                                 if (PQgetisnull(res, j, i_tgconstrrelname))
5252                                                         exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5253                                                                                   tginfo[j].dobj.name,
5254                                                                                   tbinfo->dobj.name,
5255                                                                                   tginfo[j].tgconstrrelid);
5256                                                 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5257                                         }
5258                                         else
5259                                                 tginfo[j].tgconstrrelname = NULL;
5260                                 }
5261                                 else
5262                                 {
5263                                         tginfo[j].tgconstrname = NULL;
5264                                         tginfo[j].tgconstrrelid = InvalidOid;
5265                                         tginfo[j].tgconstrrelname = NULL;
5266                                 }
5267                         }
5268                 }
5269
5270                 PQclear(res);
5271         }
5272
5273         destroyPQExpBuffer(query);
5274 }
5275
5276 /*
5277  * getProcLangs
5278  *        get basic information about every procedural language in the system
5279  *
5280  * numProcLangs is set to the number of langs read in
5281  *
5282  * NB: this must run after getFuncs() because we assume we can do
5283  * findFuncByOid().
5284  */
5285 ProcLangInfo *
5286 getProcLangs(Archive *fout, int *numProcLangs)
5287 {
5288         PGresult   *res;
5289         int                     ntups;
5290         int                     i;
5291         PQExpBuffer query = createPQExpBuffer();
5292         ProcLangInfo *planginfo;
5293         int                     i_tableoid;
5294         int                     i_oid;
5295         int                     i_lanname;
5296         int                     i_lanpltrusted;
5297         int                     i_lanplcallfoid;
5298         int                     i_laninline;
5299         int                     i_lanvalidator;
5300         int                     i_lanacl;
5301         int                     i_lanowner;
5302
5303         /* Make sure we are in proper schema */
5304         selectSourceSchema(fout, "pg_catalog");
5305
5306         if (fout->remoteVersion >= 90000)
5307         {
5308                 /* pg_language has a laninline column */
5309                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5310                                                   "lanname, lanpltrusted, lanplcallfoid, "
5311                                                   "laninline, lanvalidator,  lanacl, "
5312                                                   "(%s lanowner) AS lanowner "
5313                                                   "FROM pg_language "
5314                                                   "WHERE lanispl "
5315                                                   "ORDER BY oid",
5316                                                   username_subquery);
5317         }
5318         else if (fout->remoteVersion >= 80300)
5319         {
5320                 /* pg_language has a lanowner column */
5321                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5322                                                   "lanname, lanpltrusted, lanplcallfoid, "
5323                                                   "lanvalidator,  lanacl, "
5324                                                   "(%s lanowner) AS lanowner "
5325                                                   "FROM pg_language "
5326                                                   "WHERE lanispl "
5327                                                   "ORDER BY oid",
5328                                                   username_subquery);
5329         }
5330         else if (fout->remoteVersion >= 80100)
5331         {
5332                 /* Languages are owned by the bootstrap superuser, OID 10 */
5333                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5334                                                   "(%s '10') AS lanowner "
5335                                                   "FROM pg_language "
5336                                                   "WHERE lanispl "
5337                                                   "ORDER BY oid",
5338                                                   username_subquery);
5339         }
5340         else if (fout->remoteVersion >= 70400)
5341         {
5342                 /* Languages are owned by the bootstrap superuser, sysid 1 */
5343                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5344                                                   "(%s '1') AS lanowner "
5345                                                   "FROM pg_language "
5346                                                   "WHERE lanispl "
5347                                                   "ORDER BY oid",
5348                                                   username_subquery);
5349         }
5350         else if (fout->remoteVersion >= 70100)
5351         {
5352                 /* No clear notion of an owner at all before 7.4 ... */
5353                 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5354                                                   "WHERE lanispl "
5355                                                   "ORDER BY oid");
5356         }
5357         else
5358         {
5359                 appendPQExpBuffer(query, "SELECT "
5360                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5361                                                   "oid, * FROM pg_language "
5362                                                   "WHERE lanispl "
5363                                                   "ORDER BY oid");
5364         }
5365
5366         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5367
5368         ntups = PQntuples(res);
5369
5370         *numProcLangs = ntups;
5371
5372         planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5373
5374         i_tableoid = PQfnumber(res, "tableoid");
5375         i_oid = PQfnumber(res, "oid");
5376         i_lanname = PQfnumber(res, "lanname");
5377         i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5378         i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5379         /* these may fail and return -1: */
5380         i_laninline = PQfnumber(res, "laninline");
5381         i_lanvalidator = PQfnumber(res, "lanvalidator");
5382         i_lanacl = PQfnumber(res, "lanacl");
5383         i_lanowner = PQfnumber(res, "lanowner");
5384
5385         for (i = 0; i < ntups; i++)
5386         {
5387                 planginfo[i].dobj.objType = DO_PROCLANG;
5388                 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5389                 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5390                 AssignDumpId(&planginfo[i].dobj);
5391
5392                 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5393                 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5394                 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5395                 if (i_laninline >= 0)
5396                         planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5397                 else
5398                         planginfo[i].laninline = InvalidOid;
5399                 if (i_lanvalidator >= 0)
5400                         planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5401                 else
5402                         planginfo[i].lanvalidator = InvalidOid;
5403                 if (i_lanacl >= 0)
5404                         planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5405                 else
5406                         planginfo[i].lanacl = pg_strdup("{=U}");
5407                 if (i_lanowner >= 0)
5408                         planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5409                 else
5410                         planginfo[i].lanowner = pg_strdup("");
5411
5412                 if (fout->remoteVersion < 70300)
5413                 {
5414                         /*
5415                          * We need to make a dependency to ensure the function will be
5416                          * dumped first.  (In 7.3 and later the regular dependency
5417                          * mechanism will handle this for us.)
5418                          */
5419                         FuncInfo   *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5420
5421                         if (funcInfo)
5422                                 addObjectDependency(&planginfo[i].dobj,
5423                                                                         funcInfo->dobj.dumpId);
5424                 }
5425         }
5426
5427         PQclear(res);
5428
5429         destroyPQExpBuffer(query);
5430
5431         return planginfo;
5432 }
5433
5434 /*
5435  * getCasts
5436  *        get basic information about every cast in the system
5437  *
5438  * numCasts is set to the number of casts read in
5439  */
5440 CastInfo *
5441 getCasts(Archive *fout, int *numCasts)
5442 {
5443         PGresult   *res;
5444         int                     ntups;
5445         int                     i;
5446         PQExpBuffer query = createPQExpBuffer();
5447         CastInfo   *castinfo;
5448         int                     i_tableoid;
5449         int                     i_oid;
5450         int                     i_castsource;
5451         int                     i_casttarget;
5452         int                     i_castfunc;
5453         int                     i_castcontext;
5454         int                     i_castmethod;
5455
5456         /* Make sure we are in proper schema */
5457         selectSourceSchema(fout, "pg_catalog");
5458
5459         if (fout->remoteVersion >= 80400)
5460         {
5461                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5462                                                   "castsource, casttarget, castfunc, castcontext, "
5463                                                   "castmethod "
5464                                                   "FROM pg_cast ORDER BY 3,4");
5465         }
5466         else if (fout->remoteVersion >= 70300)
5467         {
5468                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5469                                                   "castsource, casttarget, castfunc, castcontext, "
5470                                 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
5471                                                   "FROM pg_cast ORDER BY 3,4");
5472         }
5473         else
5474         {
5475                 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
5476                                                   "t1.oid AS castsource, t2.oid AS casttarget, "
5477                                                   "p.oid AS castfunc, 'e' AS castcontext, "
5478                                                   "'f' AS castmethod "
5479                                                   "FROM pg_type t1, pg_type t2, pg_proc p "
5480                                                   "WHERE p.pronargs = 1 AND "
5481                                                   "p.proargtypes[0] = t1.oid AND "
5482                                                   "p.prorettype = t2.oid AND p.proname = t2.typname "
5483                                                   "ORDER BY 3,4");
5484         }
5485
5486         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5487
5488         ntups = PQntuples(res);
5489
5490         *numCasts = ntups;
5491
5492         castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
5493
5494         i_tableoid = PQfnumber(res, "tableoid");
5495         i_oid = PQfnumber(res, "oid");
5496         i_castsource = PQfnumber(res, "castsource");
5497         i_casttarget = PQfnumber(res, "casttarget");
5498         i_castfunc = PQfnumber(res, "castfunc");
5499         i_castcontext = PQfnumber(res, "castcontext");
5500         i_castmethod = PQfnumber(res, "castmethod");
5501
5502         for (i = 0; i < ntups; i++)
5503         {
5504                 PQExpBufferData namebuf;
5505                 TypeInfo   *sTypeInfo;
5506                 TypeInfo   *tTypeInfo;
5507
5508                 castinfo[i].dobj.objType = DO_CAST;
5509                 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5510                 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5511                 AssignDumpId(&castinfo[i].dobj);
5512                 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5513                 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5514                 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5515                 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5516                 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5517
5518                 /*
5519                  * Try to name cast as concatenation of typnames.  This is only used
5520                  * for purposes of sorting.  If we fail to find either type, the name
5521                  * will be an empty string.
5522                  */
5523                 initPQExpBuffer(&namebuf);
5524                 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5525                 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5526                 if (sTypeInfo && tTypeInfo)
5527                         appendPQExpBuffer(&namebuf, "%s %s",
5528                                                           sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5529                 castinfo[i].dobj.name = namebuf.data;
5530
5531                 if (OidIsValid(castinfo[i].castfunc))
5532                 {
5533                         /*
5534                          * We need to make a dependency to ensure the function will be
5535                          * dumped first.  (In 7.3 and later the regular dependency
5536                          * mechanism will handle this for us.)
5537                          */
5538                         FuncInfo   *funcInfo;
5539
5540                         funcInfo = findFuncByOid(castinfo[i].castfunc);
5541                         if (funcInfo)
5542                                 addObjectDependency(&castinfo[i].dobj,
5543                                                                         funcInfo->dobj.dumpId);
5544                 }
5545         }
5546
5547         PQclear(res);
5548
5549         destroyPQExpBuffer(query);
5550
5551         return castinfo;
5552 }
5553
5554 /*
5555  * getTableAttrs -
5556  *        for each interesting table, read info about its attributes
5557  *        (names, types, default values, CHECK constraints, etc)
5558  *
5559  * This is implemented in a very inefficient way right now, looping
5560  * through the tblinfo and doing a join per table to find the attrs and their
5561  * types.  However, because we want type names and so forth to be named
5562  * relative to the schema of each table, we couldn't do it in just one
5563  * query.  (Maybe one query per schema?)
5564  *
5565  *      modifies tblinfo
5566  */
5567 void
5568 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
5569 {
5570         int                     i,
5571                                 j;
5572         PQExpBuffer q = createPQExpBuffer();
5573         int                     i_attnum;
5574         int                     i_attname;
5575         int                     i_atttypname;
5576         int                     i_atttypmod;
5577         int                     i_attstattarget;
5578         int                     i_attstorage;
5579         int                     i_typstorage;
5580         int                     i_attnotnull;
5581         int                     i_atthasdef;
5582         int                     i_attisdropped;
5583         int                     i_attlen;
5584         int                     i_attalign;
5585         int                     i_attislocal;
5586         int                     i_attoptions;
5587         int                     i_attcollation;
5588         int                     i_attfdwoptions;
5589         PGresult   *res;
5590         int                     ntups;
5591         bool            hasdefaults;
5592
5593         for (i = 0; i < numTables; i++)
5594         {
5595                 TableInfo  *tbinfo = &tblinfo[i];
5596
5597                 /* Don't bother to collect info for sequences */
5598                 if (tbinfo->relkind == RELKIND_SEQUENCE)
5599                         continue;
5600
5601                 /* Don't bother with uninteresting tables, either */
5602                 if (!tbinfo->interesting)
5603                         continue;
5604
5605                 /*
5606                  * Make sure we are in proper schema for this table; this allows
5607                  * correct retrieval of formatted type names and default exprs
5608                  */
5609                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5610
5611                 /* find all the user attributes and their types */
5612
5613                 /*
5614                  * we must read the attribute names in attribute number order! because
5615                  * we will use the attnum to index into the attnames array later.  We
5616                  * actually ask to order by "attrelid, attnum" because (at least up to
5617                  * 7.3) the planner is not smart enough to realize it needn't re-sort
5618                  * the output of an indexscan on pg_attribute_relid_attnum_index.
5619                  */
5620                 if (g_verbose)
5621                         write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5622                                           tbinfo->dobj.name);
5623
5624                 resetPQExpBuffer(q);
5625
5626                 if (fout->remoteVersion >= 90200)
5627                 {
5628                         /*
5629                          * attfdwoptions is new in 9.2.
5630                          */
5631                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5632                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5633                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5634                                                           "a.attlen, a.attalign, a.attislocal, "
5635                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5636                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5637                                                           "CASE WHEN a.attcollation <> t.typcollation "
5638                                                         "THEN a.attcollation ELSE 0 END AS attcollation, "
5639                                                           "pg_catalog.array_to_string(ARRAY("
5640                                                           "SELECT pg_catalog.quote_ident(option_name) || "
5641                                                           "' ' || pg_catalog.quote_literal(option_value) "
5642                                                           "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
5643                                                           "ORDER BY option_name"
5644                                                           "), E',\n    ') AS attfdwoptions "
5645                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5646                                                           "ON a.atttypid = t.oid "
5647                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5648                                                           "AND a.attnum > 0::pg_catalog.int2 "
5649                                                           "ORDER BY a.attrelid, a.attnum",
5650                                                           tbinfo->dobj.catId.oid);
5651                 }
5652                 else if (fout->remoteVersion >= 90100)
5653                 {
5654                         /*
5655                          * attcollation is new in 9.1.  Since we only want to dump COLLATE
5656                          * clauses for attributes whose collation is different from their
5657                          * type's default, we use a CASE here to suppress uninteresting
5658                          * attcollations cheaply.
5659                          */
5660                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5661                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5662                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5663                                                           "a.attlen, a.attalign, a.attislocal, "
5664                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5665                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5666                                                           "CASE WHEN a.attcollation <> t.typcollation "
5667                                                         "THEN a.attcollation ELSE 0 END AS attcollation, "
5668                                                           "NULL AS attfdwoptions "
5669                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5670                                                           "ON a.atttypid = t.oid "
5671                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5672                                                           "AND a.attnum > 0::pg_catalog.int2 "
5673                                                           "ORDER BY a.attrelid, a.attnum",
5674                                                           tbinfo->dobj.catId.oid);
5675                 }
5676                 else if (fout->remoteVersion >= 90000)
5677                 {
5678                         /* attoptions is new in 9.0 */
5679                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5680                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5681                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5682                                                           "a.attlen, a.attalign, a.attislocal, "
5683                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5684                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5685                                                           "0 AS attcollation, "
5686                                                           "NULL AS attfdwoptions "
5687                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5688                                                           "ON a.atttypid = t.oid "
5689                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5690                                                           "AND a.attnum > 0::pg_catalog.int2 "
5691                                                           "ORDER BY a.attrelid, a.attnum",
5692                                                           tbinfo->dobj.catId.oid);
5693                 }
5694                 else if (fout->remoteVersion >= 70300)
5695                 {
5696                         /* need left join here to not fail on dropped columns ... */
5697                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5698                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5699                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5700                                                           "a.attlen, a.attalign, a.attislocal, "
5701                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5702                                                           "'' AS attoptions, 0 AS attcollation, "
5703                                                           "NULL AS attfdwoptions "
5704                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5705                                                           "ON a.atttypid = t.oid "
5706                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5707                                                           "AND a.attnum > 0::pg_catalog.int2 "
5708                                                           "ORDER BY a.attrelid, a.attnum",
5709                                                           tbinfo->dobj.catId.oid);
5710                 }
5711                 else if (fout->remoteVersion >= 70100)
5712                 {
5713                         /*
5714                          * attstattarget doesn't exist in 7.1.  It does exist in 7.2, but
5715                          * we don't dump it because we can't tell whether it's been
5716                          * explicitly set or was just a default.
5717                          *
5718                          * attislocal doesn't exist before 7.3, either; in older databases
5719                          * we assume it's TRUE, else we'd fail to dump non-inherited atts.
5720                          */
5721                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5722                                                           "-1 AS attstattarget, a.attstorage, "
5723                                                           "t.typstorage, a.attnotnull, a.atthasdef, "
5724                                                           "false AS attisdropped, a.attlen, "
5725                                                           "a.attalign, true AS attislocal, "
5726                                                           "format_type(t.oid,a.atttypmod) AS atttypname, "
5727                                                           "'' AS attoptions, 0 AS attcollation, "
5728                                                           "NULL AS attfdwoptions "
5729                                                           "FROM pg_attribute a LEFT JOIN pg_type t "
5730                                                           "ON a.atttypid = t.oid "
5731                                                           "WHERE a.attrelid = '%u'::oid "
5732                                                           "AND a.attnum > 0::int2 "
5733                                                           "ORDER BY a.attrelid, a.attnum",
5734                                                           tbinfo->dobj.catId.oid);
5735                 }
5736                 else
5737                 {
5738                         /* format_type not available before 7.1 */
5739                         appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
5740                                                           "-1 AS attstattarget, "
5741                                                           "attstorage, attstorage AS typstorage, "
5742                                                           "attnotnull, atthasdef, false AS attisdropped, "
5743                                                           "attlen, attalign, "
5744                                                           "true AS attislocal, "
5745                                                           "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
5746                                                           "'' AS attoptions, 0 AS attcollation, "
5747                                                           "NULL AS attfdwoptions "
5748                                                           "FROM pg_attribute a "
5749                                                           "WHERE attrelid = '%u'::oid "
5750                                                           "AND attnum > 0::int2 "
5751                                                           "ORDER BY attrelid, attnum",
5752                                                           tbinfo->dobj.catId.oid);
5753                 }
5754
5755                 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5756
5757                 ntups = PQntuples(res);
5758
5759                 i_attnum = PQfnumber(res, "attnum");
5760                 i_attname = PQfnumber(res, "attname");
5761                 i_atttypname = PQfnumber(res, "atttypname");
5762                 i_atttypmod = PQfnumber(res, "atttypmod");
5763                 i_attstattarget = PQfnumber(res, "attstattarget");
5764                 i_attstorage = PQfnumber(res, "attstorage");
5765                 i_typstorage = PQfnumber(res, "typstorage");
5766                 i_attnotnull = PQfnumber(res, "attnotnull");
5767                 i_atthasdef = PQfnumber(res, "atthasdef");
5768                 i_attisdropped = PQfnumber(res, "attisdropped");
5769                 i_attlen = PQfnumber(res, "attlen");
5770                 i_attalign = PQfnumber(res, "attalign");
5771                 i_attislocal = PQfnumber(res, "attislocal");
5772                 i_attoptions = PQfnumber(res, "attoptions");
5773                 i_attcollation = PQfnumber(res, "attcollation");
5774                 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
5775
5776                 tbinfo->numatts = ntups;
5777                 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
5778                 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
5779                 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
5780                 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
5781                 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
5782                 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
5783                 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
5784                 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
5785                 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
5786                 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
5787                 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
5788                 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
5789                 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
5790                 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
5791                 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
5792                 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
5793                 hasdefaults = false;
5794
5795                 for (j = 0; j < ntups; j++)
5796                 {
5797                         if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
5798                                 exit_horribly(NULL,
5799                                                           "invalid column numbering in table \"%s\"\n",
5800                                                           tbinfo->dobj.name);
5801                         tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
5802                         tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
5803                         tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
5804                         tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
5805                         tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
5806                         tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
5807                         tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
5808                         tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
5809                         tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
5810                         tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
5811                         tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
5812                         tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
5813                         tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
5814                         tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
5815                         tbinfo->attrdefs[j] = NULL; /* fix below */
5816                         if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
5817                                 hasdefaults = true;
5818                         /* these flags will be set in flagInhAttrs() */
5819                         tbinfo->inhNotNull[j] = false;
5820                 }
5821
5822                 PQclear(res);
5823
5824                 /*
5825                  * Get info about column defaults
5826                  */
5827                 if (hasdefaults)
5828                 {
5829                         AttrDefInfo *attrdefs;
5830                         int                     numDefaults;
5831
5832                         if (g_verbose)
5833                                 write_msg(NULL, "finding default expressions of table \"%s\"\n",
5834                                                   tbinfo->dobj.name);
5835
5836                         resetPQExpBuffer(q);
5837                         if (fout->remoteVersion >= 70300)
5838                         {
5839                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
5840                                                    "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
5841                                                                   "FROM pg_catalog.pg_attrdef "
5842                                                                   "WHERE adrelid = '%u'::pg_catalog.oid",
5843                                                                   tbinfo->dobj.catId.oid);
5844                         }
5845                         else if (fout->remoteVersion >= 70200)
5846                         {
5847                                 /* 7.2 did not have OIDs in pg_attrdef */
5848                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
5849                                                                   "pg_get_expr(adbin, adrelid) AS adsrc "
5850                                                                   "FROM pg_attrdef "
5851                                                                   "WHERE adrelid = '%u'::oid",
5852                                                                   tbinfo->dobj.catId.oid);
5853                         }
5854                         else if (fout->remoteVersion >= 70100)
5855                         {
5856                                 /* no pg_get_expr, so must rely on adsrc */
5857                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
5858                                                                   "FROM pg_attrdef "
5859                                                                   "WHERE adrelid = '%u'::oid",
5860                                                                   tbinfo->dobj.catId.oid);
5861                         }
5862                         else
5863                         {
5864                                 /* no pg_get_expr, no tableoid either */
5865                                 appendPQExpBuffer(q, "SELECT "
5866                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
5867                                                                   "oid, adnum, adsrc "
5868                                                                   "FROM pg_attrdef "
5869                                                                   "WHERE adrelid = '%u'::oid",
5870                                                                   tbinfo->dobj.catId.oid);
5871                         }
5872                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5873
5874                         numDefaults = PQntuples(res);
5875                         attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
5876
5877                         for (j = 0; j < numDefaults; j++)
5878                         {
5879                                 int                     adnum;
5880
5881                                 adnum = atoi(PQgetvalue(res, j, 2));
5882
5883                                 if (adnum <= 0 || adnum > ntups)
5884                                         exit_horribly(NULL,
5885                                                                   "invalid adnum value %d for table \"%s\"\n",
5886                                                                   adnum, tbinfo->dobj.name);
5887
5888                                 /*
5889                                  * dropped columns shouldn't have defaults, but just in case,
5890                                  * ignore 'em
5891                                  */
5892                                 if (tbinfo->attisdropped[adnum - 1])
5893                                         continue;
5894
5895                                 attrdefs[j].dobj.objType = DO_ATTRDEF;
5896                                 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
5897                                 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
5898                                 AssignDumpId(&attrdefs[j].dobj);
5899                                 attrdefs[j].adtable = tbinfo;
5900                                 attrdefs[j].adnum = adnum;
5901                                 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
5902
5903                                 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
5904                                 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
5905
5906                                 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
5907
5908                                 /*
5909                                  * Defaults on a VIEW must always be dumped as separate ALTER
5910                                  * TABLE commands.      Defaults on regular tables are dumped as
5911                                  * part of the CREATE TABLE if possible, which it won't be
5912                                  * if the column is not going to be emitted explicitly.
5913                                  */
5914                                 if (tbinfo->relkind == RELKIND_VIEW)
5915                                 {
5916                                         attrdefs[j].separate = true;
5917                                         /* needed in case pre-7.3 DB: */
5918                                         addObjectDependency(&attrdefs[j].dobj,
5919                                                                                 tbinfo->dobj.dumpId);
5920                                 }
5921                                 else if (!shouldPrintColumn(tbinfo, adnum - 1))
5922                                 {
5923                                         /* column will be suppressed, print default separately */
5924                                         attrdefs[j].separate = true;
5925                                         /* needed in case pre-7.3 DB: */
5926                                         addObjectDependency(&attrdefs[j].dobj,
5927                                                                                 tbinfo->dobj.dumpId);
5928                                 }
5929                                 else
5930                                 {
5931                                         attrdefs[j].separate = false;
5932                                         /*
5933                                          * Mark the default as needing to appear before the table,
5934                                          * so that any dependencies it has must be emitted before
5935                                          * the CREATE TABLE.  If this is not possible, we'll
5936                                          * change to "separate" mode while sorting dependencies.
5937                                          */
5938                                         addObjectDependency(&tbinfo->dobj,
5939                                                                                 attrdefs[j].dobj.dumpId);
5940                                 }
5941
5942                                 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
5943                         }
5944                         PQclear(res);
5945                 }
5946
5947                 /*
5948                  * Get info about table CHECK constraints
5949                  */
5950                 if (tbinfo->ncheck > 0)
5951                 {
5952                         ConstraintInfo *constrs;
5953                         int                     numConstrs;
5954
5955                         if (g_verbose)
5956                                 write_msg(NULL, "finding check constraints for table \"%s\"\n",
5957                                                   tbinfo->dobj.name);
5958
5959                         resetPQExpBuffer(q);
5960                         if (fout->remoteVersion >= 90200)
5961                         {
5962                                 /*
5963                                  * conisonly and convalidated are new in 9.2 (actually, the latter
5964                                  * is there in 9.1, but it wasn't ever false for check constraints
5965                                  * until 9.2).
5966                                  */
5967                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5968                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5969                                                                   "conislocal, convalidated, conisonly "
5970                                                                   "FROM pg_catalog.pg_constraint "
5971                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5972                                                                   "   AND contype = 'c' "
5973                                                                   "ORDER BY conname",
5974                                                                   tbinfo->dobj.catId.oid);
5975                         }
5976                         else if (fout->remoteVersion >= 80400)
5977                         {
5978                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5979                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5980                                                                   "conislocal, true AS convalidated, "
5981                                                                   "false as conisonly "
5982                                                                   "FROM pg_catalog.pg_constraint "
5983                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5984                                                                   "   AND contype = 'c' "
5985                                                                   "ORDER BY conname",
5986                                                                   tbinfo->dobj.catId.oid);
5987                         }
5988                         else if (fout->remoteVersion >= 70400)
5989                         {
5990                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5991                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5992                                                                   "true AS conislocal, true AS convalidated, "
5993                                                                   "false as conisonly "
5994                                                                   "FROM pg_catalog.pg_constraint "
5995                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5996                                                                   "   AND contype = 'c' "
5997                                                                   "ORDER BY conname",
5998                                                                   tbinfo->dobj.catId.oid);
5999                         }
6000                         else if (fout->remoteVersion >= 70300)
6001                         {
6002                                 /* no pg_get_constraintdef, must use consrc */
6003                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6004                                                                   "'CHECK (' || consrc || ')' AS consrc, "
6005                                                                   "true AS conislocal, true AS convalidated, "
6006                                                                   "false as conisonly "
6007                                                                   "FROM pg_catalog.pg_constraint "
6008                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6009                                                                   "   AND contype = 'c' "
6010                                                                   "ORDER BY conname",
6011                                                                   tbinfo->dobj.catId.oid);
6012                         }
6013                         else if (fout->remoteVersion >= 70200)
6014                         {
6015                                 /* 7.2 did not have OIDs in pg_relcheck */
6016                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6017                                                                   "rcname AS conname, "
6018                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6019                                                                   "true AS conislocal, true AS convalidated, "
6020                                                                   "false as conisonly "
6021                                                                   "FROM pg_relcheck "
6022                                                                   "WHERE rcrelid = '%u'::oid "
6023                                                                   "ORDER BY rcname",
6024                                                                   tbinfo->dobj.catId.oid);
6025                         }
6026                         else if (fout->remoteVersion >= 70100)
6027                         {
6028                                 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6029                                                                   "rcname AS conname, "
6030                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6031                                                                   "true AS conislocal, true AS convalidated, "
6032                                                                   "false as conisonly "
6033                                                                   "FROM pg_relcheck "
6034                                                                   "WHERE rcrelid = '%u'::oid "
6035                                                                   "ORDER BY rcname",
6036                                                                   tbinfo->dobj.catId.oid);
6037                         }
6038                         else
6039                         {
6040                                 /* no tableoid in 7.0 */
6041                                 appendPQExpBuffer(q, "SELECT "
6042                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6043                                                                   "oid, rcname AS conname, "
6044                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6045                                                                   "true AS conislocal, true AS convalidated, "
6046                                                                   "false as conisonly "
6047                                                                   "FROM pg_relcheck "
6048                                                                   "WHERE rcrelid = '%u'::oid "
6049                                                                   "ORDER BY rcname",
6050                                                                   tbinfo->dobj.catId.oid);
6051                         }
6052                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6053
6054                         numConstrs = PQntuples(res);
6055                         if (numConstrs != tbinfo->ncheck)
6056                         {
6057                                 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6058                                                                                  "expected %d check constraints on table \"%s\" but found %d\n",
6059                                                                                  tbinfo->ncheck),
6060                                                   tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6061                                 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6062                                 exit_nicely(1);
6063                         }
6064
6065                         constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6066                         tbinfo->checkexprs = constrs;
6067
6068                         for (j = 0; j < numConstrs; j++)
6069                         {
6070                                 bool    validated = PQgetvalue(res, j, 5)[0] == 't';
6071                                 bool    isonly = PQgetvalue(res, j, 6)[0] == 't';
6072
6073                                 constrs[j].dobj.objType = DO_CONSTRAINT;
6074                                 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6075                                 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6076                                 AssignDumpId(&constrs[j].dobj);
6077                                 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6078                                 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6079                                 constrs[j].contable = tbinfo;
6080                                 constrs[j].condomain = NULL;
6081                                 constrs[j].contype = 'c';
6082                                 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6083                                 constrs[j].confrelid = InvalidOid;
6084                                 constrs[j].conindex = 0;
6085                                 constrs[j].condeferrable = false;
6086                                 constrs[j].condeferred = false;
6087                                 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6088                                 constrs[j].conisonly = isonly;
6089                                 /*
6090                                  * An unvalidated constraint needs to be dumped separately, so
6091                                  * that potentially-violating existing data is loaded before
6092                                  * the constraint.  An ONLY constraint needs to be dumped
6093                                  * separately too.
6094                                  */
6095                                 constrs[j].separate = !validated || isonly;
6096
6097                                 constrs[j].dobj.dump = tbinfo->dobj.dump;
6098
6099                                 /*
6100                                  * Mark the constraint as needing to appear before the table
6101                                  * --- this is so that any other dependencies of the
6102                                  * constraint will be emitted before we try to create the
6103                                  * table.  If the constraint is to be dumped separately, it will be
6104                                  * dumped after data is loaded anyway, so don't do it.  (There's
6105                                  * an automatic dependency in the opposite direction anyway, so
6106                                  * don't need to add one manually here.)
6107                                  */
6108                                 if (!constrs[j].separate)
6109                                         addObjectDependency(&tbinfo->dobj,
6110                                                                                 constrs[j].dobj.dumpId);
6111
6112                                 /*
6113                                  * If the constraint is inherited, this will be detected later
6114                                  * (in pre-8.4 databases).      We also detect later if the
6115                                  * constraint must be split out from the table definition.
6116                                  */
6117                         }
6118                         PQclear(res);
6119                 }
6120         }
6121
6122         destroyPQExpBuffer(q);
6123 }
6124
6125 /*
6126  * Test whether a column should be printed as part of table's CREATE TABLE.
6127  * Column number is zero-based.
6128  *
6129  * Normally this is always true, but it's false for dropped columns, as well
6130  * as those that were inherited without any local definition.  (If we print
6131  * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6132  * However, in binary_upgrade mode, we must print all such columns anyway and
6133  * fix the attislocal/attisdropped state later, so as to keep control of the
6134  * physical column order.
6135  *
6136  * This function exists because there are scattered nonobvious places that
6137  * must be kept in sync with this decision.
6138  */
6139 bool
6140 shouldPrintColumn(TableInfo *tbinfo, int colno)
6141 {
6142         if (binary_upgrade)
6143                 return true;
6144         return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6145 }
6146
6147
6148 /*
6149  * getTSParsers:
6150  *        read all text search parsers in the system catalogs and return them
6151  *        in the TSParserInfo* structure
6152  *
6153  *      numTSParsers is set to the number of parsers read in
6154  */
6155 TSParserInfo *
6156 getTSParsers(Archive *fout, int *numTSParsers)
6157 {
6158         PGresult   *res;
6159         int                     ntups;
6160         int                     i;
6161         PQExpBuffer query;
6162         TSParserInfo *prsinfo;
6163         int                     i_tableoid;
6164         int                     i_oid;
6165         int                     i_prsname;
6166         int                     i_prsnamespace;
6167         int                     i_prsstart;
6168         int                     i_prstoken;
6169         int                     i_prsend;
6170         int                     i_prsheadline;
6171         int                     i_prslextype;
6172
6173         /* Before 8.3, there is no built-in text search support */
6174         if (fout->remoteVersion < 80300)
6175         {
6176                 *numTSParsers = 0;
6177                 return NULL;
6178         }
6179
6180         query = createPQExpBuffer();
6181
6182         /*
6183          * find all text search objects, including builtin ones; we filter out
6184          * system-defined objects at dump-out time.
6185          */
6186
6187         /* Make sure we are in proper schema */
6188         selectSourceSchema(fout, "pg_catalog");
6189
6190         appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6191                                           "prsstart::oid, prstoken::oid, "
6192                                           "prsend::oid, prsheadline::oid, prslextype::oid "
6193                                           "FROM pg_ts_parser");
6194
6195         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6196
6197         ntups = PQntuples(res);
6198         *numTSParsers = ntups;
6199
6200         prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6201
6202         i_tableoid = PQfnumber(res, "tableoid");
6203         i_oid = PQfnumber(res, "oid");
6204         i_prsname = PQfnumber(res, "prsname");
6205         i_prsnamespace = PQfnumber(res, "prsnamespace");
6206         i_prsstart = PQfnumber(res, "prsstart");
6207         i_prstoken = PQfnumber(res, "prstoken");
6208         i_prsend = PQfnumber(res, "prsend");
6209         i_prsheadline = PQfnumber(res, "prsheadline");
6210         i_prslextype = PQfnumber(res, "prslextype");
6211
6212         for (i = 0; i < ntups; i++)
6213         {
6214                 prsinfo[i].dobj.objType = DO_TSPARSER;
6215                 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6216                 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6217                 AssignDumpId(&prsinfo[i].dobj);
6218                 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6219                 prsinfo[i].dobj.namespace =
6220                         findNamespace(fout,
6221                                                   atooid(PQgetvalue(res, i, i_prsnamespace)),
6222                                                   prsinfo[i].dobj.catId.oid);
6223                 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6224                 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6225                 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6226                 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6227                 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6228
6229                 /* Decide whether we want to dump it */
6230                 selectDumpableObject(&(prsinfo[i].dobj));
6231         }
6232
6233         PQclear(res);
6234
6235         destroyPQExpBuffer(query);
6236
6237         return prsinfo;
6238 }
6239
6240 /*
6241  * getTSDictionaries:
6242  *        read all text search dictionaries in the system catalogs and return them
6243  *        in the TSDictInfo* structure
6244  *
6245  *      numTSDicts is set to the number of dictionaries read in
6246  */
6247 TSDictInfo *
6248 getTSDictionaries(Archive *fout, int *numTSDicts)
6249 {
6250         PGresult   *res;
6251         int                     ntups;
6252         int                     i;
6253         PQExpBuffer query;
6254         TSDictInfo *dictinfo;
6255         int                     i_tableoid;
6256         int                     i_oid;
6257         int                     i_dictname;
6258         int                     i_dictnamespace;
6259         int                     i_rolname;
6260         int                     i_dicttemplate;
6261         int                     i_dictinitoption;
6262
6263         /* Before 8.3, there is no built-in text search support */
6264         if (fout->remoteVersion < 80300)
6265         {
6266                 *numTSDicts = 0;
6267                 return NULL;
6268         }
6269
6270         query = createPQExpBuffer();
6271
6272         /* Make sure we are in proper schema */
6273         selectSourceSchema(fout, "pg_catalog");
6274
6275         appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6276                                           "dictnamespace, (%s dictowner) AS rolname, "
6277                                           "dicttemplate, dictinitoption "
6278                                           "FROM pg_ts_dict",
6279                                           username_subquery);
6280
6281         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6282
6283         ntups = PQntuples(res);
6284         *numTSDicts = ntups;
6285
6286         dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6287
6288         i_tableoid = PQfnumber(res, "tableoid");
6289         i_oid = PQfnumber(res, "oid");
6290         i_dictname = PQfnumber(res, "dictname");
6291         i_dictnamespace = PQfnumber(res, "dictnamespace");
6292         i_rolname = PQfnumber(res, "rolname");
6293         i_dictinitoption = PQfnumber(res, "dictinitoption");
6294         i_dicttemplate = PQfnumber(res, "dicttemplate");
6295
6296         for (i = 0; i < ntups; i++)
6297         {
6298                 dictinfo[i].dobj.objType = DO_TSDICT;
6299                 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6300                 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6301                 AssignDumpId(&dictinfo[i].dobj);
6302                 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6303                 dictinfo[i].dobj.namespace =
6304                         findNamespace(fout,
6305                                                   atooid(PQgetvalue(res, i, i_dictnamespace)),
6306                                                   dictinfo[i].dobj.catId.oid);
6307                 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6308                 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6309                 if (PQgetisnull(res, i, i_dictinitoption))
6310                         dictinfo[i].dictinitoption = NULL;
6311                 else
6312                         dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6313
6314                 /* Decide whether we want to dump it */
6315                 selectDumpableObject(&(dictinfo[i].dobj));
6316         }
6317
6318         PQclear(res);
6319
6320         destroyPQExpBuffer(query);
6321
6322         return dictinfo;
6323 }
6324
6325 /*
6326  * getTSTemplates:
6327  *        read all text search templates in the system catalogs and return them
6328  *        in the TSTemplateInfo* structure
6329  *
6330  *      numTSTemplates is set to the number of templates read in
6331  */
6332 TSTemplateInfo *
6333 getTSTemplates(Archive *fout, int *numTSTemplates)
6334 {
6335         PGresult   *res;
6336         int                     ntups;
6337         int                     i;
6338         PQExpBuffer query;
6339         TSTemplateInfo *tmplinfo;
6340         int                     i_tableoid;
6341         int                     i_oid;
6342         int                     i_tmplname;
6343         int                     i_tmplnamespace;
6344         int                     i_tmplinit;
6345         int                     i_tmpllexize;
6346
6347         /* Before 8.3, there is no built-in text search support */
6348         if (fout->remoteVersion < 80300)
6349         {
6350                 *numTSTemplates = 0;
6351                 return NULL;
6352         }
6353
6354         query = createPQExpBuffer();
6355
6356         /* Make sure we are in proper schema */
6357         selectSourceSchema(fout, "pg_catalog");
6358
6359         appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6360                                           "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6361                                           "FROM pg_ts_template");
6362
6363         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6364
6365         ntups = PQntuples(res);
6366         *numTSTemplates = ntups;
6367
6368         tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6369
6370         i_tableoid = PQfnumber(res, "tableoid");
6371         i_oid = PQfnumber(res, "oid");
6372         i_tmplname = PQfnumber(res, "tmplname");
6373         i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6374         i_tmplinit = PQfnumber(res, "tmplinit");
6375         i_tmpllexize = PQfnumber(res, "tmpllexize");
6376
6377         for (i = 0; i < ntups; i++)
6378         {
6379                 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6380                 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6381                 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6382                 AssignDumpId(&tmplinfo[i].dobj);
6383                 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6384                 tmplinfo[i].dobj.namespace =
6385                         findNamespace(fout,
6386                                                   atooid(PQgetvalue(res, i, i_tmplnamespace)),
6387                                                   tmplinfo[i].dobj.catId.oid);
6388                 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6389                 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6390
6391                 /* Decide whether we want to dump it */
6392                 selectDumpableObject(&(tmplinfo[i].dobj));
6393         }
6394
6395         PQclear(res);
6396
6397         destroyPQExpBuffer(query);
6398
6399         return tmplinfo;
6400 }
6401
6402 /*
6403  * getTSConfigurations:
6404  *        read all text search configurations in the system catalogs and return
6405  *        them in the TSConfigInfo* structure
6406  *
6407  *      numTSConfigs is set to the number of configurations read in
6408  */
6409 TSConfigInfo *
6410 getTSConfigurations(Archive *fout, int *numTSConfigs)
6411 {
6412         PGresult   *res;
6413         int                     ntups;
6414         int                     i;
6415         PQExpBuffer query;
6416         TSConfigInfo *cfginfo;
6417         int                     i_tableoid;
6418         int                     i_oid;
6419         int                     i_cfgname;
6420         int                     i_cfgnamespace;
6421         int                     i_rolname;
6422         int                     i_cfgparser;
6423
6424         /* Before 8.3, there is no built-in text search support */
6425         if (fout->remoteVersion < 80300)
6426         {
6427                 *numTSConfigs = 0;
6428                 return NULL;
6429         }
6430
6431         query = createPQExpBuffer();
6432
6433         /* Make sure we are in proper schema */
6434         selectSourceSchema(fout, "pg_catalog");
6435
6436         appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6437                                           "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6438                                           "FROM pg_ts_config",
6439                                           username_subquery);
6440
6441         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6442
6443         ntups = PQntuples(res);
6444         *numTSConfigs = ntups;
6445
6446         cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6447
6448         i_tableoid = PQfnumber(res, "tableoid");
6449         i_oid = PQfnumber(res, "oid");
6450         i_cfgname = PQfnumber(res, "cfgname");
6451         i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6452         i_rolname = PQfnumber(res, "rolname");
6453         i_cfgparser = PQfnumber(res, "cfgparser");
6454
6455         for (i = 0; i < ntups; i++)
6456         {
6457                 cfginfo[i].dobj.objType = DO_TSCONFIG;
6458                 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6459                 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6460                 AssignDumpId(&cfginfo[i].dobj);
6461                 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6462                 cfginfo[i].dobj.namespace =
6463                         findNamespace(fout,
6464                                                   atooid(PQgetvalue(res, i, i_cfgnamespace)),
6465                                                   cfginfo[i].dobj.catId.oid);
6466                 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6467                 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6468
6469                 /* Decide whether we want to dump it */
6470                 selectDumpableObject(&(cfginfo[i].dobj));
6471         }
6472
6473         PQclear(res);
6474
6475         destroyPQExpBuffer(query);
6476
6477         return cfginfo;
6478 }
6479
6480 /*
6481  * getForeignDataWrappers:
6482  *        read all foreign-data wrappers in the system catalogs and return
6483  *        them in the FdwInfo* structure
6484  *
6485  *      numForeignDataWrappers is set to the number of fdws read in
6486  */
6487 FdwInfo *
6488 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
6489 {
6490         PGresult   *res;
6491         int                     ntups;
6492         int                     i;
6493         PQExpBuffer query = createPQExpBuffer();
6494         FdwInfo    *fdwinfo;
6495         int                     i_tableoid;
6496         int                     i_oid;
6497         int                     i_fdwname;
6498         int                     i_rolname;
6499         int                     i_fdwhandler;
6500         int                     i_fdwvalidator;
6501         int                     i_fdwacl;
6502         int                     i_fdwoptions;
6503
6504         /* Before 8.4, there are no foreign-data wrappers */
6505         if (fout->remoteVersion < 80400)
6506         {
6507                 *numForeignDataWrappers = 0;
6508                 return NULL;
6509         }
6510
6511         /* Make sure we are in proper schema */
6512         selectSourceSchema(fout, "pg_catalog");
6513
6514         if (fout->remoteVersion >= 90100)
6515         {
6516                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6517                                                   "(%s fdwowner) AS rolname, "
6518                                                   "fdwhandler::pg_catalog.regproc, "
6519                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
6520                                                   "array_to_string(ARRAY("
6521                                                   "SELECT quote_ident(option_name) || ' ' || "
6522                                                   "quote_literal(option_value) "
6523                                                   "FROM pg_options_to_table(fdwoptions) "
6524                                                   "ORDER BY option_name"
6525                                                   "), E',\n    ') AS fdwoptions "
6526                                                   "FROM pg_foreign_data_wrapper",
6527                                                   username_subquery);
6528         }
6529         else
6530         {
6531                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6532                                                   "(%s fdwowner) AS rolname, "
6533                                                   "'-' AS fdwhandler, "
6534                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
6535                                                   "array_to_string(ARRAY("
6536                                                   "SELECT quote_ident(option_name) || ' ' || "
6537                                                   "quote_literal(option_value) "
6538                                                   "FROM pg_options_to_table(fdwoptions) "
6539                                                   "ORDER BY option_name"
6540                                                   "), E',\n    ') AS fdwoptions "
6541                                                   "FROM pg_foreign_data_wrapper",
6542                                                   username_subquery);
6543         }
6544
6545         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6546
6547         ntups = PQntuples(res);
6548         *numForeignDataWrappers = ntups;
6549
6550         fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6551
6552         i_tableoid = PQfnumber(res, "tableoid");
6553         i_oid = PQfnumber(res, "oid");
6554         i_fdwname = PQfnumber(res, "fdwname");
6555         i_rolname = PQfnumber(res, "rolname");
6556         i_fdwhandler = PQfnumber(res, "fdwhandler");
6557         i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6558         i_fdwacl = PQfnumber(res, "fdwacl");
6559         i_fdwoptions = PQfnumber(res, "fdwoptions");
6560
6561         for (i = 0; i < ntups; i++)
6562         {
6563                 fdwinfo[i].dobj.objType = DO_FDW;
6564                 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6565                 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6566                 AssignDumpId(&fdwinfo[i].dobj);
6567                 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6568                 fdwinfo[i].dobj.namespace = NULL;
6569                 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6570                 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6571                 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6572                 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6573                 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6574
6575                 /* Decide whether we want to dump it */
6576                 selectDumpableObject(&(fdwinfo[i].dobj));
6577         }
6578
6579         PQclear(res);
6580
6581         destroyPQExpBuffer(query);
6582
6583         return fdwinfo;
6584 }
6585
6586 /*
6587  * getForeignServers:
6588  *        read all foreign servers in the system catalogs and return
6589  *        them in the ForeignServerInfo * structure
6590  *
6591  *      numForeignServers is set to the number of servers read in
6592  */
6593 ForeignServerInfo *
6594 getForeignServers(Archive *fout, int *numForeignServers)
6595 {
6596         PGresult   *res;
6597         int                     ntups;
6598         int                     i;
6599         PQExpBuffer query = createPQExpBuffer();
6600         ForeignServerInfo *srvinfo;
6601         int                     i_tableoid;
6602         int                     i_oid;
6603         int                     i_srvname;
6604         int                     i_rolname;
6605         int                     i_srvfdw;
6606         int                     i_srvtype;
6607         int                     i_srvversion;
6608         int                     i_srvacl;
6609         int                     i_srvoptions;
6610
6611         /* Before 8.4, there are no foreign servers */
6612         if (fout->remoteVersion < 80400)
6613         {
6614                 *numForeignServers = 0;
6615                 return NULL;
6616         }
6617
6618         /* Make sure we are in proper schema */
6619         selectSourceSchema(fout,"pg_catalog");
6620
6621         appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6622                                           "(%s srvowner) AS rolname, "
6623                                           "srvfdw, srvtype, srvversion, srvacl,"
6624                                           "array_to_string(ARRAY("
6625                                           "SELECT quote_ident(option_name) || ' ' || "
6626                                           "quote_literal(option_value) "
6627                                           "FROM pg_options_to_table(srvoptions) "
6628                                           "ORDER BY option_name"
6629                                           "), E',\n    ') AS srvoptions "
6630                                           "FROM pg_foreign_server",
6631                                           username_subquery);
6632
6633         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6634
6635         ntups = PQntuples(res);
6636         *numForeignServers = ntups;
6637
6638         srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
6639
6640         i_tableoid = PQfnumber(res, "tableoid");
6641         i_oid = PQfnumber(res, "oid");
6642         i_srvname = PQfnumber(res, "srvname");
6643         i_rolname = PQfnumber(res, "rolname");
6644         i_srvfdw = PQfnumber(res, "srvfdw");
6645         i_srvtype = PQfnumber(res, "srvtype");
6646         i_srvversion = PQfnumber(res, "srvversion");
6647         i_srvacl = PQfnumber(res, "srvacl");
6648         i_srvoptions = PQfnumber(res, "srvoptions");
6649
6650         for (i = 0; i < ntups; i++)
6651         {
6652                 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
6653                 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6654                 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6655                 AssignDumpId(&srvinfo[i].dobj);
6656                 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
6657                 srvinfo[i].dobj.namespace = NULL;
6658                 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6659                 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
6660                 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
6661                 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
6662                 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
6663                 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
6664
6665                 /* Decide whether we want to dump it */
6666                 selectDumpableObject(&(srvinfo[i].dobj));
6667         }
6668
6669         PQclear(res);
6670
6671         destroyPQExpBuffer(query);
6672
6673         return srvinfo;
6674 }
6675
6676 /*
6677  * getDefaultACLs:
6678  *        read all default ACL information in the system catalogs and return
6679  *        them in the DefaultACLInfo structure
6680  *
6681  *      numDefaultACLs is set to the number of ACLs read in
6682  */
6683 DefaultACLInfo *
6684 getDefaultACLs(Archive *fout, int *numDefaultACLs)
6685 {
6686         DefaultACLInfo *daclinfo;
6687         PQExpBuffer query;
6688         PGresult   *res;
6689         int                     i_oid;
6690         int                     i_tableoid;
6691         int                     i_defaclrole;
6692         int                     i_defaclnamespace;
6693         int                     i_defaclobjtype;
6694         int                     i_defaclacl;
6695         int                     i,
6696                                 ntups;
6697
6698         if (fout->remoteVersion < 90000)
6699         {
6700                 *numDefaultACLs = 0;
6701                 return NULL;
6702         }
6703
6704         query = createPQExpBuffer();
6705
6706         /* Make sure we are in proper schema */
6707         selectSourceSchema(fout, "pg_catalog");
6708
6709         appendPQExpBuffer(query, "SELECT oid, tableoid, "
6710                                           "(%s defaclrole) AS defaclrole, "
6711                                           "defaclnamespace, "
6712                                           "defaclobjtype, "
6713                                           "defaclacl "
6714                                           "FROM pg_default_acl",
6715                                           username_subquery);
6716
6717         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6718
6719         ntups = PQntuples(res);
6720         *numDefaultACLs = ntups;
6721
6722         daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
6723
6724         i_oid = PQfnumber(res, "oid");
6725         i_tableoid = PQfnumber(res, "tableoid");
6726         i_defaclrole = PQfnumber(res, "defaclrole");
6727         i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6728         i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6729         i_defaclacl = PQfnumber(res, "defaclacl");
6730
6731         for (i = 0; i < ntups; i++)
6732         {
6733                 Oid                     nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6734
6735                 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6736                 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6737                 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6738                 AssignDumpId(&daclinfo[i].dobj);
6739                 /* cheesy ... is it worth coming up with a better object name? */
6740                 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
6741
6742                 if (nspid != InvalidOid)
6743                         daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
6744                                                                                                  daclinfo[i].dobj.catId.oid);
6745                 else
6746                         daclinfo[i].dobj.namespace = NULL;
6747
6748                 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
6749                 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6750                 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
6751
6752                 /* Decide whether we want to dump it */
6753                 selectDumpableDefaultACL(&(daclinfo[i]));
6754         }
6755
6756         PQclear(res);
6757
6758         destroyPQExpBuffer(query);
6759
6760         return daclinfo;
6761 }
6762
6763 /*
6764  * dumpComment --
6765  *
6766  * This routine is used to dump any comments associated with the
6767  * object handed to this routine. The routine takes a constant character
6768  * string for the target part of the comment-creation command, plus
6769  * the namespace and owner of the object (for labeling the ArchiveEntry),
6770  * plus catalog ID and subid which are the lookup key for pg_description,
6771  * plus the dump ID for the object (for setting a dependency).
6772  * If a matching pg_description entry is found, it is dumped.
6773  *
6774  * Note: although this routine takes a dumpId for dependency purposes,
6775  * that purpose is just to mark the dependency in the emitted dump file
6776  * for possible future use by pg_restore.  We do NOT use it for determining
6777  * ordering of the comment in the dump file, because this routine is called
6778  * after dependency sorting occurs.  This routine should be called just after
6779  * calling ArchiveEntry() for the specified object.
6780  */
6781 static void
6782 dumpComment(Archive *fout, const char *target,
6783                         const char *namespace, const char *owner,
6784                         CatalogId catalogId, int subid, DumpId dumpId)
6785 {
6786         CommentItem *comments;
6787         int                     ncomments;
6788
6789         /* Comments are schema not data ... except blob comments are data */
6790         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6791         {
6792                 if (dataOnly)
6793                         return;
6794         }
6795         else
6796         {
6797                 if (schemaOnly)
6798                         return;
6799         }
6800
6801         /* Search for comments associated with catalogId, using table */
6802         ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6803                                                          &comments);
6804
6805         /* Is there one matching the subid? */
6806         while (ncomments > 0)
6807         {
6808                 if (comments->objsubid == subid)
6809                         break;
6810                 comments++;
6811                 ncomments--;
6812         }
6813
6814         /* If a comment exists, build COMMENT ON statement */
6815         if (ncomments > 0)
6816         {
6817                 PQExpBuffer query = createPQExpBuffer();
6818
6819                 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
6820                 appendStringLiteralAH(query, comments->descr, fout);
6821                 appendPQExpBuffer(query, ";\n");
6822
6823                 /*
6824                  * We mark comments as SECTION_NONE because they really belong in the
6825                  * same section as their parent, whether that is pre-data or
6826                  * post-data.
6827                  */
6828                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6829                                          target, namespace, NULL, owner,
6830                                          false, "COMMENT", SECTION_NONE,
6831                                          query->data, "", NULL,
6832                                          &(dumpId), 1,
6833                                          NULL, NULL);
6834
6835                 destroyPQExpBuffer(query);
6836         }
6837 }
6838
6839 /*
6840  * dumpTableComment --
6841  *
6842  * As above, but dump comments for both the specified table (or view)
6843  * and its columns.
6844  */
6845 static void
6846 dumpTableComment(Archive *fout, TableInfo *tbinfo,
6847                                  const char *reltypename)
6848 {
6849         CommentItem *comments;
6850         int                     ncomments;
6851         PQExpBuffer query;
6852         PQExpBuffer target;
6853
6854         /* Comments are SCHEMA not data */
6855         if (dataOnly)
6856                 return;
6857
6858         /* Search for comments associated with relation, using table */
6859         ncomments = findComments(fout,
6860                                                          tbinfo->dobj.catId.tableoid,
6861                                                          tbinfo->dobj.catId.oid,
6862                                                          &comments);
6863
6864         /* If comments exist, build COMMENT ON statements */
6865         if (ncomments <= 0)
6866                 return;
6867
6868         query = createPQExpBuffer();
6869         target = createPQExpBuffer();
6870
6871         while (ncomments > 0)
6872         {
6873                 const char *descr = comments->descr;
6874                 int                     objsubid = comments->objsubid;
6875
6876                 if (objsubid == 0)
6877                 {
6878                         resetPQExpBuffer(target);
6879                         appendPQExpBuffer(target, "%s %s", reltypename,
6880                                                           fmtId(tbinfo->dobj.name));
6881
6882                         resetPQExpBuffer(query);
6883                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6884                         appendStringLiteralAH(query, descr, fout);
6885                         appendPQExpBuffer(query, ";\n");
6886
6887                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
6888                                                  target->data,
6889                                                  tbinfo->dobj.namespace->dobj.name,
6890                                                  NULL, tbinfo->rolname,
6891                                                  false, "COMMENT", SECTION_NONE,
6892                                                  query->data, "", NULL,
6893                                                  &(tbinfo->dobj.dumpId), 1,
6894                                                  NULL, NULL);
6895                 }
6896                 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
6897                 {
6898                         resetPQExpBuffer(target);
6899                         appendPQExpBuffer(target, "COLUMN %s.",
6900                                                           fmtId(tbinfo->dobj.name));
6901                         appendPQExpBuffer(target, "%s",
6902                                                           fmtId(tbinfo->attnames[objsubid - 1]));
6903
6904                         resetPQExpBuffer(query);
6905                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6906                         appendStringLiteralAH(query, descr, fout);
6907                         appendPQExpBuffer(query, ";\n");
6908
6909                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
6910                                                  target->data,
6911                                                  tbinfo->dobj.namespace->dobj.name,
6912                                                  NULL, tbinfo->rolname,
6913                                                  false, "COMMENT", SECTION_NONE,
6914                                                  query->data, "", NULL,
6915                                                  &(tbinfo->dobj.dumpId), 1,
6916                                                  NULL, NULL);
6917                 }
6918
6919                 comments++;
6920                 ncomments--;
6921         }
6922
6923         destroyPQExpBuffer(query);
6924         destroyPQExpBuffer(target);
6925 }
6926
6927 /*
6928  * findComments --
6929  *
6930  * Find the comment(s), if any, associated with the given object.  All the
6931  * objsubid values associated with the given classoid/objoid are found with
6932  * one search.
6933  */
6934 static int
6935 findComments(Archive *fout, Oid classoid, Oid objoid,
6936                          CommentItem **items)
6937 {
6938         /* static storage for table of comments */
6939         static CommentItem *comments = NULL;
6940         static int      ncomments = -1;
6941
6942         CommentItem *middle = NULL;
6943         CommentItem *low;
6944         CommentItem *high;
6945         int                     nmatch;
6946
6947         /* Get comments if we didn't already */
6948         if (ncomments < 0)
6949                 ncomments = collectComments(fout, &comments);
6950
6951         /*
6952          * Pre-7.2, pg_description does not contain classoid, so collectComments
6953          * just stores a zero.  If there's a collision on object OID, well, you
6954          * get duplicate comments.
6955          */
6956         if (fout->remoteVersion < 70200)
6957                 classoid = 0;
6958
6959         /*
6960          * Do binary search to find some item matching the object.
6961          */
6962         low = &comments[0];
6963         high = &comments[ncomments - 1];
6964         while (low <= high)
6965         {
6966                 middle = low + (high - low) / 2;
6967
6968                 if (classoid < middle->classoid)
6969                         high = middle - 1;
6970                 else if (classoid > middle->classoid)
6971                         low = middle + 1;
6972                 else if (objoid < middle->objoid)
6973                         high = middle - 1;
6974                 else if (objoid > middle->objoid)
6975                         low = middle + 1;
6976                 else
6977                         break;                          /* found a match */
6978         }
6979
6980         if (low > high)                         /* no matches */
6981         {
6982                 *items = NULL;
6983                 return 0;
6984         }
6985
6986         /*
6987          * Now determine how many items match the object.  The search loop
6988          * invariant still holds: only items between low and high inclusive could
6989          * match.
6990          */
6991         nmatch = 1;
6992         while (middle > low)
6993         {
6994                 if (classoid != middle[-1].classoid ||
6995                         objoid != middle[-1].objoid)
6996                         break;
6997                 middle--;
6998                 nmatch++;
6999         }
7000
7001         *items = middle;
7002
7003         middle += nmatch;
7004         while (middle <= high)
7005         {
7006                 if (classoid != middle->classoid ||
7007                         objoid != middle->objoid)
7008                         break;
7009                 middle++;
7010                 nmatch++;
7011         }
7012
7013         return nmatch;
7014 }
7015
7016 /*
7017  * collectComments --
7018  *
7019  * Construct a table of all comments available for database objects.
7020  * We used to do per-object queries for the comments, but it's much faster
7021  * to pull them all over at once, and on most databases the memory cost
7022  * isn't high.
7023  *
7024  * The table is sorted by classoid/objid/objsubid for speed in lookup.
7025  */
7026 static int
7027 collectComments(Archive *fout, CommentItem **items)
7028 {
7029         PGresult   *res;
7030         PQExpBuffer query;
7031         int                     i_description;
7032         int                     i_classoid;
7033         int                     i_objoid;
7034         int                     i_objsubid;
7035         int                     ntups;
7036         int                     i;
7037         CommentItem *comments;
7038
7039         /*
7040          * Note we do NOT change source schema here; preserve the caller's
7041          * setting, instead.
7042          */
7043
7044         query = createPQExpBuffer();
7045
7046         if (fout->remoteVersion >= 70300)
7047         {
7048                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7049                                                   "FROM pg_catalog.pg_description "
7050                                                   "ORDER BY classoid, objoid, objsubid");
7051         }
7052         else if (fout->remoteVersion >= 70200)
7053         {
7054                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7055                                                   "FROM pg_description "
7056                                                   "ORDER BY classoid, objoid, objsubid");
7057         }
7058         else
7059         {
7060                 /* Note: this will fail to find attribute comments in pre-7.2... */
7061                 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7062                                                   "FROM pg_description "
7063                                                   "ORDER BY objoid");
7064         }
7065
7066         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7067
7068         /* Construct lookup table containing OIDs in numeric form */
7069
7070         i_description = PQfnumber(res, "description");
7071         i_classoid = PQfnumber(res, "classoid");
7072         i_objoid = PQfnumber(res, "objoid");
7073         i_objsubid = PQfnumber(res, "objsubid");
7074
7075         ntups = PQntuples(res);
7076
7077         comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7078
7079         for (i = 0; i < ntups; i++)
7080         {
7081                 comments[i].descr = PQgetvalue(res, i, i_description);
7082                 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7083                 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7084                 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7085         }
7086
7087         /* Do NOT free the PGresult since we are keeping pointers into it */
7088         destroyPQExpBuffer(query);
7089
7090         *items = comments;
7091         return ntups;
7092 }
7093
7094 /*
7095  * dumpDumpableObject
7096  *
7097  * This routine and its subsidiaries are responsible for creating
7098  * ArchiveEntries (TOC objects) for each object to be dumped.
7099  */
7100 static void
7101 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7102 {
7103
7104         bool skip = false;
7105
7106         switch (dobj->objType)
7107         {
7108                 case DO_INDEX:
7109                 case DO_TRIGGER:
7110                 case DO_CONSTRAINT:
7111                 case DO_FK_CONSTRAINT:
7112                 case DO_RULE:
7113                         skip = !(dumpSections & DUMP_POST_DATA);
7114                         break;
7115                 case DO_TABLE_DATA:
7116                         skip = !(dumpSections & DUMP_DATA);
7117                         break;
7118                 default:
7119                         skip = !(dumpSections & DUMP_PRE_DATA);
7120         }
7121
7122         if (skip)
7123                 return;
7124
7125         switch (dobj->objType)
7126         {
7127                 case DO_NAMESPACE:
7128                         dumpNamespace(fout, (NamespaceInfo *) dobj);
7129                         break;
7130                 case DO_EXTENSION:
7131                         dumpExtension(fout, (ExtensionInfo *) dobj);
7132                         break;
7133                 case DO_TYPE:
7134                         dumpType(fout, (TypeInfo *) dobj);
7135                         break;
7136                 case DO_SHELL_TYPE:
7137                         dumpShellType(fout, (ShellTypeInfo *) dobj);
7138                         break;
7139                 case DO_FUNC:
7140                         dumpFunc(fout, (FuncInfo *) dobj);
7141                         break;
7142                 case DO_AGG:
7143                         dumpAgg(fout, (AggInfo *) dobj);
7144                         break;
7145                 case DO_OPERATOR:
7146                         dumpOpr(fout, (OprInfo *) dobj);
7147                         break;
7148                 case DO_OPCLASS:
7149                         dumpOpclass(fout, (OpclassInfo *) dobj);
7150                         break;
7151                 case DO_OPFAMILY:
7152                         dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7153                         break;
7154                 case DO_COLLATION:
7155                         dumpCollation(fout, (CollInfo *) dobj);
7156                         break;
7157                 case DO_CONVERSION:
7158                         dumpConversion(fout, (ConvInfo *) dobj);
7159                         break;
7160                 case DO_TABLE:
7161                         dumpTable(fout, (TableInfo *) dobj);
7162                         break;
7163                 case DO_ATTRDEF:
7164                         dumpAttrDef(fout, (AttrDefInfo *) dobj);
7165                         break;
7166                 case DO_INDEX:
7167                         dumpIndex(fout, (IndxInfo *) dobj);
7168                         break;
7169                 case DO_RULE:
7170                         dumpRule(fout, (RuleInfo *) dobj);
7171                         break;
7172                 case DO_TRIGGER:
7173                         dumpTrigger(fout, (TriggerInfo *) dobj);
7174                         break;
7175                 case DO_CONSTRAINT:
7176                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7177                         break;
7178                 case DO_FK_CONSTRAINT:
7179                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7180                         break;
7181                 case DO_PROCLANG:
7182                         dumpProcLang(fout, (ProcLangInfo *) dobj);
7183                         break;
7184                 case DO_CAST:
7185                         dumpCast(fout, (CastInfo *) dobj);
7186                         break;
7187                 case DO_TABLE_DATA:
7188                         dumpTableData(fout, (TableDataInfo *) dobj);
7189                         break;
7190                 case DO_DUMMY_TYPE:
7191                         /* table rowtypes and array types are never dumped separately */
7192                         break;
7193                 case DO_TSPARSER:
7194                         dumpTSParser(fout, (TSParserInfo *) dobj);
7195                         break;
7196                 case DO_TSDICT:
7197                         dumpTSDictionary(fout, (TSDictInfo *) dobj);
7198                         break;
7199                 case DO_TSTEMPLATE:
7200                         dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7201                         break;
7202                 case DO_TSCONFIG:
7203                         dumpTSConfig(fout, (TSConfigInfo *) dobj);
7204                         break;
7205                 case DO_FDW:
7206                         dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7207                         break;
7208                 case DO_FOREIGN_SERVER:
7209                         dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7210                         break;
7211                 case DO_DEFAULT_ACL:
7212                         dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7213                         break;
7214                 case DO_BLOB:
7215                         dumpBlob(fout, (BlobInfo *) dobj);
7216                         break;
7217                 case DO_BLOB_DATA:
7218                         ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7219                                                  dobj->name, NULL, NULL, "",
7220                                                  false, "BLOBS", SECTION_DATA,
7221                                                  "", "", NULL,
7222                                                  dobj->dependencies, dobj->nDeps,
7223                                                  dumpBlobs, NULL);
7224                         break;
7225         }
7226 }
7227
7228 /*
7229  * dumpNamespace
7230  *        writes out to fout the queries to recreate a user-defined namespace
7231  */
7232 static void
7233 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7234 {
7235         PQExpBuffer q;
7236         PQExpBuffer delq;
7237         PQExpBuffer labelq;
7238         char       *qnspname;
7239
7240         /* Skip if not to be dumped */
7241         if (!nspinfo->dobj.dump || dataOnly)
7242                 return;
7243
7244         /* don't dump dummy namespace from pre-7.3 source */
7245         if (strlen(nspinfo->dobj.name) == 0)
7246                 return;
7247
7248         q = createPQExpBuffer();
7249         delq = createPQExpBuffer();
7250         labelq = createPQExpBuffer();
7251
7252         qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7253
7254         appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7255
7256         appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7257
7258         appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7259
7260         if (binary_upgrade)
7261                 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7262
7263         ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7264                                  nspinfo->dobj.name,
7265                                  NULL, NULL,
7266                                  nspinfo->rolname,
7267                                  false, "SCHEMA", SECTION_PRE_DATA,
7268                                  q->data, delq->data, NULL,
7269                                  nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
7270                                  NULL, NULL);
7271
7272         /* Dump Schema Comments and Security Labels */
7273         dumpComment(fout, labelq->data,
7274                                 NULL, nspinfo->rolname,
7275                                 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7276         dumpSecLabel(fout, labelq->data,
7277                                  NULL, nspinfo->rolname,
7278                                  nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7279
7280         dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7281                         qnspname, NULL, nspinfo->dobj.name, NULL,
7282                         nspinfo->rolname, nspinfo->nspacl);
7283
7284         free(qnspname);
7285
7286         destroyPQExpBuffer(q);
7287         destroyPQExpBuffer(delq);
7288         destroyPQExpBuffer(labelq);
7289 }
7290
7291 /*
7292  * dumpExtension
7293  *        writes out to fout the queries to recreate an extension
7294  */
7295 static void
7296 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7297 {
7298         PQExpBuffer q;
7299         PQExpBuffer delq;
7300         PQExpBuffer labelq;
7301         char       *qextname;
7302
7303         /* Skip if not to be dumped */
7304         if (!extinfo->dobj.dump || dataOnly)
7305                 return;
7306
7307         q = createPQExpBuffer();
7308         delq = createPQExpBuffer();
7309         labelq = createPQExpBuffer();
7310
7311         qextname = pg_strdup(fmtId(extinfo->dobj.name));
7312
7313         appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7314
7315         if (!binary_upgrade)
7316         {
7317                 /*
7318                  * In a regular dump, we use IF NOT EXISTS so that there isn't a
7319                  * problem if the extension already exists in the target database;
7320                  * this is essential for installed-by-default extensions such as
7321                  * plpgsql.
7322                  *
7323                  * In binary-upgrade mode, that doesn't work well, so instead we skip
7324                  * built-in extensions based on their OIDs; see
7325                  * selectDumpableExtension.
7326                  */
7327                 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7328                                                   qextname, fmtId(extinfo->namespace));
7329         }
7330         else
7331         {
7332                 int                     i;
7333                 int                     n;
7334
7335                 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7336                 appendPQExpBuffer(q,
7337                                                   "SELECT binary_upgrade.create_empty_extension(");
7338                 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7339                 appendPQExpBuffer(q, ", ");
7340                 appendStringLiteralAH(q, extinfo->namespace, fout);
7341                 appendPQExpBuffer(q, ", ");
7342                 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7343                 appendStringLiteralAH(q, extinfo->extversion, fout);
7344                 appendPQExpBuffer(q, ", ");
7345
7346                 /*
7347                  * Note that we're pushing extconfig (an OID array) back into
7348                  * pg_extension exactly as-is.  This is OK because pg_class OIDs are
7349                  * preserved in binary upgrade.
7350                  */
7351                 if (strlen(extinfo->extconfig) > 2)
7352                         appendStringLiteralAH(q, extinfo->extconfig, fout);
7353                 else
7354                         appendPQExpBuffer(q, "NULL");
7355                 appendPQExpBuffer(q, ", ");
7356                 if (strlen(extinfo->extcondition) > 2)
7357                         appendStringLiteralAH(q, extinfo->extcondition, fout);
7358                 else
7359                         appendPQExpBuffer(q, "NULL");
7360                 appendPQExpBuffer(q, ", ");
7361                 appendPQExpBuffer(q, "ARRAY[");
7362                 n = 0;
7363                 for (i = 0; i < extinfo->dobj.nDeps; i++)
7364                 {
7365                         DumpableObject *extobj;
7366
7367                         extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7368                         if (extobj && extobj->objType == DO_EXTENSION)
7369                         {
7370                                 if (n++ > 0)
7371                                         appendPQExpBuffer(q, ",");
7372                                 appendStringLiteralAH(q, extobj->name, fout);
7373                         }
7374                 }
7375                 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7376                 appendPQExpBuffer(q, ");\n");
7377         }
7378
7379         appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7380
7381         ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7382                                  extinfo->dobj.name,
7383                                  NULL, NULL,
7384                                  "",
7385                                  false, "EXTENSION", SECTION_PRE_DATA,
7386                                  q->data, delq->data, NULL,
7387                                  extinfo->dobj.dependencies, extinfo->dobj.nDeps,
7388                                  NULL, NULL);
7389
7390         /* Dump Extension Comments and Security Labels */
7391         dumpComment(fout, labelq->data,
7392                                 NULL, "",
7393                                 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7394         dumpSecLabel(fout, labelq->data,
7395                                  NULL, "",
7396                                  extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7397
7398         free(qextname);
7399
7400         destroyPQExpBuffer(q);
7401         destroyPQExpBuffer(delq);
7402         destroyPQExpBuffer(labelq);
7403 }
7404
7405 /*
7406  * dumpType
7407  *        writes out to fout the queries to recreate a user-defined type
7408  */
7409 static void
7410 dumpType(Archive *fout, TypeInfo *tyinfo)
7411 {
7412         /* Skip if not to be dumped */
7413         if (!tyinfo->dobj.dump || dataOnly)
7414                 return;
7415
7416         /* Dump out in proper style */
7417         if (tyinfo->typtype == TYPTYPE_BASE)
7418                 dumpBaseType(fout, tyinfo);
7419         else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7420                 dumpDomain(fout, tyinfo);
7421         else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7422                 dumpCompositeType(fout, tyinfo);
7423         else if (tyinfo->typtype == TYPTYPE_ENUM)
7424                 dumpEnumType(fout, tyinfo);
7425         else if (tyinfo->typtype == TYPTYPE_RANGE)
7426                 dumpRangeType(fout, tyinfo);
7427         else
7428                 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7429                                   tyinfo->dobj.name);
7430 }
7431
7432 /*
7433  * dumpEnumType
7434  *        writes out to fout the queries to recreate a user-defined enum type
7435  */
7436 static void
7437 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7438 {
7439         PQExpBuffer q = createPQExpBuffer();
7440         PQExpBuffer delq = createPQExpBuffer();
7441         PQExpBuffer labelq = createPQExpBuffer();
7442         PQExpBuffer query = createPQExpBuffer();
7443         PGresult   *res;
7444         int                     num,
7445                                 i;
7446         Oid                     enum_oid;
7447         char       *label;
7448
7449         /* Set proper schema search path */
7450         selectSourceSchema(fout, "pg_catalog");
7451
7452         if (fout->remoteVersion >= 90100)
7453                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7454                                                   "FROM pg_catalog.pg_enum "
7455                                                   "WHERE enumtypid = '%u'"
7456                                                   "ORDER BY enumsortorder",
7457                                                   tyinfo->dobj.catId.oid);
7458         else
7459                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7460                                                   "FROM pg_catalog.pg_enum "
7461                                                   "WHERE enumtypid = '%u'"
7462                                                   "ORDER BY oid",
7463                                                   tyinfo->dobj.catId.oid);
7464
7465         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7466
7467         num = PQntuples(res);
7468
7469         /*
7470          * DROP must be fully qualified in case same name appears in pg_catalog.
7471          * CASCADE shouldn't be required here as for normal types since the I/O
7472          * functions are generic and do not get dropped.
7473          */
7474         appendPQExpBuffer(delq, "DROP TYPE %s.",
7475                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7476         appendPQExpBuffer(delq, "%s;\n",
7477                                           fmtId(tyinfo->dobj.name));
7478
7479         if (binary_upgrade)
7480                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7481                                                                                                  tyinfo->dobj.catId.oid);
7482
7483         appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7484                                           fmtId(tyinfo->dobj.name));
7485
7486         if (!binary_upgrade)
7487         {
7488                 /* Labels with server-assigned oids */
7489                 for (i = 0; i < num; i++)
7490                 {
7491                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7492                         if (i > 0)
7493                                 appendPQExpBuffer(q, ",");
7494                         appendPQExpBuffer(q, "\n    ");
7495                         appendStringLiteralAH(q, label, fout);
7496                 }
7497         }
7498
7499         appendPQExpBuffer(q, "\n);\n");
7500
7501         if (binary_upgrade)
7502         {
7503                 /* Labels with dump-assigned (preserved) oids */
7504                 for (i = 0; i < num; i++)
7505                 {
7506                         enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7507                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7508
7509                         if (i == 0)
7510                                 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7511                         appendPQExpBuffer(q,
7512                                                           "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7513                                                           enum_oid);
7514                         appendPQExpBuffer(q, "ALTER TYPE %s.",
7515                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7516                         appendPQExpBuffer(q, "%s ADD VALUE ",
7517                                                           fmtId(tyinfo->dobj.name));
7518                         appendStringLiteralAH(q, label, fout);
7519                         appendPQExpBuffer(q, ";\n\n");
7520                 }
7521         }
7522
7523         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7524
7525         if (binary_upgrade)
7526                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7527
7528         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7529                                  tyinfo->dobj.name,
7530                                  tyinfo->dobj.namespace->dobj.name,
7531                                  NULL,
7532                                  tyinfo->rolname, false,
7533                                  "TYPE", SECTION_PRE_DATA,
7534                                  q->data, delq->data, NULL,
7535                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7536                                  NULL, NULL);
7537
7538         /* Dump Type Comments and Security Labels */
7539         dumpComment(fout, labelq->data,
7540                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7541                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7542         dumpSecLabel(fout, labelq->data,
7543                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7544                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7545
7546         PQclear(res);
7547         destroyPQExpBuffer(q);
7548         destroyPQExpBuffer(delq);
7549         destroyPQExpBuffer(labelq);
7550         destroyPQExpBuffer(query);
7551 }
7552
7553 /*
7554  * dumpRangeType
7555  *        writes out to fout the queries to recreate a user-defined range type
7556  */
7557 static void
7558 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7559 {
7560         PQExpBuffer q = createPQExpBuffer();
7561         PQExpBuffer delq = createPQExpBuffer();
7562         PQExpBuffer labelq = createPQExpBuffer();
7563         PQExpBuffer query = createPQExpBuffer();
7564         PGresult   *res;
7565         Oid                     collationOid;
7566         char       *procname;
7567
7568         /*
7569          * select appropriate schema to ensure names in CREATE are properly
7570          * qualified
7571          */
7572         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7573
7574         appendPQExpBuffer(query,
7575                                           "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7576                                           "opc.opcname AS opcname, "
7577                                           "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7578                                           "  WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7579                                           "opc.opcdefault, "
7580                                           "CASE WHEN rngcollation = st.typcollation THEN 0 "
7581                                           "     ELSE rngcollation END AS collation, "
7582                                           "rngcanonical, rngsubdiff "
7583                                           "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7584                                           "     pg_catalog.pg_opclass opc "
7585                                           "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7586                                           "rngtypid = '%u'",
7587                                           tyinfo->dobj.catId.oid);
7588
7589         res = ExecuteSqlQueryForSingleRow(fout, query->data);
7590
7591         /*
7592          * DROP must be fully qualified in case same name appears in pg_catalog.
7593          * CASCADE shouldn't be required here as for normal types since the I/O
7594          * functions are generic and do not get dropped.
7595          */
7596         appendPQExpBuffer(delq, "DROP TYPE %s.",
7597                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7598         appendPQExpBuffer(delq, "%s;\n",
7599                                           fmtId(tyinfo->dobj.name));
7600
7601         if (binary_upgrade)
7602                 binary_upgrade_set_type_oids_by_type_oid(fout,
7603                                                                                                  q, tyinfo->dobj.catId.oid);
7604
7605         appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7606                                           fmtId(tyinfo->dobj.name));
7607
7608         appendPQExpBuffer(q, "\n    subtype = %s",
7609                                           PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7610
7611         /* print subtype_opclass only if not default for subtype */
7612         if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7613         {
7614                 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7615                 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7616
7617                 /* always schema-qualify, don't try to be smart */
7618                 appendPQExpBuffer(q, ",\n    subtype_opclass = %s.",
7619                                                   fmtId(nspname));
7620                 appendPQExpBuffer(q, "%s", fmtId(opcname));
7621         }
7622
7623         collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
7624         if (OidIsValid(collationOid))
7625         {
7626                 CollInfo   *coll = findCollationByOid(collationOid);
7627
7628                 if (coll)
7629                 {
7630                         /* always schema-qualify, don't try to be smart */
7631                         appendPQExpBuffer(q, ",\n    collation = %s.",
7632                                                           fmtId(coll->dobj.namespace->dobj.name));
7633                         appendPQExpBuffer(q, "%s",
7634                                                           fmtId(coll->dobj.name));
7635                 }
7636         }
7637
7638         procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
7639         if (strcmp(procname, "-") != 0)
7640                 appendPQExpBuffer(q, ",\n    canonical = %s", procname);
7641
7642         procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
7643         if (strcmp(procname, "-") != 0)
7644                 appendPQExpBuffer(q, ",\n    subtype_diff = %s", procname);
7645
7646         appendPQExpBuffer(q, "\n);\n");
7647
7648         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7649
7650         if (binary_upgrade)
7651                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7652
7653         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7654                                  tyinfo->dobj.name,
7655                                  tyinfo->dobj.namespace->dobj.name,
7656                                  NULL,
7657                                  tyinfo->rolname, false,
7658                                  "TYPE", SECTION_PRE_DATA,
7659                                  q->data, delq->data, NULL,
7660                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7661                                  NULL, NULL);
7662
7663         /* Dump Type Comments and Security Labels */
7664         dumpComment(fout, labelq->data,
7665                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7666                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7667         dumpSecLabel(fout, labelq->data,
7668                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7669                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7670
7671         PQclear(res);
7672         destroyPQExpBuffer(q);
7673         destroyPQExpBuffer(delq);
7674         destroyPQExpBuffer(labelq);
7675         destroyPQExpBuffer(query);
7676 }
7677
7678 /*
7679  * dumpBaseType
7680  *        writes out to fout the queries to recreate a user-defined base type
7681  */
7682 static void
7683 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
7684 {
7685         PQExpBuffer q = createPQExpBuffer();
7686         PQExpBuffer delq = createPQExpBuffer();
7687         PQExpBuffer labelq = createPQExpBuffer();
7688         PQExpBuffer query = createPQExpBuffer();
7689         PGresult   *res;
7690         char       *typlen;
7691         char       *typinput;
7692         char       *typoutput;
7693         char       *typreceive;
7694         char       *typsend;
7695         char       *typmodin;
7696         char       *typmodout;
7697         char       *typanalyze;
7698         Oid                     typreceiveoid;
7699         Oid                     typsendoid;
7700         Oid                     typmodinoid;
7701         Oid                     typmodoutoid;
7702         Oid                     typanalyzeoid;
7703         char       *typcategory;
7704         char       *typispreferred;
7705         char       *typdelim;
7706         char       *typbyval;
7707         char       *typalign;
7708         char       *typstorage;
7709         char       *typcollatable;
7710         char       *typdefault;
7711         bool            typdefault_is_literal = false;
7712
7713         /* Set proper schema search path so regproc references list correctly */
7714         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7715
7716         /* Fetch type-specific details */
7717         if (fout->remoteVersion >= 90100)
7718         {
7719                 appendPQExpBuffer(query, "SELECT typlen, "
7720                                                   "typinput, typoutput, typreceive, typsend, "
7721                                                   "typmodin, typmodout, typanalyze, "
7722                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7723                                                   "typsend::pg_catalog.oid AS typsendoid, "
7724                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7725                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7726                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7727                                                   "typcategory, typispreferred, "
7728                                                   "typdelim, typbyval, typalign, typstorage, "
7729                                                   "(typcollation <> 0) AS typcollatable, "
7730                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7731                                                   "FROM pg_catalog.pg_type "
7732                                                   "WHERE oid = '%u'::pg_catalog.oid",
7733                                                   tyinfo->dobj.catId.oid);
7734         }
7735         else if (fout->remoteVersion >= 80400)
7736         {
7737                 appendPQExpBuffer(query, "SELECT typlen, "
7738                                                   "typinput, typoutput, typreceive, typsend, "
7739                                                   "typmodin, typmodout, typanalyze, "
7740                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7741                                                   "typsend::pg_catalog.oid AS typsendoid, "
7742                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7743                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7744                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7745                                                   "typcategory, typispreferred, "
7746                                                   "typdelim, typbyval, typalign, typstorage, "
7747                                                   "false AS typcollatable, "
7748                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7749                                                   "FROM pg_catalog.pg_type "
7750                                                   "WHERE oid = '%u'::pg_catalog.oid",
7751                                                   tyinfo->dobj.catId.oid);
7752         }
7753         else if (fout->remoteVersion >= 80300)
7754         {
7755                 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
7756                 appendPQExpBuffer(query, "SELECT typlen, "
7757                                                   "typinput, typoutput, typreceive, typsend, "
7758                                                   "typmodin, typmodout, typanalyze, "
7759                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7760                                                   "typsend::pg_catalog.oid AS typsendoid, "
7761                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7762                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7763                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7764                                                   "'U' AS typcategory, false AS typispreferred, "
7765                                                   "typdelim, typbyval, typalign, typstorage, "
7766                                                   "false AS typcollatable, "
7767                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7768                                                   "FROM pg_catalog.pg_type "
7769                                                   "WHERE oid = '%u'::pg_catalog.oid",
7770                                                   tyinfo->dobj.catId.oid);
7771         }
7772         else if (fout->remoteVersion >= 80000)
7773         {
7774                 appendPQExpBuffer(query, "SELECT typlen, "
7775                                                   "typinput, typoutput, typreceive, typsend, "
7776                                                   "'-' AS typmodin, '-' AS typmodout, "
7777                                                   "typanalyze, "
7778                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7779                                                   "typsend::pg_catalog.oid AS typsendoid, "
7780                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7781                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7782                                                   "'U' AS typcategory, false AS typispreferred, "
7783                                                   "typdelim, typbyval, typalign, typstorage, "
7784                                                   "false AS typcollatable, "
7785                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7786                                                   "FROM pg_catalog.pg_type "
7787                                                   "WHERE oid = '%u'::pg_catalog.oid",
7788                                                   tyinfo->dobj.catId.oid);
7789         }
7790         else if (fout->remoteVersion >= 70400)
7791         {
7792                 appendPQExpBuffer(query, "SELECT typlen, "
7793                                                   "typinput, typoutput, typreceive, typsend, "
7794                                                   "'-' AS typmodin, '-' AS typmodout, "
7795                                                   "'-' AS typanalyze, "
7796                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7797                                                   "typsend::pg_catalog.oid AS typsendoid, "
7798                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7799                                                   "0 AS typanalyzeoid, "
7800                                                   "'U' AS typcategory, false AS typispreferred, "
7801                                                   "typdelim, typbyval, typalign, typstorage, "
7802                                                   "false AS typcollatable, "
7803                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7804                                                   "FROM pg_catalog.pg_type "
7805                                                   "WHERE oid = '%u'::pg_catalog.oid",
7806                                                   tyinfo->dobj.catId.oid);
7807         }
7808         else if (fout->remoteVersion >= 70300)
7809         {
7810                 appendPQExpBuffer(query, "SELECT typlen, "
7811                                                   "typinput, typoutput, "
7812                                                   "'-' AS typreceive, '-' AS typsend, "
7813                                                   "'-' AS typmodin, '-' AS typmodout, "
7814                                                   "'-' AS typanalyze, "
7815                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7816                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7817                                                   "0 AS typanalyzeoid, "
7818                                                   "'U' AS typcategory, false AS typispreferred, "
7819                                                   "typdelim, typbyval, typalign, typstorage, "
7820                                                   "false AS typcollatable, "
7821                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7822                                                   "FROM pg_catalog.pg_type "
7823                                                   "WHERE oid = '%u'::pg_catalog.oid",
7824                                                   tyinfo->dobj.catId.oid);
7825         }
7826         else if (fout->remoteVersion >= 70200)
7827         {
7828                 /*
7829                  * Note: although pre-7.3 catalogs contain typreceive and typsend,
7830                  * ignore them because they are not right.
7831                  */
7832                 appendPQExpBuffer(query, "SELECT typlen, "
7833                                                   "typinput, typoutput, "
7834                                                   "'-' AS typreceive, '-' AS typsend, "
7835                                                   "'-' AS typmodin, '-' AS typmodout, "
7836                                                   "'-' AS typanalyze, "
7837                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7838                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7839                                                   "0 AS typanalyzeoid, "
7840                                                   "'U' AS typcategory, false AS typispreferred, "
7841                                                   "typdelim, typbyval, typalign, typstorage, "
7842                                                   "false AS typcollatable, "
7843                                                   "NULL AS typdefaultbin, typdefault "
7844                                                   "FROM pg_type "
7845                                                   "WHERE oid = '%u'::oid",
7846                                                   tyinfo->dobj.catId.oid);
7847         }
7848         else if (fout->remoteVersion >= 70100)
7849         {
7850                 /*
7851                  * Ignore pre-7.2 typdefault; the field exists but has an unusable
7852                  * representation.
7853                  */
7854                 appendPQExpBuffer(query, "SELECT typlen, "
7855                                                   "typinput, typoutput, "
7856                                                   "'-' AS typreceive, '-' AS typsend, "
7857                                                   "'-' AS typmodin, '-' AS typmodout, "
7858                                                   "'-' AS typanalyze, "
7859                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7860                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7861                                                   "0 AS typanalyzeoid, "
7862                                                   "'U' AS typcategory, false AS typispreferred, "
7863                                                   "typdelim, typbyval, typalign, typstorage, "
7864                                                   "false AS typcollatable, "
7865                                                   "NULL AS typdefaultbin, NULL AS typdefault "
7866                                                   "FROM pg_type "
7867                                                   "WHERE oid = '%u'::oid",
7868                                                   tyinfo->dobj.catId.oid);
7869         }
7870         else
7871         {
7872                 appendPQExpBuffer(query, "SELECT typlen, "
7873                                                   "typinput, typoutput, "
7874                                                   "'-' AS typreceive, '-' AS typsend, "
7875                                                   "'-' AS typmodin, '-' AS typmodout, "
7876                                                   "'-' AS typanalyze, "
7877                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7878                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7879                                                   "0 AS typanalyzeoid, "
7880                                                   "'U' AS typcategory, false AS typispreferred, "
7881                                                   "typdelim, typbyval, typalign, "
7882                                                   "'p'::char AS typstorage, "
7883                                                   "false AS typcollatable, "
7884                                                   "NULL AS typdefaultbin, NULL AS typdefault "
7885                                                   "FROM pg_type "
7886                                                   "WHERE oid = '%u'::oid",
7887                                                   tyinfo->dobj.catId.oid);
7888         }
7889
7890         res = ExecuteSqlQueryForSingleRow(fout, query->data);
7891
7892         typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
7893         typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
7894         typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
7895         typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
7896         typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
7897         typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
7898         typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
7899         typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
7900         typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
7901         typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
7902         typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
7903         typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
7904         typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
7905         typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
7906         typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
7907         typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
7908         typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
7909         typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
7910         typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
7911         typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
7912         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
7913                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
7914         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
7915         {
7916                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
7917                 typdefault_is_literal = true;   /* it needs quotes */
7918         }
7919         else
7920                 typdefault = NULL;
7921
7922         /*
7923          * DROP must be fully qualified in case same name appears in pg_catalog.
7924          * The reason we include CASCADE is that the circular dependency between
7925          * the type and its I/O functions makes it impossible to drop the type any
7926          * other way.
7927          */
7928         appendPQExpBuffer(delq, "DROP TYPE %s.",
7929                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7930         appendPQExpBuffer(delq, "%s CASCADE;\n",
7931                                           fmtId(tyinfo->dobj.name));
7932
7933         /* We might already have a shell type, but setting pg_type_oid is harmless */
7934         if (binary_upgrade)
7935                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7936                                                                                                  tyinfo->dobj.catId.oid);
7937
7938         appendPQExpBuffer(q,
7939                                           "CREATE TYPE %s (\n"
7940                                           "    INTERNALLENGTH = %s",
7941                                           fmtId(tyinfo->dobj.name),
7942                                           (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
7943
7944         if (fout->remoteVersion >= 70300)
7945         {
7946                 /* regproc result is correctly quoted as of 7.3 */
7947                 appendPQExpBuffer(q, ",\n    INPUT = %s", typinput);
7948                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", typoutput);
7949                 if (OidIsValid(typreceiveoid))
7950                         appendPQExpBuffer(q, ",\n    RECEIVE = %s", typreceive);
7951                 if (OidIsValid(typsendoid))
7952                         appendPQExpBuffer(q, ",\n    SEND = %s", typsend);
7953                 if (OidIsValid(typmodinoid))
7954                         appendPQExpBuffer(q, ",\n    TYPMOD_IN = %s", typmodin);
7955                 if (OidIsValid(typmodoutoid))
7956                         appendPQExpBuffer(q, ",\n    TYPMOD_OUT = %s", typmodout);
7957                 if (OidIsValid(typanalyzeoid))
7958                         appendPQExpBuffer(q, ",\n    ANALYZE = %s", typanalyze);
7959         }
7960         else
7961         {
7962                 /* regproc delivers an unquoted name before 7.3 */
7963                 /* cannot combine these because fmtId uses static result area */
7964                 appendPQExpBuffer(q, ",\n    INPUT = %s", fmtId(typinput));
7965                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", fmtId(typoutput));
7966                 /* receive/send/typmodin/typmodout/analyze need not be printed */
7967         }
7968
7969         if (strcmp(typcollatable, "t") == 0)
7970                 appendPQExpBuffer(q, ",\n    COLLATABLE = true");
7971
7972         if (typdefault != NULL)
7973         {
7974                 appendPQExpBuffer(q, ",\n    DEFAULT = ");
7975                 if (typdefault_is_literal)
7976                         appendStringLiteralAH(q, typdefault, fout);
7977                 else
7978                         appendPQExpBufferStr(q, typdefault);
7979         }
7980
7981         if (OidIsValid(tyinfo->typelem))
7982         {
7983                 char       *elemType;
7984
7985                 /* reselect schema in case changed by function dump */
7986                 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7987                 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
7988                 appendPQExpBuffer(q, ",\n    ELEMENT = %s", elemType);
7989                 free(elemType);
7990         }
7991
7992         if (strcmp(typcategory, "U") != 0)
7993         {
7994                 appendPQExpBuffer(q, ",\n    CATEGORY = ");
7995                 appendStringLiteralAH(q, typcategory, fout);
7996         }
7997
7998         if (strcmp(typispreferred, "t") == 0)
7999                 appendPQExpBuffer(q, ",\n    PREFERRED = true");
8000
8001         if (typdelim && strcmp(typdelim, ",") != 0)
8002         {
8003                 appendPQExpBuffer(q, ",\n    DELIMITER = ");
8004                 appendStringLiteralAH(q, typdelim, fout);
8005         }
8006
8007         if (strcmp(typalign, "c") == 0)
8008                 appendPQExpBuffer(q, ",\n    ALIGNMENT = char");
8009         else if (strcmp(typalign, "s") == 0)
8010                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int2");
8011         else if (strcmp(typalign, "i") == 0)
8012                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int4");
8013         else if (strcmp(typalign, "d") == 0)
8014                 appendPQExpBuffer(q, ",\n    ALIGNMENT = double");
8015
8016         if (strcmp(typstorage, "p") == 0)
8017                 appendPQExpBuffer(q, ",\n    STORAGE = plain");
8018         else if (strcmp(typstorage, "e") == 0)
8019                 appendPQExpBuffer(q, ",\n    STORAGE = external");
8020         else if (strcmp(typstorage, "x") == 0)
8021                 appendPQExpBuffer(q, ",\n    STORAGE = extended");
8022         else if (strcmp(typstorage, "m") == 0)
8023                 appendPQExpBuffer(q, ",\n    STORAGE = main");
8024
8025         if (strcmp(typbyval, "t") == 0)
8026                 appendPQExpBuffer(q, ",\n    PASSEDBYVALUE");
8027
8028         appendPQExpBuffer(q, "\n);\n");
8029
8030         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8031
8032         if (binary_upgrade)
8033                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8034
8035         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8036                                  tyinfo->dobj.name,
8037                                  tyinfo->dobj.namespace->dobj.name,
8038                                  NULL,
8039                                  tyinfo->rolname, false,
8040                                  "TYPE", SECTION_PRE_DATA,
8041                                  q->data, delq->data, NULL,
8042                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8043                                  NULL, NULL);
8044
8045         /* Dump Type Comments and Security Labels */
8046         dumpComment(fout, labelq->data,
8047                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8048                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8049         dumpSecLabel(fout, labelq->data,
8050                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8051                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8052
8053         PQclear(res);
8054         destroyPQExpBuffer(q);
8055         destroyPQExpBuffer(delq);
8056         destroyPQExpBuffer(labelq);
8057         destroyPQExpBuffer(query);
8058 }
8059
8060 /*
8061  * dumpDomain
8062  *        writes out to fout the queries to recreate a user-defined domain
8063  */
8064 static void
8065 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8066 {
8067         PQExpBuffer q = createPQExpBuffer();
8068         PQExpBuffer delq = createPQExpBuffer();
8069         PQExpBuffer labelq = createPQExpBuffer();
8070         PQExpBuffer query = createPQExpBuffer();
8071         PGresult   *res;
8072         int                     i;
8073         char       *typnotnull;
8074         char       *typdefn;
8075         char       *typdefault;
8076         Oid                     typcollation;
8077         bool            typdefault_is_literal = false;
8078
8079         /* Set proper schema search path so type references list correctly */
8080         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8081
8082         /* Fetch domain specific details */
8083         if (fout->remoteVersion >= 90100)
8084         {
8085                 /* typcollation is new in 9.1 */
8086                 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8087                         "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8088                                                   "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8089                                                   "t.typdefault, "
8090                                                   "CASE WHEN t.typcollation <> u.typcollation "
8091                                                   "THEN t.typcollation ELSE 0 END AS typcollation "
8092                                                   "FROM pg_catalog.pg_type t "
8093                                  "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8094                                                   "WHERE t.oid = '%u'::pg_catalog.oid",
8095                                                   tyinfo->dobj.catId.oid);
8096         }
8097         else
8098         {
8099                 /* We assume here that remoteVersion must be at least 70300 */
8100                 appendPQExpBuffer(query, "SELECT typnotnull, "
8101                                 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8102                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8103                                                   "typdefault, 0 AS typcollation "
8104                                                   "FROM pg_catalog.pg_type "
8105                                                   "WHERE oid = '%u'::pg_catalog.oid",
8106                                                   tyinfo->dobj.catId.oid);
8107         }
8108
8109         res = ExecuteSqlQueryForSingleRow(fout, query->data);
8110
8111         typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8112         typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8113         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8114                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8115         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8116         {
8117                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8118                 typdefault_is_literal = true;   /* it needs quotes */
8119         }
8120         else
8121                 typdefault = NULL;
8122         typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8123
8124         if (binary_upgrade)
8125                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8126                                                                                                  tyinfo->dobj.catId.oid);
8127
8128         appendPQExpBuffer(q,
8129                                           "CREATE DOMAIN %s AS %s",
8130                                           fmtId(tyinfo->dobj.name),
8131                                           typdefn);
8132
8133         /* Print collation only if different from base type's collation */
8134         if (OidIsValid(typcollation))
8135         {
8136                 CollInfo   *coll;
8137
8138                 coll = findCollationByOid(typcollation);
8139                 if (coll)
8140                 {
8141                         /* always schema-qualify, don't try to be smart */
8142                         appendPQExpBuffer(q, " COLLATE %s.",
8143                                                           fmtId(coll->dobj.namespace->dobj.name));
8144                         appendPQExpBuffer(q, "%s",
8145                                                           fmtId(coll->dobj.name));
8146                 }
8147         }
8148
8149         if (typnotnull[0] == 't')
8150                 appendPQExpBuffer(q, " NOT NULL");
8151
8152         if (typdefault != NULL)
8153         {
8154                 appendPQExpBuffer(q, " DEFAULT ");
8155                 if (typdefault_is_literal)
8156                         appendStringLiteralAH(q, typdefault, fout);
8157                 else
8158                         appendPQExpBufferStr(q, typdefault);
8159         }
8160
8161         PQclear(res);
8162
8163         /*
8164          * Add any CHECK constraints for the domain
8165          */
8166         for (i = 0; i < tyinfo->nDomChecks; i++)
8167         {
8168                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8169
8170                 if (!domcheck->separate)
8171                         appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8172                                                           fmtId(domcheck->dobj.name), domcheck->condef);
8173         }
8174
8175         appendPQExpBuffer(q, ";\n");
8176
8177         /*
8178          * DROP must be fully qualified in case same name appears in pg_catalog
8179          */
8180         appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8181                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8182         appendPQExpBuffer(delq, "%s;\n",
8183                                           fmtId(tyinfo->dobj.name));
8184
8185         appendPQExpBuffer(labelq, "DOMAIN %s", fmtId(tyinfo->dobj.name));
8186
8187         if (binary_upgrade)
8188                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8189
8190         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8191                                  tyinfo->dobj.name,
8192                                  tyinfo->dobj.namespace->dobj.name,
8193                                  NULL,
8194                                  tyinfo->rolname, false,
8195                                  "DOMAIN", SECTION_PRE_DATA,
8196                                  q->data, delq->data, NULL,
8197                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8198                                  NULL, NULL);
8199
8200         /* Dump Domain Comments and Security Labels */
8201         dumpComment(fout, labelq->data,
8202                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8203                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8204         dumpSecLabel(fout, labelq->data,
8205                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8206                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8207
8208         destroyPQExpBuffer(q);
8209         destroyPQExpBuffer(delq);
8210         destroyPQExpBuffer(labelq);
8211         destroyPQExpBuffer(query);
8212 }
8213
8214 /*
8215  * dumpCompositeType
8216  *        writes out to fout the queries to recreate a user-defined stand-alone
8217  *        composite type
8218  */
8219 static void
8220 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8221 {
8222         PQExpBuffer q = createPQExpBuffer();
8223         PQExpBuffer dropped = createPQExpBuffer();
8224         PQExpBuffer delq = createPQExpBuffer();
8225         PQExpBuffer labelq = createPQExpBuffer();
8226         PQExpBuffer query = createPQExpBuffer();
8227         PGresult   *res;
8228         int                     ntups;
8229         int                     i_attname;
8230         int                     i_atttypdefn;
8231         int                     i_attlen;
8232         int                     i_attalign;
8233         int                     i_attisdropped;
8234         int                     i_attcollation;
8235         int                     i_typrelid;
8236         int                     i;
8237         int                     actual_atts;
8238
8239         /* Set proper schema search path so type references list correctly */
8240         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8241
8242         /* Fetch type specific details */
8243         if (fout->remoteVersion >= 90100)
8244         {
8245                 /*
8246                  * attcollation is new in 9.1.  Since we only want to dump COLLATE
8247                  * clauses for attributes whose collation is different from their
8248                  * type's default, we use a CASE here to suppress uninteresting
8249                  * attcollations cheaply.  atttypid will be 0 for dropped columns;
8250                  * collation does not matter for those.
8251                  */
8252                 appendPQExpBuffer(query, "SELECT a.attname, "
8253                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8254                                                   "a.attlen, a.attalign, a.attisdropped, "
8255                                                   "CASE WHEN a.attcollation <> at.typcollation "
8256                                                   "THEN a.attcollation ELSE 0 END AS attcollation, "
8257                                                   "ct.typrelid "
8258                                                   "FROM pg_catalog.pg_type ct "
8259                                 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8260                                         "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8261                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8262                                                   "ORDER BY a.attnum ",
8263                                                   tyinfo->dobj.catId.oid);
8264         }
8265         else
8266         {
8267                 /*
8268                  * We assume here that remoteVersion must be at least 70300.  Since
8269                  * ALTER TYPE could not drop columns until 9.1, attisdropped should
8270                  * always be false.
8271                  */
8272                 appendPQExpBuffer(query, "SELECT a.attname, "
8273                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8274                                                   "a.attlen, a.attalign, a.attisdropped, "
8275                                                   "0 AS attcollation, "
8276                                                   "ct.typrelid "
8277                                          "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8278                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8279                                                   "AND a.attrelid = ct.typrelid "
8280                                                   "ORDER BY a.attnum ",
8281                                                   tyinfo->dobj.catId.oid);
8282         }
8283
8284         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8285
8286         ntups = PQntuples(res);
8287
8288         i_attname = PQfnumber(res, "attname");
8289         i_atttypdefn = PQfnumber(res, "atttypdefn");
8290         i_attlen = PQfnumber(res, "attlen");
8291         i_attalign = PQfnumber(res, "attalign");
8292         i_attisdropped = PQfnumber(res, "attisdropped");
8293         i_attcollation = PQfnumber(res, "attcollation");
8294         i_typrelid = PQfnumber(res, "typrelid");
8295
8296         if (binary_upgrade)
8297         {
8298                 Oid                     typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8299
8300                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8301                                                                                                  tyinfo->dobj.catId.oid);
8302                 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8303         }
8304
8305         appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8306                                           fmtId(tyinfo->dobj.name));
8307
8308         actual_atts = 0;
8309         for (i = 0; i < ntups; i++)
8310         {
8311                 char       *attname;
8312                 char       *atttypdefn;
8313                 char       *attlen;
8314                 char       *attalign;
8315                 bool            attisdropped;
8316                 Oid                     attcollation;
8317
8318                 attname = PQgetvalue(res, i, i_attname);
8319                 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8320                 attlen = PQgetvalue(res, i, i_attlen);
8321                 attalign = PQgetvalue(res, i, i_attalign);
8322                 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8323                 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8324
8325                 if (attisdropped && !binary_upgrade)
8326                         continue;
8327
8328                 /* Format properly if not first attr */
8329                 if (actual_atts++ > 0)
8330                         appendPQExpBuffer(q, ",");
8331                 appendPQExpBuffer(q, "\n\t");
8332
8333                 if (!attisdropped)
8334                 {
8335                         appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8336
8337                         /* Add collation if not default for the column type */
8338                         if (OidIsValid(attcollation))
8339                         {
8340                                 CollInfo   *coll;
8341
8342                                 coll = findCollationByOid(attcollation);
8343                                 if (coll)
8344                                 {
8345                                         /* always schema-qualify, don't try to be smart */
8346                                         appendPQExpBuffer(q, " COLLATE %s.",
8347                                                                           fmtId(coll->dobj.namespace->dobj.name));
8348                                         appendPQExpBuffer(q, "%s",
8349                                                                           fmtId(coll->dobj.name));
8350                                 }
8351                         }
8352                 }
8353                 else
8354                 {
8355                         /*
8356                          * This is a dropped attribute and we're in binary_upgrade mode.
8357                          * Insert a placeholder for it in the CREATE TYPE command, and set
8358                          * length and alignment with direct UPDATE to the catalogs
8359                          * afterwards. See similar code in dumpTableSchema().
8360                          */
8361                         appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8362
8363                         /* stash separately for insertion after the CREATE TYPE */
8364                         appendPQExpBuffer(dropped,
8365                                           "\n-- For binary upgrade, recreate dropped column.\n");
8366                         appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8367                                                           "SET attlen = %s, "
8368                                                           "attalign = '%s', attbyval = false\n"
8369                                                           "WHERE attname = ", attlen, attalign);
8370                         appendStringLiteralAH(dropped, attname, fout);
8371                         appendPQExpBuffer(dropped, "\n  AND attrelid = ");
8372                         appendStringLiteralAH(dropped, fmtId(tyinfo->dobj.name), fout);
8373                         appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8374
8375                         appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8376                                                           fmtId(tyinfo->dobj.name));
8377                         appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8378                                                           fmtId(attname));
8379                 }
8380         }
8381         appendPQExpBuffer(q, "\n);\n");
8382         appendPQExpBufferStr(q, dropped->data);
8383
8384         /*
8385          * DROP must be fully qualified in case same name appears in pg_catalog
8386          */
8387         appendPQExpBuffer(delq, "DROP TYPE %s.",
8388                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8389         appendPQExpBuffer(delq, "%s;\n",
8390                                           fmtId(tyinfo->dobj.name));
8391
8392         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8393
8394         if (binary_upgrade)
8395                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8396
8397         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8398                                  tyinfo->dobj.name,
8399                                  tyinfo->dobj.namespace->dobj.name,
8400                                  NULL,
8401                                  tyinfo->rolname, false,
8402                                  "TYPE", SECTION_PRE_DATA,
8403                                  q->data, delq->data, NULL,
8404                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8405                                  NULL, NULL);
8406
8407
8408         /* Dump Type Comments and Security Labels */
8409         dumpComment(fout, labelq->data,
8410                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8411                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8412         dumpSecLabel(fout, labelq->data,
8413                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8414                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8415
8416         PQclear(res);
8417         destroyPQExpBuffer(q);
8418         destroyPQExpBuffer(dropped);
8419         destroyPQExpBuffer(delq);
8420         destroyPQExpBuffer(labelq);
8421         destroyPQExpBuffer(query);
8422
8423         /* Dump any per-column comments */
8424         dumpCompositeTypeColComments(fout, tyinfo);
8425 }
8426
8427 /*
8428  * dumpCompositeTypeColComments
8429  *        writes out to fout the queries to recreate comments on the columns of
8430  *        a user-defined stand-alone composite type
8431  */
8432 static void
8433 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8434 {
8435         CommentItem *comments;
8436         int                     ncomments;
8437         PGresult   *res;
8438         PQExpBuffer query;
8439         PQExpBuffer target;
8440         Oid                     pgClassOid;
8441         int                     i;
8442         int                     ntups;
8443         int                     i_attname;
8444         int                     i_attnum;
8445
8446         query = createPQExpBuffer();
8447
8448         /* We assume here that remoteVersion must be at least 70300 */
8449         appendPQExpBuffer(query,
8450                                           "SELECT c.tableoid, a.attname, a.attnum "
8451                                           "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8452                                           "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8453                                           "  AND NOT a.attisdropped "
8454                                           "ORDER BY a.attnum ",
8455                                           tyinfo->typrelid);
8456
8457         /* Fetch column attnames */
8458         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8459
8460         ntups = PQntuples(res);
8461         if (ntups < 1)
8462         {
8463                 PQclear(res);
8464                 destroyPQExpBuffer(query);
8465                 return;
8466         }
8467
8468         pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8469
8470         /* Search for comments associated with type's pg_class OID */
8471         ncomments = findComments(fout,
8472                                                          pgClassOid,
8473                                                          tyinfo->typrelid,
8474                                                          &comments);
8475
8476         /* If no comments exist, we're done */
8477         if (ncomments <= 0)
8478         {
8479                 PQclear(res);
8480                 destroyPQExpBuffer(query);
8481                 return;
8482         }
8483
8484         /* Build COMMENT ON statements */
8485         target = createPQExpBuffer();
8486
8487         i_attnum = PQfnumber(res, "attnum");
8488         i_attname = PQfnumber(res, "attname");
8489         while (ncomments > 0)
8490         {
8491                 const char *attname;
8492
8493                 attname = NULL;
8494                 for (i = 0; i < ntups; i++)
8495                 {
8496                         if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8497                         {
8498                                 attname = PQgetvalue(res, i, i_attname);
8499                                 break;
8500                         }
8501                 }
8502                 if (attname)                    /* just in case we don't find it */
8503                 {
8504                         const char *descr = comments->descr;
8505
8506                         resetPQExpBuffer(target);
8507                         appendPQExpBuffer(target, "COLUMN %s.",
8508                                                           fmtId(tyinfo->dobj.name));
8509                         appendPQExpBuffer(target, "%s",
8510                                                           fmtId(attname));
8511
8512                         resetPQExpBuffer(query);
8513                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8514                         appendStringLiteralAH(query, descr, fout);
8515                         appendPQExpBuffer(query, ";\n");
8516
8517                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
8518                                                  target->data,
8519                                                  tyinfo->dobj.namespace->dobj.name,
8520                                                  NULL, tyinfo->rolname,
8521                                                  false, "COMMENT", SECTION_NONE,
8522                                                  query->data, "", NULL,
8523                                                  &(tyinfo->dobj.dumpId), 1,
8524                                                  NULL, NULL);
8525                 }
8526
8527                 comments++;
8528                 ncomments--;
8529         }
8530
8531         PQclear(res);
8532         destroyPQExpBuffer(query);
8533         destroyPQExpBuffer(target);
8534 }
8535
8536 /*
8537  * dumpShellType
8538  *        writes out to fout the queries to create a shell type
8539  *
8540  * We dump a shell definition in advance of the I/O functions for the type.
8541  */
8542 static void
8543 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8544 {
8545         PQExpBuffer q;
8546
8547         /* Skip if not to be dumped */
8548         if (!stinfo->dobj.dump || dataOnly)
8549                 return;
8550
8551         q = createPQExpBuffer();
8552
8553         /*
8554          * Note the lack of a DROP command for the shell type; any required DROP
8555          * is driven off the base type entry, instead.  This interacts with
8556          * _printTocEntry()'s use of the presence of a DROP command to decide
8557          * whether an entry needs an ALTER OWNER command.  We don't want to alter
8558          * the shell type's owner immediately on creation; that should happen only
8559          * after it's filled in, otherwise the backend complains.
8560          */
8561
8562         if (binary_upgrade)
8563                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8564                                                                                    stinfo->baseType->dobj.catId.oid);
8565
8566         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8567                                           fmtId(stinfo->dobj.name));
8568
8569         ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8570                                  stinfo->dobj.name,
8571                                  stinfo->dobj.namespace->dobj.name,
8572                                  NULL,
8573                                  stinfo->baseType->rolname, false,
8574                                  "SHELL TYPE", SECTION_PRE_DATA,
8575                                  q->data, "", NULL,
8576                                  stinfo->dobj.dependencies, stinfo->dobj.nDeps,
8577                                  NULL, NULL);
8578
8579         destroyPQExpBuffer(q);
8580 }
8581
8582 /*
8583  * Determine whether we want to dump definitions for procedural languages.
8584  * Since the languages themselves don't have schemas, we can't rely on
8585  * the normal schema-based selection mechanism.  We choose to dump them
8586  * whenever neither --schema nor --table was given.  (Before 8.1, we used
8587  * the dump flag of the PL's call handler function, but in 8.1 this will
8588  * probably always be false since call handlers are created in pg_catalog.)
8589  *
8590  * For some backwards compatibility with the older behavior, we forcibly
8591  * dump a PL if its handler function (and validator if any) are in a
8592  * dumpable namespace.  That case is not checked here.
8593  *
8594  * Also, if the PL belongs to an extension, we do not use this heuristic.
8595  * That case isn't checked here either.
8596  */
8597 static bool
8598 shouldDumpProcLangs(void)
8599 {
8600         if (!include_everything)
8601                 return false;
8602         /* And they're schema not data */
8603         if (dataOnly)
8604                 return false;
8605         return true;
8606 }
8607
8608 /*
8609  * dumpProcLang
8610  *                writes out to fout the queries to recreate a user-defined
8611  *                procedural language
8612  */
8613 static void
8614 dumpProcLang(Archive *fout, ProcLangInfo *plang)
8615 {
8616         PQExpBuffer defqry;
8617         PQExpBuffer delqry;
8618         PQExpBuffer labelq;
8619         bool            useParams;
8620         char       *qlanname;
8621         char       *lanschema;
8622         FuncInfo   *funcInfo;
8623         FuncInfo   *inlineInfo = NULL;
8624         FuncInfo   *validatorInfo = NULL;
8625
8626         /* Skip if not to be dumped */
8627         if (!plang->dobj.dump || dataOnly)
8628                 return;
8629
8630         /*
8631          * Try to find the support function(s).  It is not an error if we don't
8632          * find them --- if the functions are in the pg_catalog schema, as is
8633          * standard in 8.1 and up, then we won't have loaded them. (In this case
8634          * we will emit a parameterless CREATE LANGUAGE command, which will
8635          * require PL template knowledge in the backend to reload.)
8636          */
8637
8638         funcInfo = findFuncByOid(plang->lanplcallfoid);
8639         if (funcInfo != NULL && !funcInfo->dobj.dump)
8640                 funcInfo = NULL;                /* treat not-dumped same as not-found */
8641
8642         if (OidIsValid(plang->laninline))
8643         {
8644                 inlineInfo = findFuncByOid(plang->laninline);
8645                 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
8646                         inlineInfo = NULL;
8647         }
8648
8649         if (OidIsValid(plang->lanvalidator))
8650         {
8651                 validatorInfo = findFuncByOid(plang->lanvalidator);
8652                 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
8653                         validatorInfo = NULL;
8654         }
8655
8656         /*
8657          * If the functions are dumpable then emit a traditional CREATE LANGUAGE
8658          * with parameters.  Otherwise, dump only if shouldDumpProcLangs() says to
8659          * dump it.
8660          *
8661          * However, for a language that belongs to an extension, we must not use
8662          * the shouldDumpProcLangs heuristic, but just dump the language iff we're
8663          * told to (via dobj.dump).  Generally the support functions will belong
8664          * to the same extension and so have the same dump flags ... if they
8665          * don't, this might not work terribly nicely.
8666          */
8667         useParams = (funcInfo != NULL &&
8668                                  (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
8669                                  (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
8670
8671         if (!plang->dobj.ext_member)
8672         {
8673                 if (!useParams && !shouldDumpProcLangs())
8674                         return;
8675         }
8676
8677         defqry = createPQExpBuffer();
8678         delqry = createPQExpBuffer();
8679         labelq = createPQExpBuffer();
8680
8681         qlanname = pg_strdup(fmtId(plang->dobj.name));
8682
8683         /*
8684          * If dumping a HANDLER clause, treat the language as being in the handler
8685          * function's schema; this avoids cluttering the HANDLER clause. Otherwise
8686          * it doesn't really have a schema.
8687          */
8688         if (useParams)
8689                 lanschema = funcInfo->dobj.namespace->dobj.name;
8690         else
8691                 lanschema = NULL;
8692
8693         appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
8694                                           qlanname);
8695
8696         if (useParams)
8697         {
8698                 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
8699                                                   plang->lanpltrusted ? "TRUSTED " : "",
8700                                                   qlanname);
8701                 appendPQExpBuffer(defqry, " HANDLER %s",
8702                                                   fmtId(funcInfo->dobj.name));
8703                 if (OidIsValid(plang->laninline))
8704                 {
8705                         appendPQExpBuffer(defqry, " INLINE ");
8706                         /* Cope with possibility that inline is in different schema */
8707                         if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
8708                                 appendPQExpBuffer(defqry, "%s.",
8709                                                            fmtId(inlineInfo->dobj.namespace->dobj.name));
8710                         appendPQExpBuffer(defqry, "%s",
8711                                                           fmtId(inlineInfo->dobj.name));
8712                 }
8713                 if (OidIsValid(plang->lanvalidator))
8714                 {
8715                         appendPQExpBuffer(defqry, " VALIDATOR ");
8716                         /* Cope with possibility that validator is in different schema */
8717                         if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
8718                                 appendPQExpBuffer(defqry, "%s.",
8719                                                         fmtId(validatorInfo->dobj.namespace->dobj.name));
8720                         appendPQExpBuffer(defqry, "%s",
8721                                                           fmtId(validatorInfo->dobj.name));
8722                 }
8723         }
8724         else
8725         {
8726                 /*
8727                  * If not dumping parameters, then use CREATE OR REPLACE so that the
8728                  * command will not fail if the language is preinstalled in the target
8729                  * database.  We restrict the use of REPLACE to this case so as to
8730                  * eliminate the risk of replacing a language with incompatible
8731                  * parameter settings: this command will only succeed at all if there
8732                  * is a pg_pltemplate entry, and if there is one, the existing entry
8733                  * must match it too.
8734                  */
8735                 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
8736                                                   qlanname);
8737         }
8738         appendPQExpBuffer(defqry, ";\n");
8739
8740         appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
8741
8742         if (binary_upgrade)
8743                 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
8744
8745         ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
8746                                  plang->dobj.name,
8747                                  lanschema, NULL, plang->lanowner,
8748                                  false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
8749                                  defqry->data, delqry->data, NULL,
8750                                  plang->dobj.dependencies, plang->dobj.nDeps,
8751                                  NULL, NULL);
8752
8753         /* Dump Proc Lang Comments and Security Labels */
8754         dumpComment(fout, labelq->data,
8755                                 NULL, "",
8756                                 plang->dobj.catId, 0, plang->dobj.dumpId);
8757         dumpSecLabel(fout, labelq->data,
8758                                  NULL, "",
8759                                  plang->dobj.catId, 0, plang->dobj.dumpId);
8760
8761         if (plang->lanpltrusted)
8762                 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
8763                                 qlanname, NULL, plang->dobj.name,
8764                                 lanschema,
8765                                 plang->lanowner, plang->lanacl);
8766
8767         free(qlanname);
8768
8769         destroyPQExpBuffer(defqry);
8770         destroyPQExpBuffer(delqry);
8771         destroyPQExpBuffer(labelq);
8772 }
8773
8774 /*
8775  * format_function_arguments: generate function name and argument list
8776  *
8777  * This is used when we can rely on pg_get_function_arguments to format
8778  * the argument list.
8779  */
8780 static char *
8781 format_function_arguments(FuncInfo *finfo, char *funcargs)
8782 {
8783         PQExpBufferData fn;
8784
8785         initPQExpBuffer(&fn);
8786         appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
8787         return fn.data;
8788 }
8789
8790 /*
8791  * format_function_arguments_old: generate function name and argument list
8792  *
8793  * The argument type names are qualified if needed.  The function name
8794  * is never qualified.
8795  *
8796  * This is used only with pre-8.4 servers, so we aren't expecting to see
8797  * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
8798  *
8799  * Any or all of allargtypes, argmodes, argnames may be NULL.
8800  */
8801 static char *
8802 format_function_arguments_old(Archive *fout,
8803                                                           FuncInfo *finfo, int nallargs,
8804                                                           char **allargtypes,
8805                                                           char **argmodes,
8806                                                           char **argnames)
8807 {
8808         PQExpBufferData fn;
8809         int                     j;
8810
8811         initPQExpBuffer(&fn);
8812         appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8813         for (j = 0; j < nallargs; j++)
8814         {
8815                 Oid                     typid;
8816                 char       *typname;
8817                 const char *argmode;
8818                 const char *argname;
8819
8820                 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
8821                 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
8822
8823                 if (argmodes)
8824                 {
8825                         switch (argmodes[j][0])
8826                         {
8827                                 case PROARGMODE_IN:
8828                                         argmode = "";
8829                                         break;
8830                                 case PROARGMODE_OUT:
8831                                         argmode = "OUT ";
8832                                         break;
8833                                 case PROARGMODE_INOUT:
8834                                         argmode = "INOUT ";
8835                                         break;
8836                                 default:
8837                                         write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
8838                                         argmode = "";
8839                                         break;
8840                         }
8841                 }
8842                 else
8843                         argmode = "";
8844
8845                 argname = argnames ? argnames[j] : (char *) NULL;
8846                 if (argname && argname[0] == '\0')
8847                         argname = NULL;
8848
8849                 appendPQExpBuffer(&fn, "%s%s%s%s%s",
8850                                                   (j > 0) ? ", " : "",
8851                                                   argmode,
8852                                                   argname ? fmtId(argname) : "",
8853                                                   argname ? " " : "",
8854                                                   typname);
8855                 free(typname);
8856         }
8857         appendPQExpBuffer(&fn, ")");
8858         return fn.data;
8859 }
8860
8861 /*
8862  * format_function_signature: generate function name and argument list
8863  *
8864  * This is like format_function_arguments_old except that only a minimal
8865  * list of input argument types is generated; this is sufficient to
8866  * reference the function, but not to define it.
8867  *
8868  * If honor_quotes is false then the function name is never quoted.
8869  * This is appropriate for use in TOC tags, but not in SQL commands.
8870  */
8871 static char *
8872 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
8873 {
8874         PQExpBufferData fn;
8875         int                     j;
8876
8877         initPQExpBuffer(&fn);
8878         if (honor_quotes)
8879                 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8880         else
8881                 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
8882         for (j = 0; j < finfo->nargs; j++)
8883         {
8884                 char       *typname;
8885
8886                 typname = getFormattedTypeName(fout, finfo->argtypes[j],
8887                                                                            zeroAsOpaque);
8888
8889                 appendPQExpBuffer(&fn, "%s%s",
8890                                                   (j > 0) ? ", " : "",
8891                                                   typname);
8892                 free(typname);
8893         }
8894         appendPQExpBuffer(&fn, ")");
8895         return fn.data;
8896 }
8897
8898
8899 /*
8900  * dumpFunc:
8901  *        dump out one function
8902  */
8903 static void
8904 dumpFunc(Archive *fout, FuncInfo *finfo)
8905 {
8906         PQExpBuffer query;
8907         PQExpBuffer q;
8908         PQExpBuffer delqry;
8909         PQExpBuffer labelq;
8910         PQExpBuffer asPart;
8911         PGresult   *res;
8912         char       *funcsig;            /* identity signature */
8913         char       *funcfullsig;        /* full signature */
8914         char       *funcsig_tag;
8915         char       *proretset;
8916         char       *prosrc;
8917         char       *probin;
8918         char       *funcargs;
8919         char       *funciargs;
8920         char       *funcresult;
8921         char       *proallargtypes;
8922         char       *proargmodes;
8923         char       *proargnames;
8924         char       *proiswindow;
8925         char       *provolatile;
8926         char       *proisstrict;
8927         char       *prosecdef;
8928         char       *proleakproof;
8929         char       *proconfig;
8930         char       *procost;
8931         char       *prorows;
8932         char       *lanname;
8933         char       *rettypename;
8934         int                     nallargs;
8935         char      **allargtypes = NULL;
8936         char      **argmodes = NULL;
8937         char      **argnames = NULL;
8938         char      **configitems = NULL;
8939         int                     nconfigitems = 0;
8940         int                     i;
8941
8942         /* Skip if not to be dumped */
8943         if (!finfo->dobj.dump || dataOnly)
8944                 return;
8945
8946         query = createPQExpBuffer();
8947         q = createPQExpBuffer();
8948         delqry = createPQExpBuffer();
8949         labelq = createPQExpBuffer();
8950         asPart = createPQExpBuffer();
8951
8952         /* Set proper schema search path so type references list correctly */
8953         selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
8954
8955         /* Fetch function-specific details */
8956         if (fout->remoteVersion >= 90200)
8957         {
8958                 /*
8959                  * proleakproof was added at v9.2
8960                  */
8961                 appendPQExpBuffer(query,
8962                                                   "SELECT proretset, prosrc, probin, "
8963                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8964                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8965                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8966                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
8967                                                   "proleakproof, proconfig, procost, prorows, "
8968                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8969                                                   "FROM pg_catalog.pg_proc "
8970                                                   "WHERE oid = '%u'::pg_catalog.oid",
8971                                                   finfo->dobj.catId.oid);
8972         }
8973         else if (fout->remoteVersion >= 80400)
8974         {
8975                 /*
8976                  * In 8.4 and up we rely on pg_get_function_arguments and
8977                  * pg_get_function_result instead of examining proallargtypes etc.
8978                  */
8979                 appendPQExpBuffer(query,
8980                                                   "SELECT proretset, prosrc, probin, "
8981                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8982                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8983                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8984                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
8985                                                   "false AS proleakproof, "
8986                                                   " proconfig, procost, prorows, "
8987                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8988                                                   "FROM pg_catalog.pg_proc "
8989                                                   "WHERE oid = '%u'::pg_catalog.oid",
8990                                                   finfo->dobj.catId.oid);
8991         }
8992         else if (fout->remoteVersion >= 80300)
8993         {
8994                 appendPQExpBuffer(query,
8995                                                   "SELECT proretset, prosrc, probin, "
8996                                                   "proallargtypes, proargmodes, proargnames, "
8997                                                   "false AS proiswindow, "
8998                                                   "provolatile, proisstrict, prosecdef, "
8999                                                   "false AS proleakproof, "
9000                                                   "proconfig, procost, prorows, "
9001                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9002                                                   "FROM pg_catalog.pg_proc "
9003                                                   "WHERE oid = '%u'::pg_catalog.oid",
9004                                                   finfo->dobj.catId.oid);
9005         }
9006         else if (fout->remoteVersion >= 80100)
9007         {
9008                 appendPQExpBuffer(query,
9009                                                   "SELECT proretset, prosrc, probin, "
9010                                                   "proallargtypes, proargmodes, proargnames, "
9011                                                   "false AS proiswindow, "
9012                                                   "provolatile, proisstrict, prosecdef, "
9013                                                   "false AS proleakproof, "
9014                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9015                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9016                                                   "FROM pg_catalog.pg_proc "
9017                                                   "WHERE oid = '%u'::pg_catalog.oid",
9018                                                   finfo->dobj.catId.oid);
9019         }
9020         else if (fout->remoteVersion >= 80000)
9021         {
9022                 appendPQExpBuffer(query,
9023                                                   "SELECT proretset, prosrc, probin, "
9024                                                   "null AS proallargtypes, "
9025                                                   "null AS proargmodes, "
9026                                                   "proargnames, "
9027                                                   "false AS proiswindow, "
9028                                                   "provolatile, proisstrict, prosecdef, "
9029                                                   "false AS proleakproof, "
9030                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9031                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9032                                                   "FROM pg_catalog.pg_proc "
9033                                                   "WHERE oid = '%u'::pg_catalog.oid",
9034                                                   finfo->dobj.catId.oid);
9035         }
9036         else if (fout->remoteVersion >= 70300)
9037         {
9038                 appendPQExpBuffer(query,
9039                                                   "SELECT proretset, prosrc, probin, "
9040                                                   "null AS proallargtypes, "
9041                                                   "null AS proargmodes, "
9042                                                   "null AS proargnames, "
9043                                                   "false AS proiswindow, "
9044                                                   "provolatile, proisstrict, prosecdef, "
9045                                                   "false AS proleakproof, "
9046                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9047                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9048                                                   "FROM pg_catalog.pg_proc "
9049                                                   "WHERE oid = '%u'::pg_catalog.oid",
9050                                                   finfo->dobj.catId.oid);
9051         }
9052         else if (fout->remoteVersion >= 70100)
9053         {
9054                 appendPQExpBuffer(query,
9055                                                   "SELECT proretset, prosrc, probin, "
9056                                                   "null AS proallargtypes, "
9057                                                   "null AS proargmodes, "
9058                                                   "null AS proargnames, "
9059                                                   "false AS proiswindow, "
9060                          "case when proiscachable then 'i' else 'v' end AS provolatile, "
9061                                                   "proisstrict, "
9062                                                   "false AS prosecdef, "
9063                                                   "false AS proleakproof, "
9064                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9065                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9066                                                   "FROM pg_proc "
9067                                                   "WHERE oid = '%u'::oid",
9068                                                   finfo->dobj.catId.oid);
9069         }
9070         else
9071         {
9072                 appendPQExpBuffer(query,
9073                                                   "SELECT proretset, prosrc, probin, "
9074                                                   "null AS proallargtypes, "
9075                                                   "null AS proargmodes, "
9076                                                   "null AS proargnames, "
9077                                                   "false AS proiswindow, "
9078                          "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9079                                                   "false AS proisstrict, "
9080                                                   "false AS prosecdef, "
9081                                                   "false AS proleakproof, "
9082                                                   "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9083                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9084                                                   "FROM pg_proc "
9085                                                   "WHERE oid = '%u'::oid",
9086                                                   finfo->dobj.catId.oid);
9087         }
9088
9089         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9090
9091         proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9092         prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9093         probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9094         if (fout->remoteVersion >= 80400)
9095         {
9096                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9097                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9098                 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9099                 proallargtypes = proargmodes = proargnames = NULL;
9100         }
9101         else
9102         {
9103                 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9104                 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9105                 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9106                 funcargs = funciargs = funcresult = NULL;
9107         }
9108         proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9109         provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9110         proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9111         prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9112         proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9113         proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9114         procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9115         prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9116         lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9117
9118         /*
9119          * See backend/commands/functioncmds.c for details of how the 'AS' clause
9120          * is used.  In 8.4 and up, an unused probin is NULL (here ""); previous
9121          * versions would set it to "-".  There are no known cases in which prosrc
9122          * is unused, so the tests below for "-" are probably useless.
9123          */
9124         if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9125         {
9126                 appendPQExpBuffer(asPart, "AS ");
9127                 appendStringLiteralAH(asPart, probin, fout);
9128                 if (strcmp(prosrc, "-") != 0)
9129                 {
9130                         appendPQExpBuffer(asPart, ", ");
9131
9132                         /*
9133                          * where we have bin, use dollar quoting if allowed and src
9134                          * contains quote or backslash; else use regular quoting.
9135                          */
9136                         if (disable_dollar_quoting ||
9137                           (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9138                                 appendStringLiteralAH(asPart, prosrc, fout);
9139                         else
9140                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9141                 }
9142         }
9143         else
9144         {
9145                 if (strcmp(prosrc, "-") != 0)
9146                 {
9147                         appendPQExpBuffer(asPart, "AS ");
9148                         /* with no bin, dollar quote src unconditionally if allowed */
9149                         if (disable_dollar_quoting)
9150                                 appendStringLiteralAH(asPart, prosrc, fout);
9151                         else
9152                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9153                 }
9154         }
9155
9156         nallargs = finfo->nargs;        /* unless we learn different from allargs */
9157
9158         if (proallargtypes && *proallargtypes)
9159         {
9160                 int                     nitems = 0;
9161
9162                 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9163                         nitems < finfo->nargs)
9164                 {
9165                         write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9166                         if (allargtypes)
9167                                 free(allargtypes);
9168                         allargtypes = NULL;
9169                 }
9170                 else
9171                         nallargs = nitems;
9172         }
9173
9174         if (proargmodes && *proargmodes)
9175         {
9176                 int                     nitems = 0;
9177
9178                 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9179                         nitems != nallargs)
9180                 {
9181                         write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9182                         if (argmodes)
9183                                 free(argmodes);
9184                         argmodes = NULL;
9185                 }
9186         }
9187
9188         if (proargnames && *proargnames)
9189         {
9190                 int                     nitems = 0;
9191
9192                 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9193                         nitems != nallargs)
9194                 {
9195                         write_msg(NULL, "WARNING: could not parse proargnames array\n");
9196                         if (argnames)
9197                                 free(argnames);
9198                         argnames = NULL;
9199                 }
9200         }
9201
9202         if (proconfig && *proconfig)
9203         {
9204                 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9205                 {
9206                         write_msg(NULL, "WARNING: could not parse proconfig array\n");
9207                         if (configitems)
9208                                 free(configitems);
9209                         configitems = NULL;
9210                         nconfigitems = 0;
9211                 }
9212         }
9213
9214         if (funcargs)
9215         {
9216                 /* 8.4 or later; we rely on server-side code for most of the work */
9217                 funcfullsig = format_function_arguments(finfo, funcargs);
9218                 funcsig = format_function_arguments(finfo, funciargs);
9219         }
9220         else
9221         {
9222                 /* pre-8.4, do it ourselves */
9223                 funcsig = format_function_arguments_old(fout,
9224                                                                                                 finfo, nallargs, allargtypes,
9225                                                                                                 argmodes, argnames);
9226                 funcfullsig = funcsig;
9227         }
9228
9229         funcsig_tag = format_function_signature(fout, finfo, false);
9230
9231         /*
9232          * DROP must be fully qualified in case same name appears in pg_catalog
9233          */
9234         appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9235                                           fmtId(finfo->dobj.namespace->dobj.name),
9236                                           funcsig);
9237
9238         appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9239         if (funcresult)
9240                 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9241         else
9242         {
9243                 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9244                                                                                    zeroAsOpaque);
9245                 appendPQExpBuffer(q, "RETURNS %s%s",
9246                                                   (proretset[0] == 't') ? "SETOF " : "",
9247                                                   rettypename);
9248                 free(rettypename);
9249         }
9250
9251         appendPQExpBuffer(q, "\n    LANGUAGE %s", fmtId(lanname));
9252
9253         if (proiswindow[0] == 't')
9254                 appendPQExpBuffer(q, " WINDOW");
9255
9256         if (provolatile[0] != PROVOLATILE_VOLATILE)
9257         {
9258                 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9259                         appendPQExpBuffer(q, " IMMUTABLE");
9260                 else if (provolatile[0] == PROVOLATILE_STABLE)
9261                         appendPQExpBuffer(q, " STABLE");
9262                 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9263                         exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9264                                                   finfo->dobj.name);
9265         }
9266
9267         if (proisstrict[0] == 't')
9268                 appendPQExpBuffer(q, " STRICT");
9269
9270         if (prosecdef[0] == 't')
9271                 appendPQExpBuffer(q, " SECURITY DEFINER");
9272
9273         if (proleakproof[0] == 't')
9274                 appendPQExpBuffer(q, " LEAKPROOF");
9275
9276         /*
9277          * COST and ROWS are emitted only if present and not default, so as not to
9278          * break backwards-compatibility of the dump without need.      Keep this code
9279          * in sync with the defaults in functioncmds.c.
9280          */
9281         if (strcmp(procost, "0") != 0)
9282         {
9283                 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9284                 {
9285                         /* default cost is 1 */
9286                         if (strcmp(procost, "1") != 0)
9287                                 appendPQExpBuffer(q, " COST %s", procost);
9288                 }
9289                 else
9290                 {
9291                         /* default cost is 100 */
9292                         if (strcmp(procost, "100") != 0)
9293                                 appendPQExpBuffer(q, " COST %s", procost);
9294                 }
9295         }
9296         if (proretset[0] == 't' &&
9297                 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9298                 appendPQExpBuffer(q, " ROWS %s", prorows);
9299
9300         for (i = 0; i < nconfigitems; i++)
9301         {
9302                 /* we feel free to scribble on configitems[] here */
9303                 char       *configitem = configitems[i];
9304                 char       *pos;
9305
9306                 pos = strchr(configitem, '=');
9307                 if (pos == NULL)
9308                         continue;
9309                 *pos++ = '\0';
9310                 appendPQExpBuffer(q, "\n    SET %s TO ", fmtId(configitem));
9311
9312                 /*
9313                  * Some GUC variable names are 'LIST' type and hence must not be
9314                  * quoted.
9315                  */
9316                 if (pg_strcasecmp(configitem, "DateStyle") == 0
9317                         || pg_strcasecmp(configitem, "search_path") == 0)
9318                         appendPQExpBuffer(q, "%s", pos);
9319                 else
9320                         appendStringLiteralAH(q, pos, fout);
9321         }
9322
9323         appendPQExpBuffer(q, "\n    %s;\n", asPart->data);
9324
9325         appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9326
9327         if (binary_upgrade)
9328                 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9329
9330         ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9331                                  funcsig_tag,
9332                                  finfo->dobj.namespace->dobj.name,
9333                                  NULL,
9334                                  finfo->rolname, false,
9335                                  "FUNCTION", SECTION_PRE_DATA,
9336                                  q->data, delqry->data, NULL,
9337                                  finfo->dobj.dependencies, finfo->dobj.nDeps,
9338                                  NULL, NULL);
9339
9340         /* Dump Function Comments and Security Labels */
9341         dumpComment(fout, labelq->data,
9342                                 finfo->dobj.namespace->dobj.name, finfo->rolname,
9343                                 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9344         dumpSecLabel(fout, labelq->data,
9345                                  finfo->dobj.namespace->dobj.name, finfo->rolname,
9346                                  finfo->dobj.catId, 0, finfo->dobj.dumpId);
9347
9348         dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9349                         funcsig, NULL, funcsig_tag,
9350                         finfo->dobj.namespace->dobj.name,
9351                         finfo->rolname, finfo->proacl);
9352
9353         PQclear(res);
9354
9355         destroyPQExpBuffer(query);
9356         destroyPQExpBuffer(q);
9357         destroyPQExpBuffer(delqry);
9358         destroyPQExpBuffer(labelq);
9359         destroyPQExpBuffer(asPart);
9360         free(funcsig);
9361         free(funcsig_tag);
9362         if (allargtypes)
9363                 free(allargtypes);
9364         if (argmodes)
9365                 free(argmodes);
9366         if (argnames)
9367                 free(argnames);
9368         if (configitems)
9369                 free(configitems);
9370 }
9371
9372
9373 /*
9374  * Dump a user-defined cast
9375  */
9376 static void
9377 dumpCast(Archive *fout, CastInfo *cast)
9378 {
9379         PQExpBuffer defqry;
9380         PQExpBuffer delqry;
9381         PQExpBuffer labelq;
9382         FuncInfo   *funcInfo = NULL;
9383
9384         /* Skip if not to be dumped */
9385         if (!cast->dobj.dump || dataOnly)
9386                 return;
9387
9388         /* Cannot dump if we don't have the cast function's info */
9389         if (OidIsValid(cast->castfunc))
9390         {
9391                 funcInfo = findFuncByOid(cast->castfunc);
9392                 if (funcInfo == NULL)
9393                         return;
9394         }
9395
9396         /*
9397          * As per discussion we dump casts if one or more of the underlying
9398          * objects (the conversion function and the two data types) are not
9399          * builtin AND if all of the non-builtin objects are included in the dump.
9400          * Builtin meaning, the namespace name does not start with "pg_".
9401          *
9402          * However, for a cast that belongs to an extension, we must not use this
9403          * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9404          */
9405         if (!cast->dobj.ext_member)
9406         {
9407                 TypeInfo   *sourceInfo = findTypeByOid(cast->castsource);
9408                 TypeInfo   *targetInfo = findTypeByOid(cast->casttarget);
9409
9410                 if (sourceInfo == NULL || targetInfo == NULL)
9411                         return;
9412
9413                 /*
9414                  * Skip this cast if all objects are from pg_
9415                  */
9416                 if ((funcInfo == NULL ||
9417                          strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9418                         strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9419                         strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9420                         return;
9421
9422                 /*
9423                  * Skip cast if function isn't from pg_ and is not to be dumped.
9424                  */
9425                 if (funcInfo &&
9426                         strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9427                         !funcInfo->dobj.dump)
9428                         return;
9429
9430                 /*
9431                  * Same for the source type
9432                  */
9433                 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9434                         !sourceInfo->dobj.dump)
9435                         return;
9436
9437                 /*
9438                  * and the target type.
9439                  */
9440                 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9441                         !targetInfo->dobj.dump)
9442                         return;
9443         }
9444
9445         /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9446         selectSourceSchema(fout, "pg_catalog");
9447
9448         defqry = createPQExpBuffer();
9449         delqry = createPQExpBuffer();
9450         labelq = createPQExpBuffer();
9451
9452         appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9453                                   getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9454                                   getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9455
9456         appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9457                                   getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9458                                   getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9459
9460         switch (cast->castmethod)
9461         {
9462                 case COERCION_METHOD_BINARY:
9463                         appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9464                         break;
9465                 case COERCION_METHOD_INOUT:
9466                         appendPQExpBuffer(defqry, "WITH INOUT");
9467                         break;
9468                 case COERCION_METHOD_FUNCTION:
9469                         if (funcInfo)
9470                         {
9471                                 char   *fsig = format_function_signature(fout, funcInfo, true);
9472
9473                                 /*
9474                                  * Always qualify the function name, in case it is not in
9475                                  * pg_catalog schema (format_function_signature won't qualify it).
9476                                  */
9477                                 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
9478                                                                   fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
9479                                 free(fsig);
9480                         }
9481                         else
9482                                 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
9483                         break;
9484                 default:
9485                         write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9486         }
9487
9488         if (cast->castcontext == 'a')
9489                 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9490         else if (cast->castcontext == 'i')
9491                 appendPQExpBuffer(defqry, " AS IMPLICIT");
9492         appendPQExpBuffer(defqry, ";\n");
9493
9494         appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9495                                   getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9496                                   getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9497
9498         if (binary_upgrade)
9499                 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9500
9501         ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9502                                  labelq->data,
9503                                  "pg_catalog", NULL, "",
9504                                  false, "CAST", SECTION_PRE_DATA,
9505                                  defqry->data, delqry->data, NULL,
9506                                  cast->dobj.dependencies, cast->dobj.nDeps,
9507                                  NULL, NULL);
9508
9509         /* Dump Cast Comments */
9510         dumpComment(fout, labelq->data,
9511                                 NULL, "",
9512                                 cast->dobj.catId, 0, cast->dobj.dumpId);
9513
9514         destroyPQExpBuffer(defqry);
9515         destroyPQExpBuffer(delqry);
9516         destroyPQExpBuffer(labelq);
9517 }
9518
9519 /*
9520  * dumpOpr
9521  *        write out a single operator definition
9522  */
9523 static void
9524 dumpOpr(Archive *fout, OprInfo *oprinfo)
9525 {
9526         PQExpBuffer query;
9527         PQExpBuffer q;
9528         PQExpBuffer delq;
9529         PQExpBuffer labelq;
9530         PQExpBuffer oprid;
9531         PQExpBuffer details;
9532         const char *name;
9533         PGresult   *res;
9534         int                     i_oprkind;
9535         int                     i_oprcode;
9536         int                     i_oprleft;
9537         int                     i_oprright;
9538         int                     i_oprcom;
9539         int                     i_oprnegate;
9540         int                     i_oprrest;
9541         int                     i_oprjoin;
9542         int                     i_oprcanmerge;
9543         int                     i_oprcanhash;
9544         char       *oprkind;
9545         char       *oprcode;
9546         char       *oprleft;
9547         char       *oprright;
9548         char       *oprcom;
9549         char       *oprnegate;
9550         char       *oprrest;
9551         char       *oprjoin;
9552         char       *oprcanmerge;
9553         char       *oprcanhash;
9554
9555         /* Skip if not to be dumped */
9556         if (!oprinfo->dobj.dump || dataOnly)
9557                 return;
9558
9559         /*
9560          * some operators are invalid because they were the result of user
9561          * defining operators before commutators exist
9562          */
9563         if (!OidIsValid(oprinfo->oprcode))
9564                 return;
9565
9566         query = createPQExpBuffer();
9567         q = createPQExpBuffer();
9568         delq = createPQExpBuffer();
9569         labelq = createPQExpBuffer();
9570         oprid = createPQExpBuffer();
9571         details = createPQExpBuffer();
9572
9573         /* Make sure we are in proper schema so regoperator works correctly */
9574         selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
9575
9576         if (fout->remoteVersion >= 80300)
9577         {
9578                 appendPQExpBuffer(query, "SELECT oprkind, "
9579                                                   "oprcode::pg_catalog.regprocedure, "
9580                                                   "oprleft::pg_catalog.regtype, "
9581                                                   "oprright::pg_catalog.regtype, "
9582                                                   "oprcom::pg_catalog.regoperator, "
9583                                                   "oprnegate::pg_catalog.regoperator, "
9584                                                   "oprrest::pg_catalog.regprocedure, "
9585                                                   "oprjoin::pg_catalog.regprocedure, "
9586                                                   "oprcanmerge, oprcanhash "
9587                                                   "FROM pg_catalog.pg_operator "
9588                                                   "WHERE oid = '%u'::pg_catalog.oid",
9589                                                   oprinfo->dobj.catId.oid);
9590         }
9591         else if (fout->remoteVersion >= 70300)
9592         {
9593                 appendPQExpBuffer(query, "SELECT oprkind, "
9594                                                   "oprcode::pg_catalog.regprocedure, "
9595                                                   "oprleft::pg_catalog.regtype, "
9596                                                   "oprright::pg_catalog.regtype, "
9597                                                   "oprcom::pg_catalog.regoperator, "
9598                                                   "oprnegate::pg_catalog.regoperator, "
9599                                                   "oprrest::pg_catalog.regprocedure, "
9600                                                   "oprjoin::pg_catalog.regprocedure, "
9601                                                   "(oprlsortop != 0) AS oprcanmerge, "
9602                                                   "oprcanhash "
9603                                                   "FROM pg_catalog.pg_operator "
9604                                                   "WHERE oid = '%u'::pg_catalog.oid",
9605                                                   oprinfo->dobj.catId.oid);
9606         }
9607         else if (fout->remoteVersion >= 70100)
9608         {
9609                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9610                                                   "CASE WHEN oprleft = 0 THEN '-' "
9611                                                   "ELSE format_type(oprleft, NULL) END AS oprleft, "
9612                                                   "CASE WHEN oprright = 0 THEN '-' "
9613                                                   "ELSE format_type(oprright, NULL) END AS oprright, "
9614                                                   "oprcom, oprnegate, oprrest, oprjoin, "
9615                                                   "(oprlsortop != 0) AS oprcanmerge, "
9616                                                   "oprcanhash "
9617                                                   "FROM pg_operator "
9618                                                   "WHERE oid = '%u'::oid",
9619                                                   oprinfo->dobj.catId.oid);
9620         }
9621         else
9622         {
9623                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9624                                                   "CASE WHEN oprleft = 0 THEN '-'::name "
9625                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
9626                                                   "CASE WHEN oprright = 0 THEN '-'::name "
9627                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
9628                                                   "oprcom, oprnegate, oprrest, oprjoin, "
9629                                                   "(oprlsortop != 0) AS oprcanmerge, "
9630                                                   "oprcanhash "
9631                                                   "FROM pg_operator "
9632                                                   "WHERE oid = '%u'::oid",
9633                                                   oprinfo->dobj.catId.oid);
9634         }
9635
9636         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9637
9638         i_oprkind = PQfnumber(res, "oprkind");
9639         i_oprcode = PQfnumber(res, "oprcode");
9640         i_oprleft = PQfnumber(res, "oprleft");
9641         i_oprright = PQfnumber(res, "oprright");
9642         i_oprcom = PQfnumber(res, "oprcom");
9643         i_oprnegate = PQfnumber(res, "oprnegate");
9644         i_oprrest = PQfnumber(res, "oprrest");
9645         i_oprjoin = PQfnumber(res, "oprjoin");
9646         i_oprcanmerge = PQfnumber(res, "oprcanmerge");
9647         i_oprcanhash = PQfnumber(res, "oprcanhash");
9648
9649         oprkind = PQgetvalue(res, 0, i_oprkind);
9650         oprcode = PQgetvalue(res, 0, i_oprcode);
9651         oprleft = PQgetvalue(res, 0, i_oprleft);
9652         oprright = PQgetvalue(res, 0, i_oprright);
9653         oprcom = PQgetvalue(res, 0, i_oprcom);
9654         oprnegate = PQgetvalue(res, 0, i_oprnegate);
9655         oprrest = PQgetvalue(res, 0, i_oprrest);
9656         oprjoin = PQgetvalue(res, 0, i_oprjoin);
9657         oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
9658         oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
9659
9660         appendPQExpBuffer(details, "    PROCEDURE = %s",
9661                                           convertRegProcReference(fout, oprcode));
9662
9663         appendPQExpBuffer(oprid, "%s (",
9664                                           oprinfo->dobj.name);
9665
9666         /*
9667          * right unary means there's a left arg and left unary means there's a
9668          * right arg
9669          */
9670         if (strcmp(oprkind, "r") == 0 ||
9671                 strcmp(oprkind, "b") == 0)
9672         {
9673                 if (fout->remoteVersion >= 70100)
9674                         name = oprleft;
9675                 else
9676                         name = fmtId(oprleft);
9677                 appendPQExpBuffer(details, ",\n    LEFTARG = %s", name);
9678                 appendPQExpBuffer(oprid, "%s", name);
9679         }
9680         else
9681                 appendPQExpBuffer(oprid, "NONE");
9682
9683         if (strcmp(oprkind, "l") == 0 ||
9684                 strcmp(oprkind, "b") == 0)
9685         {
9686                 if (fout->remoteVersion >= 70100)
9687                         name = oprright;
9688                 else
9689                         name = fmtId(oprright);
9690                 appendPQExpBuffer(details, ",\n    RIGHTARG = %s", name);
9691                 appendPQExpBuffer(oprid, ", %s)", name);
9692         }
9693         else
9694                 appendPQExpBuffer(oprid, ", NONE)");
9695
9696         name = convertOperatorReference(fout, oprcom);
9697         if (name)
9698                 appendPQExpBuffer(details, ",\n    COMMUTATOR = %s", name);
9699
9700         name = convertOperatorReference(fout, oprnegate);
9701         if (name)
9702                 appendPQExpBuffer(details, ",\n    NEGATOR = %s", name);
9703
9704         if (strcmp(oprcanmerge, "t") == 0)
9705                 appendPQExpBuffer(details, ",\n    MERGES");
9706
9707         if (strcmp(oprcanhash, "t") == 0)
9708                 appendPQExpBuffer(details, ",\n    HASHES");
9709
9710         name = convertRegProcReference(fout, oprrest);
9711         if (name)
9712                 appendPQExpBuffer(details, ",\n    RESTRICT = %s", name);
9713
9714         name = convertRegProcReference(fout, oprjoin);
9715         if (name)
9716                 appendPQExpBuffer(details, ",\n    JOIN = %s", name);
9717
9718         /*
9719          * DROP must be fully qualified in case same name appears in pg_catalog
9720          */
9721         appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
9722                                           fmtId(oprinfo->dobj.namespace->dobj.name),
9723                                           oprid->data);
9724
9725         appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
9726                                           oprinfo->dobj.name, details->data);
9727
9728         appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
9729
9730         if (binary_upgrade)
9731                 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
9732
9733         ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
9734                                  oprinfo->dobj.name,
9735                                  oprinfo->dobj.namespace->dobj.name,
9736                                  NULL,
9737                                  oprinfo->rolname,
9738                                  false, "OPERATOR", SECTION_PRE_DATA,
9739                                  q->data, delq->data, NULL,
9740                                  oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
9741                                  NULL, NULL);
9742
9743         /* Dump Operator Comments */
9744         dumpComment(fout, labelq->data,
9745                                 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
9746                                 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
9747
9748         PQclear(res);
9749
9750         destroyPQExpBuffer(query);
9751         destroyPQExpBuffer(q);
9752         destroyPQExpBuffer(delq);
9753         destroyPQExpBuffer(labelq);
9754         destroyPQExpBuffer(oprid);
9755         destroyPQExpBuffer(details);
9756 }
9757
9758 /*
9759  * Convert a function reference obtained from pg_operator
9760  *
9761  * Returns what to print, or NULL if function references is InvalidOid
9762  *
9763  * In 7.3 the input is a REGPROCEDURE display; we have to strip the
9764  * argument-types part.  In prior versions, the input is a REGPROC display.
9765  */
9766 static const char *
9767 convertRegProcReference(Archive *fout, const char *proc)
9768 {
9769         /* In all cases "-" means a null reference */
9770         if (strcmp(proc, "-") == 0)
9771                 return NULL;
9772
9773         if (fout->remoteVersion >= 70300)
9774         {
9775                 char       *name;
9776                 char       *paren;
9777                 bool            inquote;
9778
9779                 name = pg_strdup(proc);
9780                 /* find non-double-quoted left paren */
9781                 inquote = false;
9782                 for (paren = name; *paren; paren++)
9783                 {
9784                         if (*paren == '(' && !inquote)
9785                         {
9786                                 *paren = '\0';
9787                                 break;
9788                         }
9789                         if (*paren == '"')
9790                                 inquote = !inquote;
9791                 }
9792                 return name;
9793         }
9794
9795         /* REGPROC before 7.3 does not quote its result */
9796         return fmtId(proc);
9797 }
9798
9799 /*
9800  * Convert an operator cross-reference obtained from pg_operator
9801  *
9802  * Returns what to print, or NULL to print nothing
9803  *
9804  * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
9805  * argument-types part, and add OPERATOR() decoration if the name is
9806  * schema-qualified.  In older versions, the input is just a numeric OID,
9807  * which we search our operator list for.
9808  */
9809 static const char *
9810 convertOperatorReference(Archive *fout, const char *opr)
9811 {
9812         OprInfo    *oprInfo;
9813
9814         /* In all cases "0" means a null reference */
9815         if (strcmp(opr, "0") == 0)
9816                 return NULL;
9817
9818         if (fout->remoteVersion >= 70300)
9819         {
9820                 char       *name;
9821                 char       *oname;
9822                 char       *ptr;
9823                 bool            inquote;
9824                 bool            sawdot;
9825
9826                 name = pg_strdup(opr);
9827                 /* find non-double-quoted left paren, and check for non-quoted dot */
9828                 inquote = false;
9829                 sawdot = false;
9830                 for (ptr = name; *ptr; ptr++)
9831                 {
9832                         if (*ptr == '"')
9833                                 inquote = !inquote;
9834                         else if (*ptr == '.' && !inquote)
9835                                 sawdot = true;
9836                         else if (*ptr == '(' && !inquote)
9837                         {
9838                                 *ptr = '\0';
9839                                 break;
9840                         }
9841                 }
9842                 /* If not schema-qualified, don't need to add OPERATOR() */
9843                 if (!sawdot)
9844                         return name;
9845                 oname = pg_malloc(strlen(name) + 11);
9846                 sprintf(oname, "OPERATOR(%s)", name);
9847                 free(name);
9848                 return oname;
9849         }
9850
9851         oprInfo = findOprByOid(atooid(opr));
9852         if (oprInfo == NULL)
9853         {
9854                 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
9855                                   opr);
9856                 return NULL;
9857         }
9858         return oprInfo->dobj.name;
9859 }
9860
9861 /*
9862  * Convert a function OID obtained from pg_ts_parser or pg_ts_template
9863  *
9864  * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
9865  * argument lists of these functions are predetermined.  Note that the
9866  * caller should ensure we are in the proper schema, because the results
9867  * are search path dependent!
9868  */
9869 static const char *
9870 convertTSFunction(Archive *fout, Oid funcOid)
9871 {
9872         char       *result;
9873         char            query[128];
9874         PGresult   *res;
9875
9876         snprintf(query, sizeof(query),
9877                          "SELECT '%u'::pg_catalog.regproc", funcOid);
9878         res = ExecuteSqlQueryForSingleRow(fout, query);
9879
9880         result = pg_strdup(PQgetvalue(res, 0, 0));
9881
9882         PQclear(res);
9883
9884         return result;
9885 }
9886
9887
9888 /*
9889  * dumpOpclass
9890  *        write out a single operator class definition
9891  */
9892 static void
9893 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
9894 {
9895         PQExpBuffer query;
9896         PQExpBuffer q;
9897         PQExpBuffer delq;
9898         PQExpBuffer labelq;
9899         PGresult   *res;
9900         int                     ntups;
9901         int                     i_opcintype;
9902         int                     i_opckeytype;
9903         int                     i_opcdefault;
9904         int                     i_opcfamily;
9905         int                     i_opcfamilyname;
9906         int                     i_opcfamilynsp;
9907         int                     i_amname;
9908         int                     i_amopstrategy;
9909         int                     i_amopreqcheck;
9910         int                     i_amopopr;
9911         int                     i_sortfamily;
9912         int                     i_sortfamilynsp;
9913         int                     i_amprocnum;
9914         int                     i_amproc;
9915         int                     i_amproclefttype;
9916         int                     i_amprocrighttype;
9917         char       *opcintype;
9918         char       *opckeytype;
9919         char       *opcdefault;
9920         char       *opcfamily;
9921         char       *opcfamilyname;
9922         char       *opcfamilynsp;
9923         char       *amname;
9924         char       *amopstrategy;
9925         char       *amopreqcheck;
9926         char       *amopopr;
9927         char       *sortfamily;
9928         char       *sortfamilynsp;
9929         char       *amprocnum;
9930         char       *amproc;
9931         char       *amproclefttype;
9932         char       *amprocrighttype;
9933         bool            needComma;
9934         int                     i;
9935
9936         /* Skip if not to be dumped */
9937         if (!opcinfo->dobj.dump || dataOnly)
9938                 return;
9939
9940         /*
9941          * XXX currently we do not implement dumping of operator classes from
9942          * pre-7.3 databases.  This could be done but it seems not worth the
9943          * trouble.
9944          */
9945         if (fout->remoteVersion < 70300)
9946                 return;
9947
9948         query = createPQExpBuffer();
9949         q = createPQExpBuffer();
9950         delq = createPQExpBuffer();
9951         labelq = createPQExpBuffer();
9952
9953         /* Make sure we are in proper schema so regoperator works correctly */
9954         selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
9955
9956         /* Get additional fields from the pg_opclass row */
9957         if (fout->remoteVersion >= 80300)
9958         {
9959                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9960                                                   "opckeytype::pg_catalog.regtype, "
9961                                                   "opcdefault, opcfamily, "
9962                                                   "opfname AS opcfamilyname, "
9963                                                   "nspname AS opcfamilynsp, "
9964                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
9965                                                   "FROM pg_catalog.pg_opclass c "
9966                                    "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
9967                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
9968                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
9969                                                   opcinfo->dobj.catId.oid);
9970         }
9971         else
9972         {
9973                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9974                                                   "opckeytype::pg_catalog.regtype, "
9975                                                   "opcdefault, NULL AS opcfamily, "
9976                                                   "NULL AS opcfamilyname, "
9977                                                   "NULL AS opcfamilynsp, "
9978                 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
9979                                                   "FROM pg_catalog.pg_opclass "
9980                                                   "WHERE oid = '%u'::pg_catalog.oid",
9981                                                   opcinfo->dobj.catId.oid);
9982         }
9983
9984         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9985
9986         i_opcintype = PQfnumber(res, "opcintype");
9987         i_opckeytype = PQfnumber(res, "opckeytype");
9988         i_opcdefault = PQfnumber(res, "opcdefault");
9989         i_opcfamily = PQfnumber(res, "opcfamily");
9990         i_opcfamilyname = PQfnumber(res, "opcfamilyname");
9991         i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
9992         i_amname = PQfnumber(res, "amname");
9993
9994         opcintype = PQgetvalue(res, 0, i_opcintype);
9995         opckeytype = PQgetvalue(res, 0, i_opckeytype);
9996         opcdefault = PQgetvalue(res, 0, i_opcdefault);
9997         /* opcfamily will still be needed after we PQclear res */
9998         opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
9999         opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
10000         opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10001         /* amname will still be needed after we PQclear res */
10002         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10003
10004         /*
10005          * DROP must be fully qualified in case same name appears in pg_catalog
10006          */
10007         appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10008                                           fmtId(opcinfo->dobj.namespace->dobj.name));
10009         appendPQExpBuffer(delq, ".%s",
10010                                           fmtId(opcinfo->dobj.name));
10011         appendPQExpBuffer(delq, " USING %s;\n",
10012                                           fmtId(amname));
10013
10014         /* Build the fixed portion of the CREATE command */
10015         appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n    ",
10016                                           fmtId(opcinfo->dobj.name));
10017         if (strcmp(opcdefault, "t") == 0)
10018                 appendPQExpBuffer(q, "DEFAULT ");
10019         appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10020                                           opcintype,
10021                                           fmtId(amname));
10022         if (strlen(opcfamilyname) > 0 &&
10023                 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10024                  strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10025         {
10026                 appendPQExpBuffer(q, " FAMILY ");
10027                 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10028                         appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10029                 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10030         }
10031         appendPQExpBuffer(q, " AS\n    ");
10032
10033         needComma = false;
10034
10035         if (strcmp(opckeytype, "-") != 0)
10036         {
10037                 appendPQExpBuffer(q, "STORAGE %s",
10038                                                   opckeytype);
10039                 needComma = true;
10040         }
10041
10042         PQclear(res);
10043
10044         /*
10045          * Now fetch and print the OPERATOR entries (pg_amop rows).
10046          *
10047          * Print only those opfamily members that are tied to the opclass by
10048          * pg_depend entries.
10049          *
10050          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10051          * older server's opclass in which it is used.  This is to avoid
10052          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10053          * older server and then reload into that old version.  This can go away
10054          * once 8.3 is so old as to not be of interest to anyone.
10055          */
10056         resetPQExpBuffer(query);
10057
10058         if (fout->remoteVersion >= 90100)
10059         {
10060                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10061                                                   "amopopr::pg_catalog.regoperator, "
10062                                                   "opfname AS sortfamily, "
10063                                                   "nspname AS sortfamilynsp "
10064                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10065                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10066                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10067                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10068                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10069                                                   "AND refobjid = '%u'::pg_catalog.oid "
10070                                                   "AND amopfamily = '%s'::pg_catalog.oid "
10071                                                   "ORDER BY amopstrategy",
10072                                                   opcinfo->dobj.catId.oid,
10073                                                   opcfamily);
10074         }
10075         else if (fout->remoteVersion >= 80400)
10076         {
10077                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10078                                                   "amopopr::pg_catalog.regoperator, "
10079                                                   "NULL AS sortfamily, "
10080                                                   "NULL AS sortfamilynsp "
10081                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10082                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10083                                                   "AND refobjid = '%u'::pg_catalog.oid "
10084                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10085                                                   "AND objid = ao.oid "
10086                                                   "ORDER BY amopstrategy",
10087                                                   opcinfo->dobj.catId.oid);
10088         }
10089         else if (fout->remoteVersion >= 80300)
10090         {
10091                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10092                                                   "amopopr::pg_catalog.regoperator, "
10093                                                   "NULL AS sortfamily, "
10094                                                   "NULL AS sortfamilynsp "
10095                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10096                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10097                                                   "AND refobjid = '%u'::pg_catalog.oid "
10098                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10099                                                   "AND objid = ao.oid "
10100                                                   "ORDER BY amopstrategy",
10101                                                   opcinfo->dobj.catId.oid);
10102         }
10103         else
10104         {
10105                 /*
10106                  * Here, we print all entries since there are no opfamilies and hence
10107                  * no loose operators to worry about.
10108                  */
10109                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10110                                                   "amopopr::pg_catalog.regoperator, "
10111                                                   "NULL AS sortfamily, "
10112                                                   "NULL AS sortfamilynsp "
10113                                                   "FROM pg_catalog.pg_amop "
10114                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10115                                                   "ORDER BY amopstrategy",
10116                                                   opcinfo->dobj.catId.oid);
10117         }
10118
10119         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10120
10121         ntups = PQntuples(res);
10122
10123         i_amopstrategy = PQfnumber(res, "amopstrategy");
10124         i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10125         i_amopopr = PQfnumber(res, "amopopr");
10126         i_sortfamily = PQfnumber(res, "sortfamily");
10127         i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10128
10129         for (i = 0; i < ntups; i++)
10130         {
10131                 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10132                 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10133                 amopopr = PQgetvalue(res, i, i_amopopr);
10134                 sortfamily = PQgetvalue(res, i, i_sortfamily);
10135                 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10136
10137                 if (needComma)
10138                         appendPQExpBuffer(q, " ,\n    ");
10139
10140                 appendPQExpBuffer(q, "OPERATOR %s %s",
10141                                                   amopstrategy, amopopr);
10142
10143                 if (strlen(sortfamily) > 0)
10144                 {
10145                         appendPQExpBuffer(q, " FOR ORDER BY ");
10146                         if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10147                                 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10148                         appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10149                 }
10150
10151                 if (strcmp(amopreqcheck, "t") == 0)
10152                         appendPQExpBuffer(q, " RECHECK");
10153
10154                 needComma = true;
10155         }
10156
10157         PQclear(res);
10158
10159         /*
10160          * Now fetch and print the FUNCTION entries (pg_amproc rows).
10161          *
10162          * Print only those opfamily members that are tied to the opclass by
10163          * pg_depend entries.
10164          *
10165          * We print the amproclefttype/amprocrighttype even though in most cases
10166          * the backend could deduce the right values, because of the corner case
10167          * of a btree sort support function for a cross-type comparison.  That's
10168          * only allowed in 9.2 and later, but for simplicity print them in all
10169          * versions that have the columns.
10170          */
10171         resetPQExpBuffer(query);
10172
10173         if (fout->remoteVersion >= 80300)
10174         {
10175                 appendPQExpBuffer(query, "SELECT amprocnum, "
10176                                                   "amproc::pg_catalog.regprocedure, "
10177                                                   "amproclefttype::pg_catalog.regtype, "
10178                                                   "amprocrighttype::pg_catalog.regtype "
10179                                                 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10180                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10181                                                   "AND refobjid = '%u'::pg_catalog.oid "
10182                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10183                                                   "AND objid = ap.oid "
10184                                                   "ORDER BY amprocnum",
10185                                                   opcinfo->dobj.catId.oid);
10186         }
10187         else
10188         {
10189                 appendPQExpBuffer(query, "SELECT amprocnum, "
10190                                                   "amproc::pg_catalog.regprocedure, "
10191                                                   "'' AS amproclefttype, "
10192                                                   "'' AS amprocrighttype "
10193                                                   "FROM pg_catalog.pg_amproc "
10194                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10195                                                   "ORDER BY amprocnum",
10196                                                   opcinfo->dobj.catId.oid);
10197         }
10198
10199         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10200
10201         ntups = PQntuples(res);
10202
10203         i_amprocnum = PQfnumber(res, "amprocnum");
10204         i_amproc = PQfnumber(res, "amproc");
10205         i_amproclefttype = PQfnumber(res, "amproclefttype");
10206         i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10207
10208         for (i = 0; i < ntups; i++)
10209         {
10210                 amprocnum = PQgetvalue(res, i, i_amprocnum);
10211                 amproc = PQgetvalue(res, i, i_amproc);
10212                 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10213                 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10214
10215                 if (needComma)
10216                         appendPQExpBuffer(q, " ,\n    ");
10217
10218                 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10219
10220                 if (*amproclefttype && *amprocrighttype)
10221                         appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10222
10223                 appendPQExpBuffer(q, " %s", amproc);
10224
10225                 needComma = true;
10226         }
10227
10228         PQclear(res);
10229
10230         appendPQExpBuffer(q, ";\n");
10231
10232         appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10233                                           fmtId(opcinfo->dobj.name));
10234         appendPQExpBuffer(labelq, " USING %s",
10235                                           fmtId(amname));
10236
10237         if (binary_upgrade)
10238                 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10239
10240         ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10241                                  opcinfo->dobj.name,
10242                                  opcinfo->dobj.namespace->dobj.name,
10243                                  NULL,
10244                                  opcinfo->rolname,
10245                                  false, "OPERATOR CLASS", SECTION_PRE_DATA,
10246                                  q->data, delq->data, NULL,
10247                                  opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
10248                                  NULL, NULL);
10249
10250         /* Dump Operator Class Comments */
10251         dumpComment(fout, labelq->data,
10252                                 NULL, opcinfo->rolname,
10253                                 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10254
10255         free(amname);
10256         destroyPQExpBuffer(query);
10257         destroyPQExpBuffer(q);
10258         destroyPQExpBuffer(delq);
10259         destroyPQExpBuffer(labelq);
10260 }
10261
10262 /*
10263  * dumpOpfamily
10264  *        write out a single operator family definition
10265  *
10266  * Note: this also dumps any "loose" operator members that aren't bound to a
10267  * specific opclass within the opfamily.
10268  */
10269 static void
10270 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10271 {
10272         PQExpBuffer query;
10273         PQExpBuffer q;
10274         PQExpBuffer delq;
10275         PQExpBuffer labelq;
10276         PGresult   *res;
10277         PGresult   *res_ops;
10278         PGresult   *res_procs;
10279         int                     ntups;
10280         int                     i_amname;
10281         int                     i_amopstrategy;
10282         int                     i_amopreqcheck;
10283         int                     i_amopopr;
10284         int                     i_sortfamily;
10285         int                     i_sortfamilynsp;
10286         int                     i_amprocnum;
10287         int                     i_amproc;
10288         int                     i_amproclefttype;
10289         int                     i_amprocrighttype;
10290         char       *amname;
10291         char       *amopstrategy;
10292         char       *amopreqcheck;
10293         char       *amopopr;
10294         char       *sortfamily;
10295         char       *sortfamilynsp;
10296         char       *amprocnum;
10297         char       *amproc;
10298         char       *amproclefttype;
10299         char       *amprocrighttype;
10300         bool            needComma;
10301         int                     i;
10302
10303         /* Skip if not to be dumped */
10304         if (!opfinfo->dobj.dump || dataOnly)
10305                 return;
10306
10307         /*
10308          * We want to dump the opfamily only if (1) it contains "loose" operators
10309          * or functions, or (2) it contains an opclass with a different name or
10310          * owner.  Otherwise it's sufficient to let it be created during creation
10311          * of the contained opclass, and not dumping it improves portability of
10312          * the dump.  Since we have to fetch the loose operators/funcs anyway, do
10313          * that first.
10314          */
10315
10316         query = createPQExpBuffer();
10317         q = createPQExpBuffer();
10318         delq = createPQExpBuffer();
10319         labelq = createPQExpBuffer();
10320
10321         /* Make sure we are in proper schema so regoperator works correctly */
10322         selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10323
10324         /*
10325          * Fetch only those opfamily members that are tied directly to the
10326          * opfamily by pg_depend entries.
10327          *
10328          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10329          * older server's opclass in which it is used.  This is to avoid
10330          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10331          * older server and then reload into that old version.  This can go away
10332          * once 8.3 is so old as to not be of interest to anyone.
10333          */
10334         if (fout->remoteVersion >= 90100)
10335         {
10336                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10337                                                   "amopopr::pg_catalog.regoperator, "
10338                                                   "opfname AS sortfamily, "
10339                                                   "nspname AS sortfamilynsp "
10340                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10341                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10342                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10343                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10344                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10345                                                   "AND refobjid = '%u'::pg_catalog.oid "
10346                                                   "AND amopfamily = '%u'::pg_catalog.oid "
10347                                                   "ORDER BY amopstrategy",
10348                                                   opfinfo->dobj.catId.oid,
10349                                                   opfinfo->dobj.catId.oid);
10350         }
10351         else if (fout->remoteVersion >= 80400)
10352         {
10353                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10354                                                   "amopopr::pg_catalog.regoperator, "
10355                                                   "NULL AS sortfamily, "
10356                                                   "NULL AS sortfamilynsp "
10357                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10358                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10359                                                   "AND refobjid = '%u'::pg_catalog.oid "
10360                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10361                                                   "AND objid = ao.oid "
10362                                                   "ORDER BY amopstrategy",
10363                                                   opfinfo->dobj.catId.oid);
10364         }
10365         else
10366         {
10367                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10368                                                   "amopopr::pg_catalog.regoperator, "
10369                                                   "NULL AS sortfamily, "
10370                                                   "NULL AS sortfamilynsp "
10371                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10372                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10373                                                   "AND refobjid = '%u'::pg_catalog.oid "
10374                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10375                                                   "AND objid = ao.oid "
10376                                                   "ORDER BY amopstrategy",
10377                                                   opfinfo->dobj.catId.oid);
10378         }
10379
10380         res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10381
10382         resetPQExpBuffer(query);
10383
10384         appendPQExpBuffer(query, "SELECT amprocnum, "
10385                                           "amproc::pg_catalog.regprocedure, "
10386                                           "amproclefttype::pg_catalog.regtype, "
10387                                           "amprocrighttype::pg_catalog.regtype "
10388                                           "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10389                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10390                                           "AND refobjid = '%u'::pg_catalog.oid "
10391                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10392                                           "AND objid = ap.oid "
10393                                           "ORDER BY amprocnum",
10394                                           opfinfo->dobj.catId.oid);
10395
10396         res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10397
10398         if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10399         {
10400                 /* No loose members, so check contained opclasses */
10401                 resetPQExpBuffer(query);
10402
10403                 appendPQExpBuffer(query, "SELECT 1 "
10404                                                   "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10405                                                   "WHERE f.oid = '%u'::pg_catalog.oid "
10406                         "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10407                                                   "AND refobjid = f.oid "
10408                                 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10409                                                   "AND objid = c.oid "
10410                                                   "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10411                                                   "LIMIT 1",
10412                                                   opfinfo->dobj.catId.oid);
10413
10414                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10415
10416                 if (PQntuples(res) == 0)
10417                 {
10418                         /* no need to dump it, so bail out */
10419                         PQclear(res);
10420                         PQclear(res_ops);
10421                         PQclear(res_procs);
10422                         destroyPQExpBuffer(query);
10423                         destroyPQExpBuffer(q);
10424                         destroyPQExpBuffer(delq);
10425                         destroyPQExpBuffer(labelq);
10426                         return;
10427                 }
10428
10429                 PQclear(res);
10430         }
10431
10432         /* Get additional fields from the pg_opfamily row */
10433         resetPQExpBuffer(query);
10434
10435         appendPQExpBuffer(query, "SELECT "
10436          "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10437                                           "FROM pg_catalog.pg_opfamily "
10438                                           "WHERE oid = '%u'::pg_catalog.oid",
10439                                           opfinfo->dobj.catId.oid);
10440
10441         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10442
10443         i_amname = PQfnumber(res, "amname");
10444
10445         /* amname will still be needed after we PQclear res */
10446         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10447
10448         /*
10449          * DROP must be fully qualified in case same name appears in pg_catalog
10450          */
10451         appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10452                                           fmtId(opfinfo->dobj.namespace->dobj.name));
10453         appendPQExpBuffer(delq, ".%s",
10454                                           fmtId(opfinfo->dobj.name));
10455         appendPQExpBuffer(delq, " USING %s;\n",
10456                                           fmtId(amname));
10457
10458         /* Build the fixed portion of the CREATE command */
10459         appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10460                                           fmtId(opfinfo->dobj.name));
10461         appendPQExpBuffer(q, " USING %s;\n",
10462                                           fmtId(amname));
10463
10464         PQclear(res);
10465
10466         /* Do we need an ALTER to add loose members? */
10467         if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10468         {
10469                 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10470                                                   fmtId(opfinfo->dobj.name));
10471                 appendPQExpBuffer(q, " USING %s ADD\n    ",
10472                                                   fmtId(amname));
10473
10474                 needComma = false;
10475
10476                 /*
10477                  * Now fetch and print the OPERATOR entries (pg_amop rows).
10478                  */
10479                 ntups = PQntuples(res_ops);
10480
10481                 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10482                 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10483                 i_amopopr = PQfnumber(res_ops, "amopopr");
10484                 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10485                 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10486
10487                 for (i = 0; i < ntups; i++)
10488                 {
10489                         amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10490                         amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10491                         amopopr = PQgetvalue(res_ops, i, i_amopopr);
10492                         sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10493                         sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10494
10495                         if (needComma)
10496                                 appendPQExpBuffer(q, " ,\n    ");
10497
10498                         appendPQExpBuffer(q, "OPERATOR %s %s",
10499                                                           amopstrategy, amopopr);
10500
10501                         if (strlen(sortfamily) > 0)
10502                         {
10503                                 appendPQExpBuffer(q, " FOR ORDER BY ");
10504                                 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10505                                         appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10506                                 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10507                         }
10508
10509                         if (strcmp(amopreqcheck, "t") == 0)
10510                                 appendPQExpBuffer(q, " RECHECK");
10511
10512                         needComma = true;
10513                 }
10514
10515                 /*
10516                  * Now fetch and print the FUNCTION entries (pg_amproc rows).
10517                  */
10518                 ntups = PQntuples(res_procs);
10519
10520                 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10521                 i_amproc = PQfnumber(res_procs, "amproc");
10522                 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10523                 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10524
10525                 for (i = 0; i < ntups; i++)
10526                 {
10527                         amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10528                         amproc = PQgetvalue(res_procs, i, i_amproc);
10529                         amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10530                         amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10531
10532                         if (needComma)
10533                                 appendPQExpBuffer(q, " ,\n    ");
10534
10535                         appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10536                                                           amprocnum, amproclefttype, amprocrighttype,
10537                                                           amproc);
10538
10539                         needComma = true;
10540                 }
10541
10542                 appendPQExpBuffer(q, ";\n");
10543         }
10544
10545         appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10546                                           fmtId(opfinfo->dobj.name));
10547         appendPQExpBuffer(labelq, " USING %s",
10548                                           fmtId(amname));
10549
10550         if (binary_upgrade)
10551                 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10552
10553         ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10554                                  opfinfo->dobj.name,
10555                                  opfinfo->dobj.namespace->dobj.name,
10556                                  NULL,
10557                                  opfinfo->rolname,
10558                                  false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10559                                  q->data, delq->data, NULL,
10560                                  opfinfo->dobj.dependencies, opfinfo->dobj.nDeps,
10561                                  NULL, NULL);
10562
10563         /* Dump Operator Family Comments */
10564         dumpComment(fout, labelq->data,
10565                                 NULL, opfinfo->rolname,
10566                                 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10567
10568         free(amname);
10569         PQclear(res_ops);
10570         PQclear(res_procs);
10571         destroyPQExpBuffer(query);
10572         destroyPQExpBuffer(q);
10573         destroyPQExpBuffer(delq);
10574         destroyPQExpBuffer(labelq);
10575 }
10576
10577 /*
10578  * dumpCollation
10579  *        write out a single collation definition
10580  */
10581 static void
10582 dumpCollation(Archive *fout, CollInfo *collinfo)
10583 {
10584         PQExpBuffer query;
10585         PQExpBuffer q;
10586         PQExpBuffer delq;
10587         PQExpBuffer labelq;
10588         PGresult   *res;
10589         int                     i_collcollate;
10590         int                     i_collctype;
10591         const char *collcollate;
10592         const char *collctype;
10593
10594         /* Skip if not to be dumped */
10595         if (!collinfo->dobj.dump || dataOnly)
10596                 return;
10597
10598         query = createPQExpBuffer();
10599         q = createPQExpBuffer();
10600         delq = createPQExpBuffer();
10601         labelq = createPQExpBuffer();
10602
10603         /* Make sure we are in proper schema */
10604         selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
10605
10606         /* Get conversion-specific details */
10607         appendPQExpBuffer(query, "SELECT "
10608                                           "collcollate, "
10609                                           "collctype "
10610                                           "FROM pg_catalog.pg_collation c "
10611                                           "WHERE c.oid = '%u'::pg_catalog.oid",
10612                                           collinfo->dobj.catId.oid);
10613
10614         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10615
10616         i_collcollate = PQfnumber(res, "collcollate");
10617         i_collctype = PQfnumber(res, "collctype");
10618
10619         collcollate = PQgetvalue(res, 0, i_collcollate);
10620         collctype = PQgetvalue(res, 0, i_collctype);
10621
10622         /*
10623          * DROP must be fully qualified in case same name appears in pg_catalog
10624          */
10625         appendPQExpBuffer(delq, "DROP COLLATION %s",
10626                                           fmtId(collinfo->dobj.namespace->dobj.name));
10627         appendPQExpBuffer(delq, ".%s;\n",
10628                                           fmtId(collinfo->dobj.name));
10629
10630         appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
10631                                           fmtId(collinfo->dobj.name));
10632         appendStringLiteralAH(q, collcollate, fout);
10633         appendPQExpBuffer(q, ", lc_ctype = ");
10634         appendStringLiteralAH(q, collctype, fout);
10635         appendPQExpBuffer(q, ");\n");
10636
10637         appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
10638
10639         if (binary_upgrade)
10640                 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
10641
10642         ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
10643                                  collinfo->dobj.name,
10644                                  collinfo->dobj.namespace->dobj.name,
10645                                  NULL,
10646                                  collinfo->rolname,
10647                                  false, "COLLATION", SECTION_PRE_DATA,
10648                                  q->data, delq->data, NULL,
10649                                  collinfo->dobj.dependencies, collinfo->dobj.nDeps,
10650                                  NULL, NULL);
10651
10652         /* Dump Collation Comments */
10653         dumpComment(fout, labelq->data,
10654                                 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
10655                                 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
10656
10657         PQclear(res);
10658
10659         destroyPQExpBuffer(query);
10660         destroyPQExpBuffer(q);
10661         destroyPQExpBuffer(delq);
10662         destroyPQExpBuffer(labelq);
10663 }
10664
10665 /*
10666  * dumpConversion
10667  *        write out a single conversion definition
10668  */
10669 static void
10670 dumpConversion(Archive *fout, ConvInfo *convinfo)
10671 {
10672         PQExpBuffer query;
10673         PQExpBuffer q;
10674         PQExpBuffer delq;
10675         PQExpBuffer labelq;
10676         PGresult   *res;
10677         int                     i_conforencoding;
10678         int                     i_contoencoding;
10679         int                     i_conproc;
10680         int                     i_condefault;
10681         const char *conforencoding;
10682         const char *contoencoding;
10683         const char *conproc;
10684         bool            condefault;
10685
10686         /* Skip if not to be dumped */
10687         if (!convinfo->dobj.dump || dataOnly)
10688                 return;
10689
10690         query = createPQExpBuffer();
10691         q = createPQExpBuffer();
10692         delq = createPQExpBuffer();
10693         labelq = createPQExpBuffer();
10694
10695         /* Make sure we are in proper schema */
10696         selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
10697
10698         /* Get conversion-specific details */
10699         appendPQExpBuffer(query, "SELECT "
10700                  "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
10701                    "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
10702                                           "conproc, condefault "
10703                                           "FROM pg_catalog.pg_conversion c "
10704                                           "WHERE c.oid = '%u'::pg_catalog.oid",
10705                                           convinfo->dobj.catId.oid);
10706
10707         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10708
10709         i_conforencoding = PQfnumber(res, "conforencoding");
10710         i_contoencoding = PQfnumber(res, "contoencoding");
10711         i_conproc = PQfnumber(res, "conproc");
10712         i_condefault = PQfnumber(res, "condefault");
10713
10714         conforencoding = PQgetvalue(res, 0, i_conforencoding);
10715         contoencoding = PQgetvalue(res, 0, i_contoencoding);
10716         conproc = PQgetvalue(res, 0, i_conproc);
10717         condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
10718
10719         /*
10720          * DROP must be fully qualified in case same name appears in pg_catalog
10721          */
10722         appendPQExpBuffer(delq, "DROP CONVERSION %s",
10723                                           fmtId(convinfo->dobj.namespace->dobj.name));
10724         appendPQExpBuffer(delq, ".%s;\n",
10725                                           fmtId(convinfo->dobj.name));
10726
10727         appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
10728                                           (condefault) ? "DEFAULT " : "",
10729                                           fmtId(convinfo->dobj.name));
10730         appendStringLiteralAH(q, conforencoding, fout);
10731         appendPQExpBuffer(q, " TO ");
10732         appendStringLiteralAH(q, contoencoding, fout);
10733         /* regproc is automatically quoted in 7.3 and above */
10734         appendPQExpBuffer(q, " FROM %s;\n", conproc);
10735
10736         appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
10737
10738         if (binary_upgrade)
10739                 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
10740
10741         ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
10742                                  convinfo->dobj.name,
10743                                  convinfo->dobj.namespace->dobj.name,
10744                                  NULL,
10745                                  convinfo->rolname,
10746                                  false, "CONVERSION", SECTION_PRE_DATA,
10747                                  q->data, delq->data, NULL,
10748                                  convinfo->dobj.dependencies, convinfo->dobj.nDeps,
10749                                  NULL, NULL);
10750
10751         /* Dump Conversion Comments */
10752         dumpComment(fout, labelq->data,
10753                                 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
10754                                 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
10755
10756         PQclear(res);
10757
10758         destroyPQExpBuffer(query);
10759         destroyPQExpBuffer(q);
10760         destroyPQExpBuffer(delq);
10761         destroyPQExpBuffer(labelq);
10762 }
10763
10764 /*
10765  * format_aggregate_signature: generate aggregate name and argument list
10766  *
10767  * The argument type names are qualified if needed.  The aggregate name
10768  * is never qualified.
10769  */
10770 static char *
10771 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
10772 {
10773         PQExpBufferData buf;
10774         int                     j;
10775
10776         initPQExpBuffer(&buf);
10777         if (honor_quotes)
10778                 appendPQExpBuffer(&buf, "%s",
10779                                                   fmtId(agginfo->aggfn.dobj.name));
10780         else
10781                 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
10782
10783         if (agginfo->aggfn.nargs == 0)
10784                 appendPQExpBuffer(&buf, "(*)");
10785         else
10786         {
10787                 appendPQExpBuffer(&buf, "(");
10788                 for (j = 0; j < agginfo->aggfn.nargs; j++)
10789                 {
10790                         char       *typname;
10791
10792                         typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
10793                                                                                    zeroAsOpaque);
10794
10795                         appendPQExpBuffer(&buf, "%s%s",
10796                                                           (j > 0) ? ", " : "",
10797                                                           typname);
10798                         free(typname);
10799                 }
10800                 appendPQExpBuffer(&buf, ")");
10801         }
10802         return buf.data;
10803 }
10804
10805 /*
10806  * dumpAgg
10807  *        write out a single aggregate definition
10808  */
10809 static void
10810 dumpAgg(Archive *fout, AggInfo *agginfo)
10811 {
10812         PQExpBuffer query;
10813         PQExpBuffer q;
10814         PQExpBuffer delq;
10815         PQExpBuffer labelq;
10816         PQExpBuffer details;
10817         char       *aggsig;
10818         char       *aggsig_tag;
10819         PGresult   *res;
10820         int                     i_aggtransfn;
10821         int                     i_aggfinalfn;
10822         int                     i_aggsortop;
10823         int                     i_aggtranstype;
10824         int                     i_agginitval;
10825         int                     i_convertok;
10826         const char *aggtransfn;
10827         const char *aggfinalfn;
10828         const char *aggsortop;
10829         const char *aggtranstype;
10830         const char *agginitval;
10831         bool            convertok;
10832
10833         /* Skip if not to be dumped */
10834         if (!agginfo->aggfn.dobj.dump || dataOnly)
10835                 return;
10836
10837         query = createPQExpBuffer();
10838         q = createPQExpBuffer();
10839         delq = createPQExpBuffer();
10840         labelq = createPQExpBuffer();
10841         details = createPQExpBuffer();
10842
10843         /* Make sure we are in proper schema */
10844         selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
10845
10846         /* Get aggregate-specific details */
10847         if (fout->remoteVersion >= 80100)
10848         {
10849                 appendPQExpBuffer(query, "SELECT aggtransfn, "
10850                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10851                                                   "aggsortop::pg_catalog.regoperator, "
10852                                                   "agginitval, "
10853                                                   "'t'::boolean AS convertok "
10854                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10855                                                   "WHERE a.aggfnoid = p.oid "
10856                                                   "AND p.oid = '%u'::pg_catalog.oid",
10857                                                   agginfo->aggfn.dobj.catId.oid);
10858         }
10859         else if (fout->remoteVersion >= 70300)
10860         {
10861                 appendPQExpBuffer(query, "SELECT aggtransfn, "
10862                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10863                                                   "0 AS aggsortop, "
10864                                                   "agginitval, "
10865                                                   "'t'::boolean AS convertok "
10866                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10867                                                   "WHERE a.aggfnoid = p.oid "
10868                                                   "AND p.oid = '%u'::pg_catalog.oid",
10869                                                   agginfo->aggfn.dobj.catId.oid);
10870         }
10871         else if (fout->remoteVersion >= 70100)
10872         {
10873                 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
10874                                                   "format_type(aggtranstype, NULL) AS aggtranstype, "
10875                                                   "0 AS aggsortop, "
10876                                                   "agginitval, "
10877                                                   "'t'::boolean AS convertok "
10878                                                   "FROM pg_aggregate "
10879                                                   "WHERE oid = '%u'::oid",
10880                                                   agginfo->aggfn.dobj.catId.oid);
10881         }
10882         else
10883         {
10884                 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
10885                                                   "aggfinalfn, "
10886                                                   "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
10887                                                   "0 AS aggsortop, "
10888                                                   "agginitval1 AS agginitval, "
10889                                                   "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
10890                                                   "FROM pg_aggregate "
10891                                                   "WHERE oid = '%u'::oid",
10892                                                   agginfo->aggfn.dobj.catId.oid);
10893         }
10894
10895         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10896
10897         i_aggtransfn = PQfnumber(res, "aggtransfn");
10898         i_aggfinalfn = PQfnumber(res, "aggfinalfn");
10899         i_aggsortop = PQfnumber(res, "aggsortop");
10900         i_aggtranstype = PQfnumber(res, "aggtranstype");
10901         i_agginitval = PQfnumber(res, "agginitval");
10902         i_convertok = PQfnumber(res, "convertok");
10903
10904         aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
10905         aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
10906         aggsortop = PQgetvalue(res, 0, i_aggsortop);
10907         aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
10908         agginitval = PQgetvalue(res, 0, i_agginitval);
10909         convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
10910
10911         aggsig = format_aggregate_signature(agginfo, fout, true);
10912         aggsig_tag = format_aggregate_signature(agginfo, fout, false);
10913
10914         if (!convertok)
10915         {
10916                 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
10917                                   aggsig);
10918                 return;
10919         }
10920
10921         if (fout->remoteVersion >= 70300)
10922         {
10923                 /* If using 7.3's regproc or regtype, data is already quoted */
10924                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
10925                                                   aggtransfn,
10926                                                   aggtranstype);
10927         }
10928         else if (fout->remoteVersion >= 70100)
10929         {
10930                 /* format_type quotes, regproc does not */
10931                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
10932                                                   fmtId(aggtransfn),
10933                                                   aggtranstype);
10934         }
10935         else
10936         {
10937                 /* need quotes all around */
10938                 appendPQExpBuffer(details, "    SFUNC = %s,\n",
10939                                                   fmtId(aggtransfn));
10940                 appendPQExpBuffer(details, "    STYPE = %s",
10941                                                   fmtId(aggtranstype));
10942         }
10943
10944         if (!PQgetisnull(res, 0, i_agginitval))
10945         {
10946                 appendPQExpBuffer(details, ",\n    INITCOND = ");
10947                 appendStringLiteralAH(details, agginitval, fout);
10948         }
10949
10950         if (strcmp(aggfinalfn, "-") != 0)
10951         {
10952                 appendPQExpBuffer(details, ",\n    FINALFUNC = %s",
10953                                                   aggfinalfn);
10954         }
10955
10956         aggsortop = convertOperatorReference(fout, aggsortop);
10957         if (aggsortop)
10958         {
10959                 appendPQExpBuffer(details, ",\n    SORTOP = %s",
10960                                                   aggsortop);
10961         }
10962
10963         /*
10964          * DROP must be fully qualified in case same name appears in pg_catalog
10965          */
10966         appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
10967                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
10968                                           aggsig);
10969
10970         appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
10971                                           aggsig, details->data);
10972
10973         appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
10974
10975         if (binary_upgrade)
10976                 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
10977
10978         ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
10979                                  aggsig_tag,
10980                                  agginfo->aggfn.dobj.namespace->dobj.name,
10981                                  NULL,
10982                                  agginfo->aggfn.rolname,
10983                                  false, "AGGREGATE", SECTION_PRE_DATA,
10984                                  q->data, delq->data, NULL,
10985                                  agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
10986                                  NULL, NULL);
10987
10988         /* Dump Aggregate Comments */
10989         dumpComment(fout, labelq->data,
10990                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
10991                                 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
10992         dumpSecLabel(fout, labelq->data,
10993                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
10994                                  agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
10995
10996         /*
10997          * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
10998          * command look like a function's GRANT; in particular this affects the
10999          * syntax for zero-argument aggregates.
11000          */
11001         free(aggsig);
11002         free(aggsig_tag);
11003
11004         aggsig = format_function_signature(fout, &agginfo->aggfn, true);
11005         aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
11006
11007         dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11008                         "FUNCTION",
11009                         aggsig, NULL, aggsig_tag,
11010                         agginfo->aggfn.dobj.namespace->dobj.name,
11011                         agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11012
11013         free(aggsig);
11014         free(aggsig_tag);
11015
11016         PQclear(res);
11017
11018         destroyPQExpBuffer(query);
11019         destroyPQExpBuffer(q);
11020         destroyPQExpBuffer(delq);
11021         destroyPQExpBuffer(labelq);
11022         destroyPQExpBuffer(details);
11023 }
11024
11025 /*
11026  * dumpTSParser
11027  *        write out a single text search parser
11028  */
11029 static void
11030 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11031 {
11032         PQExpBuffer q;
11033         PQExpBuffer delq;
11034         PQExpBuffer labelq;
11035
11036         /* Skip if not to be dumped */
11037         if (!prsinfo->dobj.dump || dataOnly)
11038                 return;
11039
11040         q = createPQExpBuffer();
11041         delq = createPQExpBuffer();
11042         labelq = createPQExpBuffer();
11043
11044         /* Make sure we are in proper schema */
11045         selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11046
11047         appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11048                                           fmtId(prsinfo->dobj.name));
11049
11050         appendPQExpBuffer(q, "    START = %s,\n",
11051                                           convertTSFunction(fout, prsinfo->prsstart));
11052         appendPQExpBuffer(q, "    GETTOKEN = %s,\n",
11053                                           convertTSFunction(fout, prsinfo->prstoken));
11054         appendPQExpBuffer(q, "    END = %s,\n",
11055                                           convertTSFunction(fout, prsinfo->prsend));
11056         if (prsinfo->prsheadline != InvalidOid)
11057                 appendPQExpBuffer(q, "    HEADLINE = %s,\n",
11058                                                   convertTSFunction(fout, prsinfo->prsheadline));
11059         appendPQExpBuffer(q, "    LEXTYPES = %s );\n",
11060                                           convertTSFunction(fout, prsinfo->prslextype));
11061
11062         /*
11063          * DROP must be fully qualified in case same name appears in pg_catalog
11064          */
11065         appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11066                                           fmtId(prsinfo->dobj.namespace->dobj.name));
11067         appendPQExpBuffer(delq, ".%s;\n",
11068                                           fmtId(prsinfo->dobj.name));
11069
11070         appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11071                                           fmtId(prsinfo->dobj.name));
11072
11073         if (binary_upgrade)
11074                 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11075
11076         ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11077                                  prsinfo->dobj.name,
11078                                  prsinfo->dobj.namespace->dobj.name,
11079                                  NULL,
11080                                  "",
11081                                  false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11082                                  q->data, delq->data, NULL,
11083                                  prsinfo->dobj.dependencies, prsinfo->dobj.nDeps,
11084                                  NULL, NULL);
11085
11086         /* Dump Parser Comments */
11087         dumpComment(fout, labelq->data,
11088                                 NULL, "",
11089                                 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11090
11091         destroyPQExpBuffer(q);
11092         destroyPQExpBuffer(delq);
11093         destroyPQExpBuffer(labelq);
11094 }
11095
11096 /*
11097  * dumpTSDictionary
11098  *        write out a single text search dictionary
11099  */
11100 static void
11101 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11102 {
11103         PQExpBuffer q;
11104         PQExpBuffer delq;
11105         PQExpBuffer labelq;
11106         PQExpBuffer query;
11107         PGresult   *res;
11108         char       *nspname;
11109         char       *tmplname;
11110
11111         /* Skip if not to be dumped */
11112         if (!dictinfo->dobj.dump || dataOnly)
11113                 return;
11114
11115         q = createPQExpBuffer();
11116         delq = createPQExpBuffer();
11117         labelq = createPQExpBuffer();
11118         query = createPQExpBuffer();
11119
11120         /* Fetch name and namespace of the dictionary's template */
11121         selectSourceSchema(fout, "pg_catalog");
11122         appendPQExpBuffer(query, "SELECT nspname, tmplname "
11123                                           "FROM pg_ts_template p, pg_namespace n "
11124                                           "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11125                                           dictinfo->dicttemplate);
11126         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11127         nspname = PQgetvalue(res, 0, 0);
11128         tmplname = PQgetvalue(res, 0, 1);
11129
11130         /* Make sure we are in proper schema */
11131         selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11132
11133         appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11134                                           fmtId(dictinfo->dobj.name));
11135
11136         appendPQExpBuffer(q, "    TEMPLATE = ");
11137         if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11138                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11139         appendPQExpBuffer(q, "%s", fmtId(tmplname));
11140
11141         PQclear(res);
11142
11143         /* the dictinitoption can be dumped straight into the command */
11144         if (dictinfo->dictinitoption)
11145                 appendPQExpBuffer(q, ",\n    %s", dictinfo->dictinitoption);
11146
11147         appendPQExpBuffer(q, " );\n");
11148
11149         /*
11150          * DROP must be fully qualified in case same name appears in pg_catalog
11151          */
11152         appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11153                                           fmtId(dictinfo->dobj.namespace->dobj.name));
11154         appendPQExpBuffer(delq, ".%s;\n",
11155                                           fmtId(dictinfo->dobj.name));
11156
11157         appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11158                                           fmtId(dictinfo->dobj.name));
11159
11160         if (binary_upgrade)
11161                 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11162
11163         ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11164                                  dictinfo->dobj.name,
11165                                  dictinfo->dobj.namespace->dobj.name,
11166                                  NULL,
11167                                  dictinfo->rolname,
11168                                  false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11169                                  q->data, delq->data, NULL,
11170                                  dictinfo->dobj.dependencies, dictinfo->dobj.nDeps,
11171                                  NULL, NULL);
11172
11173         /* Dump Dictionary Comments */
11174         dumpComment(fout, labelq->data,
11175                                 NULL, dictinfo->rolname,
11176                                 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11177
11178         destroyPQExpBuffer(q);
11179         destroyPQExpBuffer(delq);
11180         destroyPQExpBuffer(labelq);
11181         destroyPQExpBuffer(query);
11182 }
11183
11184 /*
11185  * dumpTSTemplate
11186  *        write out a single text search template
11187  */
11188 static void
11189 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11190 {
11191         PQExpBuffer q;
11192         PQExpBuffer delq;
11193         PQExpBuffer labelq;
11194
11195         /* Skip if not to be dumped */
11196         if (!tmplinfo->dobj.dump || dataOnly)
11197                 return;
11198
11199         q = createPQExpBuffer();
11200         delq = createPQExpBuffer();
11201         labelq = createPQExpBuffer();
11202
11203         /* Make sure we are in proper schema */
11204         selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11205
11206         appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11207                                           fmtId(tmplinfo->dobj.name));
11208
11209         if (tmplinfo->tmplinit != InvalidOid)
11210                 appendPQExpBuffer(q, "    INIT = %s,\n",
11211                                                   convertTSFunction(fout, tmplinfo->tmplinit));
11212         appendPQExpBuffer(q, "    LEXIZE = %s );\n",
11213                                           convertTSFunction(fout, tmplinfo->tmpllexize));
11214
11215         /*
11216          * DROP must be fully qualified in case same name appears in pg_catalog
11217          */
11218         appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11219                                           fmtId(tmplinfo->dobj.namespace->dobj.name));
11220         appendPQExpBuffer(delq, ".%s;\n",
11221                                           fmtId(tmplinfo->dobj.name));
11222
11223         appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11224                                           fmtId(tmplinfo->dobj.name));
11225
11226         if (binary_upgrade)
11227                 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11228
11229         ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11230                                  tmplinfo->dobj.name,
11231                                  tmplinfo->dobj.namespace->dobj.name,
11232                                  NULL,
11233                                  "",
11234                                  false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11235                                  q->data, delq->data, NULL,
11236                                  tmplinfo->dobj.dependencies, tmplinfo->dobj.nDeps,
11237                                  NULL, NULL);
11238
11239         /* Dump Template Comments */
11240         dumpComment(fout, labelq->data,
11241                                 NULL, "",
11242                                 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11243
11244         destroyPQExpBuffer(q);
11245         destroyPQExpBuffer(delq);
11246         destroyPQExpBuffer(labelq);
11247 }
11248
11249 /*
11250  * dumpTSConfig
11251  *        write out a single text search configuration
11252  */
11253 static void
11254 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11255 {
11256         PQExpBuffer q;
11257         PQExpBuffer delq;
11258         PQExpBuffer labelq;
11259         PQExpBuffer query;
11260         PGresult   *res;
11261         char       *nspname;
11262         char       *prsname;
11263         int                     ntups,
11264                                 i;
11265         int                     i_tokenname;
11266         int                     i_dictname;
11267
11268         /* Skip if not to be dumped */
11269         if (!cfginfo->dobj.dump || dataOnly)
11270                 return;
11271
11272         q = createPQExpBuffer();
11273         delq = createPQExpBuffer();
11274         labelq = createPQExpBuffer();
11275         query = createPQExpBuffer();
11276
11277         /* Fetch name and namespace of the config's parser */
11278         selectSourceSchema(fout, "pg_catalog");
11279         appendPQExpBuffer(query, "SELECT nspname, prsname "
11280                                           "FROM pg_ts_parser p, pg_namespace n "
11281                                           "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11282                                           cfginfo->cfgparser);
11283         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11284         nspname = PQgetvalue(res, 0, 0);
11285         prsname = PQgetvalue(res, 0, 1);
11286
11287         /* Make sure we are in proper schema */
11288         selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11289
11290         appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11291                                           fmtId(cfginfo->dobj.name));
11292
11293         appendPQExpBuffer(q, "    PARSER = ");
11294         if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11295                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11296         appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11297
11298         PQclear(res);
11299
11300         resetPQExpBuffer(query);
11301         appendPQExpBuffer(query,
11302                                           "SELECT \n"
11303                                           "  ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11304                                           "    WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11305                                           "  m.mapdict::pg_catalog.regdictionary AS dictname \n"
11306                                           "FROM pg_catalog.pg_ts_config_map AS m \n"
11307                                           "WHERE m.mapcfg = '%u' \n"
11308                                           "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11309                                           cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11310
11311         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11312         ntups = PQntuples(res);
11313
11314         i_tokenname = PQfnumber(res, "tokenname");
11315         i_dictname = PQfnumber(res, "dictname");
11316
11317         for (i = 0; i < ntups; i++)
11318         {
11319                 char       *tokenname = PQgetvalue(res, i, i_tokenname);
11320                 char       *dictname = PQgetvalue(res, i, i_dictname);
11321
11322                 if (i == 0 ||
11323                         strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11324                 {
11325                         /* starting a new token type, so start a new command */
11326                         if (i > 0)
11327                                 appendPQExpBuffer(q, ";\n");
11328                         appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11329                                                           fmtId(cfginfo->dobj.name));
11330                         /* tokenname needs quoting, dictname does NOT */
11331                         appendPQExpBuffer(q, "    ADD MAPPING FOR %s WITH %s",
11332                                                           fmtId(tokenname), dictname);
11333                 }
11334                 else
11335                         appendPQExpBuffer(q, ", %s", dictname);
11336         }
11337
11338         if (ntups > 0)
11339                 appendPQExpBuffer(q, ";\n");
11340
11341         PQclear(res);
11342
11343         /*
11344          * DROP must be fully qualified in case same name appears in pg_catalog
11345          */
11346         appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11347                                           fmtId(cfginfo->dobj.namespace->dobj.name));
11348         appendPQExpBuffer(delq, ".%s;\n",
11349                                           fmtId(cfginfo->dobj.name));
11350
11351         appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11352                                           fmtId(cfginfo->dobj.name));
11353
11354         if (binary_upgrade)
11355                 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11356
11357         ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11358                                  cfginfo->dobj.name,
11359                                  cfginfo->dobj.namespace->dobj.name,
11360                                  NULL,
11361                                  cfginfo->rolname,
11362                                  false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11363                                  q->data, delq->data, NULL,
11364                                  cfginfo->dobj.dependencies, cfginfo->dobj.nDeps,
11365                                  NULL, NULL);
11366
11367         /* Dump Configuration Comments */
11368         dumpComment(fout, labelq->data,
11369                                 NULL, cfginfo->rolname,
11370                                 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11371
11372         destroyPQExpBuffer(q);
11373         destroyPQExpBuffer(delq);
11374         destroyPQExpBuffer(labelq);
11375         destroyPQExpBuffer(query);
11376 }
11377
11378 /*
11379  * dumpForeignDataWrapper
11380  *        write out a single foreign-data wrapper definition
11381  */
11382 static void
11383 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11384 {
11385         PQExpBuffer q;
11386         PQExpBuffer delq;
11387         PQExpBuffer labelq;
11388         char       *qfdwname;
11389
11390         /* Skip if not to be dumped */
11391         if (!fdwinfo->dobj.dump || dataOnly)
11392                 return;
11393
11394         /*
11395          * FDWs that belong to an extension are dumped based on their "dump"
11396          * field. Otherwise omit them if we are only dumping some specific object.
11397          */
11398         if (!fdwinfo->dobj.ext_member)
11399                 if (!include_everything)
11400                         return;
11401
11402         q = createPQExpBuffer();
11403         delq = createPQExpBuffer();
11404         labelq = createPQExpBuffer();
11405
11406         qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11407
11408         appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11409                                           qfdwname);
11410
11411         if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11412                 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11413
11414         if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11415                 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11416
11417         if (strlen(fdwinfo->fdwoptions) > 0)
11418                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", fdwinfo->fdwoptions);
11419
11420         appendPQExpBuffer(q, ";\n");
11421
11422         appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11423                                           qfdwname);
11424
11425         appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11426                                           qfdwname);
11427
11428         if (binary_upgrade)
11429                 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11430
11431         ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11432                                  fdwinfo->dobj.name,
11433                                  NULL,
11434                                  NULL,
11435                                  fdwinfo->rolname,
11436                                  false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11437                                  q->data, delq->data, NULL,
11438                                  fdwinfo->dobj.dependencies, fdwinfo->dobj.nDeps,
11439                                  NULL, NULL);
11440
11441         /* Handle the ACL */
11442         dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11443                         "FOREIGN DATA WRAPPER",
11444                         qfdwname, NULL, fdwinfo->dobj.name,
11445                         NULL, fdwinfo->rolname,
11446                         fdwinfo->fdwacl);
11447
11448         /* Dump Foreign Data Wrapper Comments */
11449         dumpComment(fout, labelq->data,
11450                                 NULL, fdwinfo->rolname,
11451                                 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11452
11453         free(qfdwname);
11454
11455         destroyPQExpBuffer(q);
11456         destroyPQExpBuffer(delq);
11457         destroyPQExpBuffer(labelq);
11458 }
11459
11460 /*
11461  * dumpForeignServer
11462  *        write out a foreign server definition
11463  */
11464 static void
11465 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11466 {
11467         PQExpBuffer q;
11468         PQExpBuffer delq;
11469         PQExpBuffer labelq;
11470         PQExpBuffer query;
11471         PGresult   *res;
11472         char       *qsrvname;
11473         char       *fdwname;
11474
11475         /* Skip if not to be dumped */
11476         if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11477                 return;
11478
11479         q = createPQExpBuffer();
11480         delq = createPQExpBuffer();
11481         labelq = createPQExpBuffer();
11482         query = createPQExpBuffer();
11483
11484         qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11485
11486         /* look up the foreign-data wrapper */
11487         selectSourceSchema(fout, "pg_catalog");
11488         appendPQExpBuffer(query, "SELECT fdwname "
11489                                           "FROM pg_foreign_data_wrapper w "
11490                                           "WHERE w.oid = '%u'",
11491                                           srvinfo->srvfdw);
11492         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11493         fdwname = PQgetvalue(res, 0, 0);
11494
11495         appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11496         if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11497         {
11498                 appendPQExpBuffer(q, " TYPE ");
11499                 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11500         }
11501         if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11502         {
11503                 appendPQExpBuffer(q, " VERSION ");
11504                 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11505         }
11506
11507         appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11508         appendPQExpBuffer(q, "%s", fmtId(fdwname));
11509
11510         if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11511                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", srvinfo->srvoptions);
11512
11513         appendPQExpBuffer(q, ";\n");
11514
11515         appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11516                                           qsrvname);
11517
11518         appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11519
11520         if (binary_upgrade)
11521                 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11522
11523         ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11524                                  srvinfo->dobj.name,
11525                                  NULL,
11526                                  NULL,
11527                                  srvinfo->rolname,
11528                                  false, "SERVER", SECTION_PRE_DATA,
11529                                  q->data, delq->data, NULL,
11530                                  srvinfo->dobj.dependencies, srvinfo->dobj.nDeps,
11531                                  NULL, NULL);
11532
11533         /* Handle the ACL */
11534         dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11535                         "FOREIGN SERVER",
11536                         qsrvname, NULL, srvinfo->dobj.name,
11537                         NULL, srvinfo->rolname,
11538                         srvinfo->srvacl);
11539
11540         /* Dump user mappings */
11541         dumpUserMappings(fout,
11542                                          srvinfo->dobj.name, NULL,
11543                                          srvinfo->rolname,
11544                                          srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11545
11546         /* Dump Foreign Server Comments */
11547         dumpComment(fout, labelq->data,
11548                                 NULL, srvinfo->rolname,
11549                                 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11550
11551         free(qsrvname);
11552
11553         destroyPQExpBuffer(q);
11554         destroyPQExpBuffer(delq);
11555         destroyPQExpBuffer(labelq);
11556 }
11557
11558 /*
11559  * dumpUserMappings
11560  *
11561  * This routine is used to dump any user mappings associated with the
11562  * server handed to this routine. Should be called after ArchiveEntry()
11563  * for the server.
11564  */
11565 static void
11566 dumpUserMappings(Archive *fout,
11567                                  const char *servername, const char *namespace,
11568                                  const char *owner,
11569                                  CatalogId catalogId, DumpId dumpId)
11570 {
11571         PQExpBuffer q;
11572         PQExpBuffer delq;
11573         PQExpBuffer query;
11574         PQExpBuffer tag;
11575         PGresult   *res;
11576         int                     ntups;
11577         int                     i_usename;
11578         int                     i_umoptions;
11579         int                     i;
11580
11581         q = createPQExpBuffer();
11582         tag = createPQExpBuffer();
11583         delq = createPQExpBuffer();
11584         query = createPQExpBuffer();
11585
11586         /*
11587          * We read from the publicly accessible view pg_user_mappings, so as not
11588          * to fail if run by a non-superuser.  Note that the view will show
11589          * umoptions as null if the user hasn't got privileges for the associated
11590          * server; this means that pg_dump will dump such a mapping, but with no
11591          * OPTIONS clause.      A possible alternative is to skip such mappings
11592          * altogether, but it's not clear that that's an improvement.
11593          */
11594         selectSourceSchema(fout, "pg_catalog");
11595
11596         appendPQExpBuffer(query,
11597                                           "SELECT usename, "
11598                                           "array_to_string(ARRAY("
11599                                           "SELECT quote_ident(option_name) || ' ' || "
11600                                           "quote_literal(option_value) "
11601                                           "FROM pg_options_to_table(umoptions) "
11602                                           "ORDER BY option_name"
11603                                           "), E',\n    ') AS umoptions "
11604                                           "FROM pg_user_mappings "
11605                                           "WHERE srvid = '%u' "
11606                                           "ORDER BY usename",
11607                                           catalogId.oid);
11608
11609         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11610
11611         ntups = PQntuples(res);
11612         i_usename = PQfnumber(res, "usename");
11613         i_umoptions = PQfnumber(res, "umoptions");
11614
11615         for (i = 0; i < ntups; i++)
11616         {
11617                 char       *usename;
11618                 char       *umoptions;
11619
11620                 usename = PQgetvalue(res, i, i_usename);
11621                 umoptions = PQgetvalue(res, i, i_umoptions);
11622
11623                 resetPQExpBuffer(q);
11624                 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
11625                 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
11626
11627                 if (umoptions && strlen(umoptions) > 0)
11628                         appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", umoptions);
11629
11630                 appendPQExpBuffer(q, ";\n");
11631
11632                 resetPQExpBuffer(delq);
11633                 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
11634                 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
11635
11636                 resetPQExpBuffer(tag);
11637                 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
11638                                                   usename, servername);
11639
11640                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11641                                          tag->data,
11642                                          namespace,
11643                                          NULL,
11644                                          owner, false,
11645                                          "USER MAPPING", SECTION_PRE_DATA,
11646                                          q->data, delq->data, NULL,
11647                                          &dumpId, 1,
11648                                          NULL, NULL);
11649         }
11650
11651         PQclear(res);
11652
11653         destroyPQExpBuffer(query);
11654         destroyPQExpBuffer(delq);
11655         destroyPQExpBuffer(q);
11656 }
11657
11658 /*
11659  * Write out default privileges information
11660  */
11661 static void
11662 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
11663 {
11664         PQExpBuffer q;
11665         PQExpBuffer tag;
11666         const char *type;
11667
11668         /* Skip if not to be dumped */
11669         if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
11670                 return;
11671
11672         q = createPQExpBuffer();
11673         tag = createPQExpBuffer();
11674
11675         switch (daclinfo->defaclobjtype)
11676         {
11677                 case DEFACLOBJ_RELATION:
11678                         type = "TABLES";
11679                         break;
11680                 case DEFACLOBJ_SEQUENCE:
11681                         type = "SEQUENCES";
11682                         break;
11683                 case DEFACLOBJ_FUNCTION:
11684                         type = "FUNCTIONS";
11685                         break;
11686                 default:
11687                         /* shouldn't get here */
11688                         exit_horribly(NULL,
11689                                                   "unknown object type (%d) in default privileges\n",
11690                                                   (int) daclinfo->defaclobjtype);
11691                         type = "";                      /* keep compiler quiet */
11692         }
11693
11694         appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
11695
11696         /* build the actual command(s) for this tuple */
11697         if (!buildDefaultACLCommands(type,
11698                                                                  daclinfo->dobj.namespace != NULL ?
11699                                                                  daclinfo->dobj.namespace->dobj.name : NULL,
11700                                                                  daclinfo->defaclacl,
11701                                                                  daclinfo->defaclrole,
11702                                                                  fout->remoteVersion,
11703                                                                  q))
11704                 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
11705                                           daclinfo->defaclacl);
11706
11707         ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
11708                                  tag->data,
11709            daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
11710                                  NULL,
11711                                  daclinfo->defaclrole,
11712                                  false, "DEFAULT ACL", SECTION_NONE,
11713                                  q->data, "", NULL,
11714                                  daclinfo->dobj.dependencies, daclinfo->dobj.nDeps,
11715                                  NULL, NULL);
11716
11717         destroyPQExpBuffer(tag);
11718         destroyPQExpBuffer(q);
11719 }
11720
11721 /*----------
11722  * Write out grant/revoke information
11723  *
11724  * 'objCatId' is the catalog ID of the underlying object.
11725  * 'objDumpId' is the dump ID of the underlying object.
11726  * 'type' must be one of
11727  *              TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
11728  *              FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
11729  * 'name' is the formatted name of the object.  Must be quoted etc. already.
11730  * 'subname' is the formatted name of the sub-object, if any.  Must be quoted.
11731  * 'tag' is the tag for the archive entry (typ. unquoted name of object).
11732  * 'nspname' is the namespace the object is in (NULL if none).
11733  * 'owner' is the owner, NULL if there is no owner (for languages).
11734  * 'acls' is the string read out of the fooacl system catalog field;
11735  *              it will be parsed here.
11736  *----------
11737  */
11738 static void
11739 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
11740                 const char *type, const char *name, const char *subname,
11741                 const char *tag, const char *nspname, const char *owner,
11742                 const char *acls)
11743 {
11744         PQExpBuffer sql;
11745
11746         /* Do nothing if ACL dump is not enabled */
11747         if (aclsSkip)
11748                 return;
11749
11750         /* --data-only skips ACLs *except* BLOB ACLs */
11751         if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
11752                 return;
11753
11754         sql = createPQExpBuffer();
11755
11756         if (!buildACLCommands(name, subname, type, acls, owner,
11757                                                   "", fout->remoteVersion, sql))
11758                 exit_horribly(NULL,
11759                                           "could not parse ACL list (%s) for object \"%s\" (%s)\n",
11760                                           acls, name, type);
11761
11762         if (sql->len > 0)
11763                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11764                                          tag, nspname,
11765                                          NULL,
11766                                          owner ? owner : "",
11767                                          false, "ACL", SECTION_NONE,
11768                                          sql->data, "", NULL,
11769                                          &(objDumpId), 1,
11770                                          NULL, NULL);
11771
11772         destroyPQExpBuffer(sql);
11773 }
11774
11775 /*
11776  * dumpSecLabel
11777  *
11778  * This routine is used to dump any security labels associated with the
11779  * object handed to this routine. The routine takes a constant character
11780  * string for the target part of the security-label command, plus
11781  * the namespace and owner of the object (for labeling the ArchiveEntry),
11782  * plus catalog ID and subid which are the lookup key for pg_seclabel,
11783  * plus the dump ID for the object (for setting a dependency).
11784  * If a matching pg_seclabel entry is found, it is dumped.
11785  *
11786  * Note: although this routine takes a dumpId for dependency purposes,
11787  * that purpose is just to mark the dependency in the emitted dump file
11788  * for possible future use by pg_restore.  We do NOT use it for determining
11789  * ordering of the label in the dump file, because this routine is called
11790  * after dependency sorting occurs.  This routine should be called just after
11791  * calling ArchiveEntry() for the specified object.
11792  */
11793 static void
11794 dumpSecLabel(Archive *fout, const char *target,
11795                          const char *namespace, const char *owner,
11796                          CatalogId catalogId, int subid, DumpId dumpId)
11797 {
11798         SecLabelItem *labels;
11799         int                     nlabels;
11800         int                     i;
11801         PQExpBuffer query;
11802
11803         /* do nothing, if --no-security-labels is supplied */
11804         if (no_security_labels)
11805                 return;
11806
11807         /* Comments are schema not data ... except blob comments are data */
11808         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
11809         {
11810                 if (dataOnly)
11811                         return;
11812         }
11813         else
11814         {
11815                 if (schemaOnly)
11816                         return;
11817         }
11818
11819         /* Search for security labels associated with catalogId, using table */
11820         nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
11821
11822         query = createPQExpBuffer();
11823
11824         for (i = 0; i < nlabels; i++)
11825         {
11826                 /*
11827                  * Ignore label entries for which the subid doesn't match.
11828                  */
11829                 if (labels[i].objsubid != subid)
11830                         continue;
11831
11832                 appendPQExpBuffer(query,
11833                                                   "SECURITY LABEL FOR %s ON %s IS ",
11834                                                   fmtId(labels[i].provider), target);
11835                 appendStringLiteralAH(query, labels[i].label, fout);
11836                 appendPQExpBuffer(query, ";\n");
11837         }
11838
11839         if (query->len > 0)
11840         {
11841                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11842                                          target, namespace, NULL, owner,
11843                                          false, "SECURITY LABEL", SECTION_NONE,
11844                                          query->data, "", NULL,
11845                                          &(dumpId), 1,
11846                                          NULL, NULL);
11847         }
11848         destroyPQExpBuffer(query);
11849 }
11850
11851 /*
11852  * dumpTableSecLabel
11853  *
11854  * As above, but dump security label for both the specified table (or view)
11855  * and its columns.
11856  */
11857 static void
11858 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
11859 {
11860         SecLabelItem *labels;
11861         int                     nlabels;
11862         int                     i;
11863         PQExpBuffer query;
11864         PQExpBuffer target;
11865
11866         /* do nothing, if --no-security-labels is supplied */
11867         if (no_security_labels)
11868                 return;
11869
11870         /* SecLabel are SCHEMA not data */
11871         if (dataOnly)
11872                 return;
11873
11874         /* Search for comments associated with relation, using table */
11875         nlabels = findSecLabels(fout,
11876                                                         tbinfo->dobj.catId.tableoid,
11877                                                         tbinfo->dobj.catId.oid,
11878                                                         &labels);
11879
11880         /* If security labels exist, build SECURITY LABEL statements */
11881         if (nlabels <= 0)
11882                 return;
11883
11884         query = createPQExpBuffer();
11885         target = createPQExpBuffer();
11886
11887         for (i = 0; i < nlabels; i++)
11888         {
11889                 const char *colname;
11890                 const char *provider = labels[i].provider;
11891                 const char *label = labels[i].label;
11892                 int                     objsubid = labels[i].objsubid;
11893
11894                 resetPQExpBuffer(target);
11895                 if (objsubid == 0)
11896                 {
11897                         appendPQExpBuffer(target, "%s %s", reltypename,
11898                                                           fmtId(tbinfo->dobj.name));
11899                 }
11900                 else
11901                 {
11902                         colname = getAttrName(objsubid, tbinfo);
11903                         /* first fmtId result must be consumed before calling it again */
11904                         appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
11905                         appendPQExpBuffer(target, ".%s", fmtId(colname));
11906                 }
11907                 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
11908                                                   fmtId(provider), target->data);
11909                 appendStringLiteralAH(query, label, fout);
11910                 appendPQExpBuffer(query, ";\n");
11911         }
11912         if (query->len > 0)
11913         {
11914                 resetPQExpBuffer(target);
11915                 appendPQExpBuffer(target, "%s %s", reltypename,
11916                                                   fmtId(tbinfo->dobj.name));
11917                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11918                                          target->data,
11919                                          tbinfo->dobj.namespace->dobj.name,
11920                                          NULL, tbinfo->rolname,
11921                                          false, "SECURITY LABEL", SECTION_NONE,
11922                                          query->data, "", NULL,
11923                                          &(tbinfo->dobj.dumpId), 1,
11924                                          NULL, NULL);
11925         }
11926         destroyPQExpBuffer(query);
11927         destroyPQExpBuffer(target);
11928 }
11929
11930 /*
11931  * findSecLabels
11932  *
11933  * Find the security label(s), if any, associated with the given object.
11934  * All the objsubid values associated with the given classoid/objoid are
11935  * found with one search.
11936  */
11937 static int
11938 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
11939 {
11940         /* static storage for table of security labels */
11941         static SecLabelItem *labels = NULL;
11942         static int      nlabels = -1;
11943
11944         SecLabelItem *middle = NULL;
11945         SecLabelItem *low;
11946         SecLabelItem *high;
11947         int                     nmatch;
11948
11949         /* Get security labels if we didn't already */
11950         if (nlabels < 0)
11951                 nlabels = collectSecLabels(fout, &labels);
11952
11953         if (nlabels <= 0)                       /* no labels, so no match is possible */
11954         {
11955                 *items = NULL;
11956                 return 0;
11957         }
11958
11959         /*
11960          * Do binary search to find some item matching the object.
11961          */
11962         low = &labels[0];
11963         high = &labels[nlabels - 1];
11964         while (low <= high)
11965         {
11966                 middle = low + (high - low) / 2;
11967
11968                 if (classoid < middle->classoid)
11969                         high = middle - 1;
11970                 else if (classoid > middle->classoid)
11971                         low = middle + 1;
11972                 else if (objoid < middle->objoid)
11973                         high = middle - 1;
11974                 else if (objoid > middle->objoid)
11975                         low = middle + 1;
11976                 else
11977                         break;                          /* found a match */
11978         }
11979
11980         if (low > high)                         /* no matches */
11981         {
11982                 *items = NULL;
11983                 return 0;
11984         }
11985
11986         /*
11987          * Now determine how many items match the object.  The search loop
11988          * invariant still holds: only items between low and high inclusive could
11989          * match.
11990          */
11991         nmatch = 1;
11992         while (middle > low)
11993         {
11994                 if (classoid != middle[-1].classoid ||
11995                         objoid != middle[-1].objoid)
11996                         break;
11997                 middle--;
11998                 nmatch++;
11999         }
12000
12001         *items = middle;
12002
12003         middle += nmatch;
12004         while (middle <= high)
12005         {
12006                 if (classoid != middle->classoid ||
12007                         objoid != middle->objoid)
12008                         break;
12009                 middle++;
12010                 nmatch++;
12011         }
12012
12013         return nmatch;
12014 }
12015
12016 /*
12017  * collectSecLabels
12018  *
12019  * Construct a table of all security labels available for database objects.
12020  * It's much faster to pull them all at once.
12021  *
12022  * The table is sorted by classoid/objid/objsubid for speed in lookup.
12023  */
12024 static int
12025 collectSecLabels(Archive *fout, SecLabelItem **items)
12026 {
12027         PGresult   *res;
12028         PQExpBuffer query;
12029         int                     i_label;
12030         int                     i_provider;
12031         int                     i_classoid;
12032         int                     i_objoid;
12033         int                     i_objsubid;
12034         int                     ntups;
12035         int                     i;
12036         SecLabelItem *labels;
12037
12038         query = createPQExpBuffer();
12039
12040         appendPQExpBuffer(query,
12041                                           "SELECT label, provider, classoid, objoid, objsubid "
12042                                           "FROM pg_catalog.pg_seclabel "
12043                                           "ORDER BY classoid, objoid, objsubid");
12044
12045         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12046
12047         /* Construct lookup table containing OIDs in numeric form */
12048         i_label = PQfnumber(res, "label");
12049         i_provider = PQfnumber(res, "provider");
12050         i_classoid = PQfnumber(res, "classoid");
12051         i_objoid = PQfnumber(res, "objoid");
12052         i_objsubid = PQfnumber(res, "objsubid");
12053
12054         ntups = PQntuples(res);
12055
12056         labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12057
12058         for (i = 0; i < ntups; i++)
12059         {
12060                 labels[i].label = PQgetvalue(res, i, i_label);
12061                 labels[i].provider = PQgetvalue(res, i, i_provider);
12062                 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12063                 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12064                 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12065         }
12066
12067         /* Do NOT free the PGresult since we are keeping pointers into it */
12068         destroyPQExpBuffer(query);
12069
12070         *items = labels;
12071         return ntups;
12072 }
12073
12074 /*
12075  * dumpTable
12076  *        write out to fout the declarations (not data) of a user-defined table
12077  */
12078 static void
12079 dumpTable(Archive *fout, TableInfo *tbinfo)
12080 {
12081         if (tbinfo->dobj.dump)
12082         {
12083                 char       *namecopy;
12084
12085                 if (tbinfo->relkind == RELKIND_SEQUENCE)
12086                         dumpSequence(fout, tbinfo);
12087                 else if (!dataOnly)
12088                         dumpTableSchema(fout, tbinfo);
12089
12090                 /* Handle the ACL here */
12091                 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12092                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12093                                 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12094                                 "TABLE",
12095                                 namecopy, NULL, tbinfo->dobj.name,
12096                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12097                                 tbinfo->relacl);
12098
12099                 /*
12100                  * Handle column ACLs, if any.  Note: we pull these with a separate
12101                  * query rather than trying to fetch them during getTableAttrs, so
12102                  * that we won't miss ACLs on system columns.
12103                  */
12104                 if (fout->remoteVersion >= 80400)
12105                 {
12106                         PQExpBuffer query = createPQExpBuffer();
12107                         PGresult   *res;
12108                         int                     i;
12109
12110                         appendPQExpBuffer(query,
12111                                            "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12112                                                           "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12113                                                           "ORDER BY attnum",
12114                                                           tbinfo->dobj.catId.oid);
12115                         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12116
12117                         for (i = 0; i < PQntuples(res); i++)
12118                         {
12119                                 char       *attname = PQgetvalue(res, i, 0);
12120                                 char       *attacl = PQgetvalue(res, i, 1);
12121                                 char       *attnamecopy;
12122                                 char       *acltag;
12123
12124                                 attnamecopy = pg_strdup(fmtId(attname));
12125                                 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12126                                 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12127                                 /* Column's GRANT type is always TABLE */
12128                                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12129                                                 namecopy, attnamecopy, acltag,
12130                                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12131                                                 attacl);
12132                                 free(attnamecopy);
12133                                 free(acltag);
12134                         }
12135                         PQclear(res);
12136                         destroyPQExpBuffer(query);
12137                 }
12138
12139                 free(namecopy);
12140         }
12141 }
12142
12143 /*
12144  * dumpTableSchema
12145  *        write the declaration (not data) of one user-defined table or view
12146  */
12147 static void
12148 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12149 {
12150         PQExpBuffer query = createPQExpBuffer();
12151         PQExpBuffer q = createPQExpBuffer();
12152         PQExpBuffer delq = createPQExpBuffer();
12153         PQExpBuffer labelq = createPQExpBuffer();
12154         PGresult   *res;
12155         int                     numParents;
12156         TableInfo **parents;
12157         int                     actual_atts;    /* number of attrs in this CREATE statment */
12158         const char *reltypename;
12159         char       *storage;
12160         char       *srvname;
12161         char       *ftoptions;
12162         int                     j,
12163                                 k;
12164
12165         /* Make sure we are in proper schema */
12166         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12167
12168         if (binary_upgrade)
12169                 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12170                                                                                                 tbinfo->dobj.catId.oid);
12171
12172         /* Is it a table or a view? */
12173         if (tbinfo->relkind == RELKIND_VIEW)
12174         {
12175                 char       *viewdef;
12176
12177                 reltypename = "VIEW";
12178
12179                 /* Fetch the view definition */
12180                 if (fout->remoteVersion >= 70300)
12181                 {
12182                         /* Beginning in 7.3, viewname is not unique; rely on OID */
12183                         appendPQExpBuffer(query,
12184                                                           "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12185                                                           tbinfo->dobj.catId.oid);
12186                 }
12187                 else
12188                 {
12189                         appendPQExpBuffer(query, "SELECT definition AS viewdef "
12190                                                           "FROM pg_views WHERE viewname = ");
12191                         appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12192                         appendPQExpBuffer(query, ";");
12193                 }
12194
12195                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12196
12197                 if (PQntuples(res) != 1)
12198                 {
12199                         if (PQntuples(res) < 1)
12200                                 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12201                                                   tbinfo->dobj.name);
12202                         else
12203                                 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12204                                                   tbinfo->dobj.name);
12205                 }
12206
12207                 viewdef = PQgetvalue(res, 0, 0);
12208
12209                 if (strlen(viewdef) == 0)
12210                         exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12211                                                   tbinfo->dobj.name);
12212
12213                 /*
12214                  * DROP must be fully qualified in case same name appears in
12215                  * pg_catalog
12216                  */
12217                 appendPQExpBuffer(delq, "DROP VIEW %s.",
12218                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12219                 appendPQExpBuffer(delq, "%s;\n",
12220                                                   fmtId(tbinfo->dobj.name));
12221
12222                 if (binary_upgrade)
12223                         binary_upgrade_set_pg_class_oids(fout, q,
12224                                                                                          tbinfo->dobj.catId.oid, false);
12225
12226                 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12227                 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12228                         appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12229                 appendPQExpBuffer(q, " AS\n    %s\n", viewdef);
12230
12231                 appendPQExpBuffer(labelq, "VIEW %s",
12232                                                   fmtId(tbinfo->dobj.name));
12233
12234                 PQclear(res);
12235         }
12236         else
12237         {
12238                 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12239                 {
12240                         int                     i_srvname;
12241                         int                     i_ftoptions;
12242
12243                         reltypename = "FOREIGN TABLE";
12244
12245                         /* retrieve name of foreign server and generic options */
12246                         appendPQExpBuffer(query,
12247                                                           "SELECT fs.srvname, "
12248                                                           "pg_catalog.array_to_string(ARRAY("
12249                                                           "SELECT pg_catalog.quote_ident(option_name) || "
12250                                                           "' ' || pg_catalog.quote_literal(option_value) "
12251                                                           "FROM pg_catalog.pg_options_to_table(ftoptions) "
12252                                                           "ORDER BY option_name"
12253                                                           "), E',\n    ') AS ftoptions "
12254                                                           "FROM pg_catalog.pg_foreign_table ft "
12255                                                           "JOIN pg_catalog.pg_foreign_server fs "
12256                                                           "ON (fs.oid = ft.ftserver) "
12257                                                           "WHERE ft.ftrelid = '%u'",
12258                                                           tbinfo->dobj.catId.oid);
12259                         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12260                         i_srvname = PQfnumber(res, "srvname");
12261                         i_ftoptions = PQfnumber(res, "ftoptions");
12262                         srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12263                         ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12264                         PQclear(res);
12265                 }
12266                 else
12267                 {
12268                         reltypename = "TABLE";
12269                         srvname = NULL;
12270                         ftoptions = NULL;
12271                 }
12272                 numParents = tbinfo->numParents;
12273                 parents = tbinfo->parents;
12274
12275                 /*
12276                  * DROP must be fully qualified in case same name appears in
12277                  * pg_catalog
12278                  */
12279                 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12280                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12281                 appendPQExpBuffer(delq, "%s;\n",
12282                                                   fmtId(tbinfo->dobj.name));
12283
12284                 appendPQExpBuffer(labelq, "%s %s", reltypename,
12285                                                   fmtId(tbinfo->dobj.name));
12286
12287                 if (binary_upgrade)
12288                         binary_upgrade_set_pg_class_oids(fout, q,
12289                                                                                          tbinfo->dobj.catId.oid, false);
12290
12291                 appendPQExpBuffer(q, "CREATE %s%s %s",
12292                                                   tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12293                                                   "UNLOGGED " : "",
12294                                                   reltypename,
12295                                                   fmtId(tbinfo->dobj.name));
12296
12297                 /*
12298                  * Attach to type, if reloftype; except in case of a binary upgrade,
12299                  * we dump the table normally and attach it to the type afterward.
12300                  */
12301                 if (tbinfo->reloftype && !binary_upgrade)
12302                         appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12303
12304                 /* Dump the attributes */
12305                 actual_atts = 0;
12306                 for (j = 0; j < tbinfo->numatts; j++)
12307                 {
12308                         /*
12309                          * Normally, dump if it's locally defined in this table, and not
12310                          * dropped.  But for binary upgrade, we'll dump all the columns,
12311                          * and then fix up the dropped and nonlocal cases below.
12312                          */
12313                         if (shouldPrintColumn(tbinfo, j))
12314                         {
12315                                 /*
12316                                  * Default value --- suppress if to be printed separately.
12317                                  */
12318                                 bool            has_default = (tbinfo->attrdefs[j] != NULL &&
12319                                                                                    !tbinfo->attrdefs[j]->separate);
12320
12321                                 /*
12322                                  * Not Null constraint --- suppress if inherited, except in
12323                                  * binary-upgrade case where that won't work.
12324                                  */
12325                                 bool            has_notnull = (tbinfo->notnull[j] &&
12326                                                                                    (!tbinfo->inhNotNull[j] ||
12327                                                                                         binary_upgrade));
12328
12329                                 /* Skip column if fully defined by reloftype */
12330                                 if (tbinfo->reloftype &&
12331                                         !has_default && !has_notnull && !binary_upgrade)
12332                                         continue;
12333
12334                                 /* Format properly if not first attr */
12335                                 if (actual_atts == 0)
12336                                         appendPQExpBuffer(q, " (");
12337                                 else
12338                                         appendPQExpBuffer(q, ",");
12339                                 appendPQExpBuffer(q, "\n    ");
12340                                 actual_atts++;
12341
12342                                 /* Attribute name */
12343                                 appendPQExpBuffer(q, "%s ",
12344                                                                   fmtId(tbinfo->attnames[j]));
12345
12346                                 if (tbinfo->attisdropped[j])
12347                                 {
12348                                         /*
12349                                          * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12350                                          * so we will not have gotten a valid type name; insert
12351                                          * INTEGER as a stopgap.  We'll clean things up later.
12352                                          */
12353                                         appendPQExpBuffer(q, "INTEGER /* dummy */");
12354                                         /* Skip all the rest, too */
12355                                         continue;
12356                                 }
12357
12358                                 /* Attribute type */
12359                                 if (tbinfo->reloftype && !binary_upgrade)
12360                                 {
12361                                         appendPQExpBuffer(q, "WITH OPTIONS");
12362                                 }
12363                                 else if (fout->remoteVersion >= 70100)
12364                                 {
12365                                         appendPQExpBuffer(q, "%s",
12366                                                                           tbinfo->atttypnames[j]);
12367                                 }
12368                                 else
12369                                 {
12370                                         /* If no format_type, fake it */
12371                                         appendPQExpBuffer(q, "%s",
12372                                                                           myFormatType(tbinfo->atttypnames[j],
12373                                                                                                    tbinfo->atttypmod[j]));
12374                                 }
12375
12376                                 /* Add collation if not default for the type */
12377                                 if (OidIsValid(tbinfo->attcollation[j]))
12378                                 {
12379                                         CollInfo   *coll;
12380
12381                                         coll = findCollationByOid(tbinfo->attcollation[j]);
12382                                         if (coll)
12383                                         {
12384                                                 /* always schema-qualify, don't try to be smart */
12385                                                 appendPQExpBuffer(q, " COLLATE %s.",
12386                                                                          fmtId(coll->dobj.namespace->dobj.name));
12387                                                 appendPQExpBuffer(q, "%s",
12388                                                                                   fmtId(coll->dobj.name));
12389                                         }
12390                                 }
12391
12392                                 if (has_default)
12393                                         appendPQExpBuffer(q, " DEFAULT %s",
12394                                                                           tbinfo->attrdefs[j]->adef_expr);
12395
12396                                 if (has_notnull)
12397                                         appendPQExpBuffer(q, " NOT NULL");
12398                         }
12399                 }
12400
12401                 /*
12402                  * Add non-inherited CHECK constraints, if any.
12403                  */
12404                 for (j = 0; j < tbinfo->ncheck; j++)
12405                 {
12406                         ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12407
12408                         if (constr->separate || !constr->conislocal)
12409                                 continue;
12410
12411                         if (actual_atts == 0)
12412                                 appendPQExpBuffer(q, " (\n    ");
12413                         else
12414                                 appendPQExpBuffer(q, ",\n    ");
12415
12416                         appendPQExpBuffer(q, "CONSTRAINT %s ",
12417                                                           fmtId(constr->dobj.name));
12418                         appendPQExpBuffer(q, "%s", constr->condef);
12419
12420                         actual_atts++;
12421                 }
12422
12423                 if (actual_atts)
12424                         appendPQExpBuffer(q, "\n)");
12425                 else if (!(tbinfo->reloftype && !binary_upgrade))
12426                 {
12427                         /*
12428                          * We must have a parenthesized attribute list, even though empty,
12429                          * when not using the OF TYPE syntax.
12430                          */
12431                         appendPQExpBuffer(q, " (\n)");
12432                 }
12433
12434                 if (numParents > 0 && !binary_upgrade)
12435                 {
12436                         appendPQExpBuffer(q, "\nINHERITS (");
12437                         for (k = 0; k < numParents; k++)
12438                         {
12439                                 TableInfo  *parentRel = parents[k];
12440
12441                                 if (k > 0)
12442                                         appendPQExpBuffer(q, ", ");
12443                                 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12444                                         appendPQExpBuffer(q, "%s.",
12445                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
12446                                 appendPQExpBuffer(q, "%s",
12447                                                                   fmtId(parentRel->dobj.name));
12448                         }
12449                         appendPQExpBuffer(q, ")");
12450                 }
12451
12452                 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12453                         appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12454
12455                 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12456                   (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12457                 {
12458                         bool            addcomma = false;
12459
12460                         appendPQExpBuffer(q, "\nWITH (");
12461                         if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12462                         {
12463                                 addcomma = true;
12464                                 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12465                         }
12466                         if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12467                         {
12468                                 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12469                                                                   tbinfo->toast_reloptions);
12470                         }
12471                         appendPQExpBuffer(q, ")");
12472                 }
12473
12474                 /* Dump generic options if any */
12475                 if (ftoptions && ftoptions[0])
12476                         appendPQExpBuffer(q, "\nOPTIONS (\n    %s\n)", ftoptions);
12477
12478                 appendPQExpBuffer(q, ";\n");
12479
12480                 /*
12481                  * To create binary-compatible heap files, we have to ensure the same
12482                  * physical column order, including dropped columns, as in the
12483                  * original.  Therefore, we create dropped columns above and drop them
12484                  * here, also updating their attlen/attalign values so that the
12485                  * dropped column can be skipped properly.      (We do not bother with
12486                  * restoring the original attbyval setting.)  Also, inheritance
12487                  * relationships are set up by doing ALTER INHERIT rather than using
12488                  * an INHERITS clause --- the latter would possibly mess up the column
12489                  * order.  That also means we have to take care about setting
12490                  * attislocal correctly, plus fix up any inherited CHECK constraints.
12491                  * Analogously, we set up typed tables using ALTER TABLE / OF here.
12492                  */
12493                 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12494                 {
12495                         for (j = 0; j < tbinfo->numatts; j++)
12496                         {
12497                                 if (tbinfo->attisdropped[j])
12498                                 {
12499                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12500                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12501                                                                           "SET attlen = %d, "
12502                                                                           "attalign = '%c', attbyval = false\n"
12503                                                                           "WHERE attname = ",
12504                                                                           tbinfo->attlen[j],
12505                                                                           tbinfo->attalign[j]);
12506                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12507                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
12508                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12509                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12510
12511                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12512                                                                           fmtId(tbinfo->dobj.name));
12513                                         appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12514                                                                           fmtId(tbinfo->attnames[j]));
12515                                 }
12516                                 else if (!tbinfo->attislocal[j])
12517                                 {
12518                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12519                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12520                                                                           "SET attislocal = false\n"
12521                                                                           "WHERE attname = ");
12522                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12523                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
12524                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12525                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12526                                 }
12527                         }
12528
12529                         for (k = 0; k < tbinfo->ncheck; k++)
12530                         {
12531                                 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12532
12533                                 if (constr->separate || constr->conislocal)
12534                                         continue;
12535
12536                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12537                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12538                                                                   fmtId(tbinfo->dobj.name));
12539                                 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12540                                                                   fmtId(constr->dobj.name));
12541                                 appendPQExpBuffer(q, "%s;\n", constr->condef);
12542                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
12543                                                                   "SET conislocal = false\n"
12544                                                                   "WHERE contype = 'c' AND conname = ");
12545                                 appendStringLiteralAH(q, constr->dobj.name, fout);
12546                                 appendPQExpBuffer(q, "\n  AND conrelid = ");
12547                                 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12548                                 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12549                         }
12550
12551                         if (numParents > 0)
12552                         {
12553                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
12554                                 for (k = 0; k < numParents; k++)
12555                                 {
12556                                         TableInfo  *parentRel = parents[k];
12557
12558                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
12559                                                                           fmtId(tbinfo->dobj.name));
12560                                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12561                                                 appendPQExpBuffer(q, "%s.",
12562                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
12563                                         appendPQExpBuffer(q, "%s;\n",
12564                                                                           fmtId(parentRel->dobj.name));
12565                                 }
12566                         }
12567
12568                         if (tbinfo->reloftype)
12569                         {
12570                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
12571                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
12572                                                                   fmtId(tbinfo->dobj.name),
12573                                                                   tbinfo->reloftype);
12574                         }
12575
12576                         appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
12577                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12578                                                           "SET relfrozenxid = '%u'\n"
12579                                                           "WHERE oid = ",
12580                                                           tbinfo->frozenxid);
12581                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12582                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12583
12584                         if (tbinfo->toast_oid)
12585                         {
12586                                 /* We preserve the toast oids, so we can use it during restore */
12587                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
12588                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12589                                                                   "SET relfrozenxid = '%u'\n"
12590                                                                   "WHERE oid = '%u';\n",
12591                                                                   tbinfo->toast_frozenxid, tbinfo->toast_oid);
12592                         }
12593                 }
12594
12595                 /*
12596                  * Dump additional per-column properties that we can't handle in the
12597                  * main CREATE TABLE command.
12598                  */
12599                 for (j = 0; j < tbinfo->numatts; j++)
12600                 {
12601                         /* None of this applies to dropped columns */
12602                         if (tbinfo->attisdropped[j])
12603                                 continue;
12604
12605                         /*
12606                          * If we didn't dump the column definition explicitly above, and
12607                          * it is NOT NULL and did not inherit that property from a parent,
12608                          * we have to mark it separately.
12609                          */
12610                         if (!shouldPrintColumn(tbinfo, j) &&
12611                                 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
12612                         {
12613                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12614                                                                   fmtId(tbinfo->dobj.name));
12615                                 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
12616                                                                   fmtId(tbinfo->attnames[j]));
12617                         }
12618
12619                         /*
12620                          * Dump per-column statistics information. We only issue an ALTER
12621                          * TABLE statement if the attstattarget entry for this column is
12622                          * non-negative (i.e. it's not the default value)
12623                          */
12624                         if (tbinfo->attstattarget[j] >= 0)
12625                         {
12626                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12627                                                                   fmtId(tbinfo->dobj.name));
12628                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12629                                                                   fmtId(tbinfo->attnames[j]));
12630                                 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
12631                                                                   tbinfo->attstattarget[j]);
12632                         }
12633
12634                         /*
12635                          * Dump per-column storage information.  The statement is only
12636                          * dumped if the storage has been changed from the type's default.
12637                          */
12638                         if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
12639                         {
12640                                 switch (tbinfo->attstorage[j])
12641                                 {
12642                                         case 'p':
12643                                                 storage = "PLAIN";
12644                                                 break;
12645                                         case 'e':
12646                                                 storage = "EXTERNAL";
12647                                                 break;
12648                                         case 'm':
12649                                                 storage = "MAIN";
12650                                                 break;
12651                                         case 'x':
12652                                                 storage = "EXTENDED";
12653                                                 break;
12654                                         default:
12655                                                 storage = NULL;
12656                                 }
12657
12658                                 /*
12659                                  * Only dump the statement if it's a storage type we recognize
12660                                  */
12661                                 if (storage != NULL)
12662                                 {
12663                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12664                                                                           fmtId(tbinfo->dobj.name));
12665                                         appendPQExpBuffer(q, "ALTER COLUMN %s ",
12666                                                                           fmtId(tbinfo->attnames[j]));
12667                                         appendPQExpBuffer(q, "SET STORAGE %s;\n",
12668                                                                           storage);
12669                                 }
12670                         }
12671
12672                         /*
12673                          * Dump per-column attributes.
12674                          */
12675                         if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
12676                         {
12677                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12678                                                                   fmtId(tbinfo->dobj.name));
12679                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12680                                                                   fmtId(tbinfo->attnames[j]));
12681                                 appendPQExpBuffer(q, "SET (%s);\n",
12682                                                                   tbinfo->attoptions[j]);
12683                         }
12684
12685                         /*
12686                          * Dump per-column fdw options.
12687                          */
12688                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
12689                                 tbinfo->attfdwoptions[j] &&
12690                                 tbinfo->attfdwoptions[j][0] != '\0')
12691                         {
12692                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
12693                                                                   fmtId(tbinfo->dobj.name));
12694                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12695                                                                   fmtId(tbinfo->attnames[j]));
12696                                 appendPQExpBuffer(q, "OPTIONS (\n    %s\n);\n",
12697                                                                   tbinfo->attfdwoptions[j]);
12698                         }
12699                 }
12700         }
12701
12702         if (binary_upgrade)
12703                 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
12704
12705         ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12706                                  tbinfo->dobj.name,
12707                                  tbinfo->dobj.namespace->dobj.name,
12708                         (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
12709                                  tbinfo->rolname,
12710                            (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
12711                                  reltypename, SECTION_PRE_DATA,
12712                                  q->data, delq->data, NULL,
12713                                  tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
12714                                  NULL, NULL);
12715
12716
12717         /* Dump Table Comments */
12718         dumpTableComment(fout, tbinfo, reltypename);
12719
12720         /* Dump Table Security Labels */
12721         dumpTableSecLabel(fout, tbinfo, reltypename);
12722
12723         /* Dump comments on inlined table constraints */
12724         for (j = 0; j < tbinfo->ncheck; j++)
12725         {
12726                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12727
12728                 if (constr->separate || !constr->conislocal)
12729                         continue;
12730
12731                 dumpTableConstraintComment(fout, constr);
12732         }
12733
12734         destroyPQExpBuffer(query);
12735         destroyPQExpBuffer(q);
12736         destroyPQExpBuffer(delq);
12737         destroyPQExpBuffer(labelq);
12738 }
12739
12740 /*
12741  * dumpAttrDef --- dump an attribute's default-value declaration
12742  */
12743 static void
12744 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
12745 {
12746         TableInfo  *tbinfo = adinfo->adtable;
12747         int                     adnum = adinfo->adnum;
12748         PQExpBuffer q;
12749         PQExpBuffer delq;
12750
12751         /* Skip if table definition not to be dumped */
12752         if (!tbinfo->dobj.dump || dataOnly)
12753                 return;
12754
12755         /* Skip if not "separate"; it was dumped in the table's definition */
12756         if (!adinfo->separate)
12757                 return;
12758
12759         q = createPQExpBuffer();
12760         delq = createPQExpBuffer();
12761
12762         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12763                                           fmtId(tbinfo->dobj.name));
12764         appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
12765                                           fmtId(tbinfo->attnames[adnum - 1]),
12766                                           adinfo->adef_expr);
12767
12768         /*
12769          * DROP must be fully qualified in case same name appears in pg_catalog
12770          */
12771         appendPQExpBuffer(delq, "ALTER TABLE %s.",
12772                                           fmtId(tbinfo->dobj.namespace->dobj.name));
12773         appendPQExpBuffer(delq, "%s ",
12774                                           fmtId(tbinfo->dobj.name));
12775         appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
12776                                           fmtId(tbinfo->attnames[adnum - 1]));
12777
12778         ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
12779                                  tbinfo->attnames[adnum - 1],
12780                                  tbinfo->dobj.namespace->dobj.name,
12781                                  NULL,
12782                                  tbinfo->rolname,
12783                                  false, "DEFAULT", SECTION_PRE_DATA,
12784                                  q->data, delq->data, NULL,
12785                                  adinfo->dobj.dependencies, adinfo->dobj.nDeps,
12786                                  NULL, NULL);
12787
12788         destroyPQExpBuffer(q);
12789         destroyPQExpBuffer(delq);
12790 }
12791
12792 /*
12793  * getAttrName: extract the correct name for an attribute
12794  *
12795  * The array tblInfo->attnames[] only provides names of user attributes;
12796  * if a system attribute number is supplied, we have to fake it.
12797  * We also do a little bit of bounds checking for safety's sake.
12798  */
12799 static const char *
12800 getAttrName(int attrnum, TableInfo *tblInfo)
12801 {
12802         if (attrnum > 0 && attrnum <= tblInfo->numatts)
12803                 return tblInfo->attnames[attrnum - 1];
12804         switch (attrnum)
12805         {
12806                 case SelfItemPointerAttributeNumber:
12807                         return "ctid";
12808                 case ObjectIdAttributeNumber:
12809                         return "oid";
12810                 case MinTransactionIdAttributeNumber:
12811                         return "xmin";
12812                 case MinCommandIdAttributeNumber:
12813                         return "cmin";
12814                 case MaxTransactionIdAttributeNumber:
12815                         return "xmax";
12816                 case MaxCommandIdAttributeNumber:
12817                         return "cmax";
12818                 case TableOidAttributeNumber:
12819                         return "tableoid";
12820         }
12821         exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
12822                                   attrnum, tblInfo->dobj.name);
12823         return NULL;                            /* keep compiler quiet */
12824 }
12825
12826 /*
12827  * dumpIndex
12828  *        write out to fout a user-defined index
12829  */
12830 static void
12831 dumpIndex(Archive *fout, IndxInfo *indxinfo)
12832 {
12833         TableInfo  *tbinfo = indxinfo->indextable;
12834         PQExpBuffer q;
12835         PQExpBuffer delq;
12836         PQExpBuffer labelq;
12837
12838         if (dataOnly)
12839                 return;
12840
12841         q = createPQExpBuffer();
12842         delq = createPQExpBuffer();
12843         labelq = createPQExpBuffer();
12844
12845         appendPQExpBuffer(labelq, "INDEX %s",
12846                                           fmtId(indxinfo->dobj.name));
12847
12848         /*
12849          * If there's an associated constraint, don't dump the index per se, but
12850          * do dump any comment for it.  (This is safe because dependency ordering
12851          * will have ensured the constraint is emitted first.)
12852          */
12853         if (indxinfo->indexconstraint == 0)
12854         {
12855                 if (binary_upgrade)
12856                         binary_upgrade_set_pg_class_oids(fout, q,
12857                                                                                          indxinfo->dobj.catId.oid, true);
12858
12859                 /* Plain secondary index */
12860                 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
12861
12862                 /* If the index is clustered, we need to record that. */
12863                 if (indxinfo->indisclustered)
12864                 {
12865                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12866                                                           fmtId(tbinfo->dobj.name));
12867                         appendPQExpBuffer(q, " ON %s;\n",
12868                                                           fmtId(indxinfo->dobj.name));
12869                 }
12870
12871                 /*
12872                  * DROP must be fully qualified in case same name appears in
12873                  * pg_catalog
12874                  */
12875                 appendPQExpBuffer(delq, "DROP INDEX %s.",
12876                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12877                 appendPQExpBuffer(delq, "%s;\n",
12878                                                   fmtId(indxinfo->dobj.name));
12879
12880                 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
12881                                          indxinfo->dobj.name,
12882                                          tbinfo->dobj.namespace->dobj.name,
12883                                          indxinfo->tablespace,
12884                                          tbinfo->rolname, false,
12885                                          "INDEX", SECTION_POST_DATA,
12886                                          q->data, delq->data, NULL,
12887                                          indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
12888                                          NULL, NULL);
12889         }
12890
12891         /* Dump Index Comments */
12892         dumpComment(fout, labelq->data,
12893                                 tbinfo->dobj.namespace->dobj.name,
12894                                 tbinfo->rolname,
12895                                 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
12896
12897         destroyPQExpBuffer(q);
12898         destroyPQExpBuffer(delq);
12899         destroyPQExpBuffer(labelq);
12900 }
12901
12902 /*
12903  * dumpConstraint
12904  *        write out to fout a user-defined constraint
12905  */
12906 static void
12907 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
12908 {
12909         TableInfo  *tbinfo = coninfo->contable;
12910         PQExpBuffer q;
12911         PQExpBuffer delq;
12912
12913         /* Skip if not to be dumped */
12914         if (!coninfo->dobj.dump || dataOnly)
12915                 return;
12916
12917         q = createPQExpBuffer();
12918         delq = createPQExpBuffer();
12919
12920         if (coninfo->contype == 'p' ||
12921                 coninfo->contype == 'u' ||
12922                 coninfo->contype == 'x')
12923         {
12924                 /* Index-related constraint */
12925                 IndxInfo   *indxinfo;
12926                 int                     k;
12927
12928                 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
12929
12930                 if (indxinfo == NULL)
12931                         exit_horribly(NULL, "missing index for constraint \"%s\"\n",
12932                                                   coninfo->dobj.name);
12933
12934                 if (binary_upgrade)
12935                         binary_upgrade_set_pg_class_oids(fout, q,
12936                                                                                          indxinfo->dobj.catId.oid, true);
12937
12938                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
12939                                                   fmtId(tbinfo->dobj.name));
12940                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s ",
12941                                                   fmtId(coninfo->dobj.name));
12942
12943                 if (coninfo->condef)
12944                 {
12945                         /* pg_get_constraintdef should have provided everything */
12946                         appendPQExpBuffer(q, "%s;\n", coninfo->condef);
12947                 }
12948                 else
12949                 {
12950                         appendPQExpBuffer(q, "%s (",
12951                                                  coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
12952                         for (k = 0; k < indxinfo->indnkeys; k++)
12953                         {
12954                                 int                     indkey = (int) indxinfo->indkeys[k];
12955                                 const char *attname;
12956
12957                                 if (indkey == InvalidAttrNumber)
12958                                         break;
12959                                 attname = getAttrName(indkey, tbinfo);
12960
12961                                 appendPQExpBuffer(q, "%s%s",
12962                                                                   (k == 0) ? "" : ", ",
12963                                                                   fmtId(attname));
12964                         }
12965
12966                         appendPQExpBuffer(q, ")");
12967
12968                         if (indxinfo->options && strlen(indxinfo->options) > 0)
12969                                 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
12970
12971                         if (coninfo->condeferrable)
12972                         {
12973                                 appendPQExpBuffer(q, " DEFERRABLE");
12974                                 if (coninfo->condeferred)
12975                                         appendPQExpBuffer(q, " INITIALLY DEFERRED");
12976                         }
12977
12978                         appendPQExpBuffer(q, ";\n");
12979                 }
12980
12981                 /* If the index is clustered, we need to record that. */
12982                 if (indxinfo->indisclustered)
12983                 {
12984                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12985                                                           fmtId(tbinfo->dobj.name));
12986                         appendPQExpBuffer(q, " ON %s;\n",
12987                                                           fmtId(indxinfo->dobj.name));
12988                 }
12989
12990                 /*
12991                  * DROP must be fully qualified in case same name appears in
12992                  * pg_catalog
12993                  */
12994                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
12995                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12996                 appendPQExpBuffer(delq, "%s ",
12997                                                   fmtId(tbinfo->dobj.name));
12998                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
12999                                                   fmtId(coninfo->dobj.name));
13000
13001                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13002                                          coninfo->dobj.name,
13003                                          tbinfo->dobj.namespace->dobj.name,
13004                                          indxinfo->tablespace,
13005                                          tbinfo->rolname, false,
13006                                          "CONSTRAINT", SECTION_POST_DATA,
13007                                          q->data, delq->data, NULL,
13008                                          coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13009                                          NULL, NULL);
13010         }
13011         else if (coninfo->contype == 'f')
13012         {
13013                 /*
13014                  * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13015                  * current table data is not processed
13016                  */
13017                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13018                                                   fmtId(tbinfo->dobj.name));
13019                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13020                                                   fmtId(coninfo->dobj.name),
13021                                                   coninfo->condef);
13022
13023                 /*
13024                  * DROP must be fully qualified in case same name appears in
13025                  * pg_catalog
13026                  */
13027                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13028                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13029                 appendPQExpBuffer(delq, "%s ",
13030                                                   fmtId(tbinfo->dobj.name));
13031                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13032                                                   fmtId(coninfo->dobj.name));
13033
13034                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13035                                          coninfo->dobj.name,
13036                                          tbinfo->dobj.namespace->dobj.name,
13037                                          NULL,
13038                                          tbinfo->rolname, false,
13039                                          "FK CONSTRAINT", SECTION_POST_DATA,
13040                                          q->data, delq->data, NULL,
13041                                          coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13042                                          NULL, NULL);
13043         }
13044         else if (coninfo->contype == 'c' && tbinfo)
13045         {
13046                 /* CHECK constraint on a table */
13047
13048                 /* Ignore if not to be dumped separately */
13049                 if (coninfo->separate)
13050                 {
13051                         /* add ONLY if we do not want it to propagate to children */
13052                         appendPQExpBuffer(q, "ALTER TABLE %s %s\n",
13053                                                          coninfo->conisonly ? "ONLY" : "", fmtId(tbinfo->dobj.name));
13054                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13055                                                           fmtId(coninfo->dobj.name),
13056                                                           coninfo->condef);
13057
13058                         /*
13059                          * DROP must be fully qualified in case same name appears in
13060                          * pg_catalog
13061                          */
13062                         appendPQExpBuffer(delq, "ALTER TABLE %s.",
13063                                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13064                         appendPQExpBuffer(delq, "%s ",
13065                                                           fmtId(tbinfo->dobj.name));
13066                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13067                                                           fmtId(coninfo->dobj.name));
13068
13069                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13070                                                  coninfo->dobj.name,
13071                                                  tbinfo->dobj.namespace->dobj.name,
13072                                                  NULL,
13073                                                  tbinfo->rolname, false,
13074                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13075                                                  q->data, delq->data, NULL,
13076                                                  coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13077                                                  NULL, NULL);
13078                 }
13079         }
13080         else if (coninfo->contype == 'c' && tbinfo == NULL)
13081         {
13082                 /* CHECK constraint on a domain */
13083                 TypeInfo   *tyinfo = coninfo->condomain;
13084
13085                 /* Ignore if not to be dumped separately */
13086                 if (coninfo->separate)
13087                 {
13088                         appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13089                                                           fmtId(tyinfo->dobj.name));
13090                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13091                                                           fmtId(coninfo->dobj.name),
13092                                                           coninfo->condef);
13093
13094                         /*
13095                          * DROP must be fully qualified in case same name appears in
13096                          * pg_catalog
13097                          */
13098                         appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13099                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
13100                         appendPQExpBuffer(delq, "%s ",
13101                                                           fmtId(tyinfo->dobj.name));
13102                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13103                                                           fmtId(coninfo->dobj.name));
13104
13105                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13106                                                  coninfo->dobj.name,
13107                                                  tyinfo->dobj.namespace->dobj.name,
13108                                                  NULL,
13109                                                  tyinfo->rolname, false,
13110                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13111                                                  q->data, delq->data, NULL,
13112                                                  coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13113                                                  NULL, NULL);
13114                 }
13115         }
13116         else
13117         {
13118                 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13119                                           coninfo->contype);
13120         }
13121
13122         /* Dump Constraint Comments --- only works for table constraints */
13123         if (tbinfo && coninfo->separate)
13124                 dumpTableConstraintComment(fout, coninfo);
13125
13126         destroyPQExpBuffer(q);
13127         destroyPQExpBuffer(delq);
13128 }
13129
13130 /*
13131  * dumpTableConstraintComment --- dump a constraint's comment if any
13132  *
13133  * This is split out because we need the function in two different places
13134  * depending on whether the constraint is dumped as part of CREATE TABLE
13135  * or as a separate ALTER command.
13136  */
13137 static void
13138 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13139 {
13140         TableInfo  *tbinfo = coninfo->contable;
13141         PQExpBuffer labelq = createPQExpBuffer();
13142
13143         appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13144                                           fmtId(coninfo->dobj.name));
13145         appendPQExpBuffer(labelq, "ON %s",
13146                                           fmtId(tbinfo->dobj.name));
13147         dumpComment(fout, labelq->data,
13148                                 tbinfo->dobj.namespace->dobj.name,
13149                                 tbinfo->rolname,
13150                                 coninfo->dobj.catId, 0,
13151                          coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13152
13153         destroyPQExpBuffer(labelq);
13154 }
13155
13156 /*
13157  * findLastBuiltInOid -
13158  * find the last built in oid
13159  *
13160  * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13161  * pg_database entry for the current database
13162  */
13163 static Oid
13164 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13165 {
13166         PGresult   *res;
13167         Oid                     last_oid;
13168         PQExpBuffer query = createPQExpBuffer();
13169
13170         resetPQExpBuffer(query);
13171         appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13172         appendStringLiteralAH(query, dbname, fout);
13173
13174         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13175         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13176         PQclear(res);
13177         destroyPQExpBuffer(query);
13178         return last_oid;
13179 }
13180
13181 /*
13182  * findLastBuiltInOid -
13183  * find the last built in oid
13184  *
13185  * For 7.0, we do this by assuming that the last thing that initdb does is to
13186  * create the pg_indexes view.  This sucks in general, but seeing that 7.0.x
13187  * initdb won't be changing anymore, it'll do.
13188  */
13189 static Oid
13190 findLastBuiltinOid_V70(Archive *fout)
13191 {
13192         PGresult   *res;
13193         int                     last_oid;
13194
13195         res = ExecuteSqlQueryForSingleRow(fout,
13196                                         "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13197         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13198         PQclear(res);
13199         return last_oid;
13200 }
13201
13202 static void
13203 dumpSequence(Archive *fout, TableInfo *tbinfo)
13204 {
13205         PGresult   *res;
13206         char       *startv,
13207                            *last,
13208                            *incby,
13209                            *maxv = NULL,
13210                            *minv = NULL,
13211                            *cache;
13212         char            bufm[100],
13213                                 bufx[100];
13214         bool            cycled,
13215                                 called;
13216         PQExpBuffer query = createPQExpBuffer();
13217         PQExpBuffer delqry = createPQExpBuffer();
13218         PQExpBuffer labelq = createPQExpBuffer();
13219
13220         /* Make sure we are in proper schema */
13221         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13222
13223         snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13224         snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13225
13226         if (fout->remoteVersion >= 80400)
13227         {
13228                 appendPQExpBuffer(query,
13229                                                   "SELECT sequence_name, "
13230                                                   "start_value, last_value, increment_by, "
13231                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13232                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13233                                                   "     ELSE max_value "
13234                                                   "END AS max_value, "
13235                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13236                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13237                                                   "     ELSE min_value "
13238                                                   "END AS min_value, "
13239                                                   "cache_value, is_cycled, is_called from %s",
13240                                                   bufx, bufm,
13241                                                   fmtId(tbinfo->dobj.name));
13242         }
13243         else
13244         {
13245                 appendPQExpBuffer(query,
13246                                                   "SELECT sequence_name, "
13247                                                   "0 AS start_value, last_value, increment_by, "
13248                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13249                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13250                                                   "     ELSE max_value "
13251                                                   "END AS max_value, "
13252                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13253                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13254                                                   "     ELSE min_value "
13255                                                   "END AS min_value, "
13256                                                   "cache_value, is_cycled, is_called from %s",
13257                                                   bufx, bufm,
13258                                                   fmtId(tbinfo->dobj.name));
13259         }
13260
13261         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13262
13263         if (PQntuples(res) != 1)
13264         {
13265                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13266                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13267                                                                  PQntuples(res)),
13268                                   tbinfo->dobj.name, PQntuples(res));
13269                 exit_nicely(1);
13270         }
13271
13272         /* Disable this check: it fails if sequence has been renamed */
13273 #ifdef NOT_USED
13274         if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13275         {
13276                 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13277                                   tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13278                 exit_nicely(1);
13279         }
13280 #endif
13281
13282         startv = PQgetvalue(res, 0, 1);
13283         last = PQgetvalue(res, 0, 2);
13284         incby = PQgetvalue(res, 0, 3);
13285         if (!PQgetisnull(res, 0, 4))
13286                 maxv = PQgetvalue(res, 0, 4);
13287         if (!PQgetisnull(res, 0, 5))
13288                 minv = PQgetvalue(res, 0, 5);
13289         cache = PQgetvalue(res, 0, 6);
13290         cycled = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
13291         called = (strcmp(PQgetvalue(res, 0, 8), "t") == 0);
13292
13293         /*
13294          * The logic we use for restoring sequences is as follows:
13295          *
13296          * Add a CREATE SEQUENCE statement as part of a "schema" dump (use
13297          * last_val for start if called is false, else use min_val for start_val).
13298          * Also, if the sequence is owned by a column, add an ALTER SEQUENCE OWNED
13299          * BY command for it.
13300          *
13301          * Add a 'SETVAL(seq, last_val, iscalled)' as part of a "data" dump.
13302          */
13303         if (!dataOnly)
13304         {
13305                 /*
13306                  * DROP must be fully qualified in case same name appears in
13307                  * pg_catalog
13308                  */
13309                 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13310                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13311                 appendPQExpBuffer(delqry, "%s;\n",
13312                                                   fmtId(tbinfo->dobj.name));
13313
13314                 resetPQExpBuffer(query);
13315
13316                 if (binary_upgrade)
13317                 {
13318                         binary_upgrade_set_pg_class_oids(fout, query,
13319                                                                                          tbinfo->dobj.catId.oid, false);
13320                         binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13321                                                                                                         tbinfo->dobj.catId.oid);
13322                 }
13323
13324                 appendPQExpBuffer(query,
13325                                                   "CREATE SEQUENCE %s\n",
13326                                                   fmtId(tbinfo->dobj.name));
13327
13328                 if (fout->remoteVersion >= 80400)
13329                         appendPQExpBuffer(query, "    START WITH %s\n", startv);
13330                 else
13331                 {
13332                         /*
13333                          * Versions before 8.4 did not remember the true start value.  If
13334                          * is_called is false then the sequence has never been incremented
13335                          * so we can use last_val.      Otherwise punt and let it default.
13336                          */
13337                         if (!called)
13338                                 appendPQExpBuffer(query, "    START WITH %s\n", last);
13339                 }
13340
13341                 appendPQExpBuffer(query, "    INCREMENT BY %s\n", incby);
13342
13343                 if (minv)
13344                         appendPQExpBuffer(query, "    MINVALUE %s\n", minv);
13345                 else
13346                         appendPQExpBuffer(query, "    NO MINVALUE\n");
13347
13348                 if (maxv)
13349                         appendPQExpBuffer(query, "    MAXVALUE %s\n", maxv);
13350                 else
13351                         appendPQExpBuffer(query, "    NO MAXVALUE\n");
13352
13353                 appendPQExpBuffer(query,
13354                                                   "    CACHE %s%s",
13355                                                   cache, (cycled ? "\n    CYCLE" : ""));
13356
13357                 appendPQExpBuffer(query, ";\n");
13358
13359                 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13360
13361                 /* binary_upgrade:      no need to clear TOAST table oid */
13362
13363                 if (binary_upgrade)
13364                         binary_upgrade_extension_member(query, &tbinfo->dobj,
13365                                                                                         labelq->data);
13366
13367                 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13368                                          tbinfo->dobj.name,
13369                                          tbinfo->dobj.namespace->dobj.name,
13370                                          NULL,
13371                                          tbinfo->rolname,
13372                                          false, "SEQUENCE", SECTION_PRE_DATA,
13373                                          query->data, delqry->data, NULL,
13374                                          tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
13375                                          NULL, NULL);
13376
13377                 /*
13378                  * If the sequence is owned by a table column, emit the ALTER for it
13379                  * as a separate TOC entry immediately following the sequence's own
13380                  * entry.  It's OK to do this rather than using full sorting logic,
13381                  * because the dependency that tells us it's owned will have forced
13382                  * the table to be created first.  We can't just include the ALTER in
13383                  * the TOC entry because it will fail if we haven't reassigned the
13384                  * sequence owner to match the table's owner.
13385                  *
13386                  * We need not schema-qualify the table reference because both
13387                  * sequence and table must be in the same schema.
13388                  */
13389                 if (OidIsValid(tbinfo->owning_tab))
13390                 {
13391                         TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
13392
13393                         if (owning_tab && owning_tab->dobj.dump)
13394                         {
13395                                 resetPQExpBuffer(query);
13396                                 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13397                                                                   fmtId(tbinfo->dobj.name));
13398                                 appendPQExpBuffer(query, " OWNED BY %s",
13399                                                                   fmtId(owning_tab->dobj.name));
13400                                 appendPQExpBuffer(query, ".%s;\n",
13401                                                 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13402
13403                                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13404                                                          tbinfo->dobj.name,
13405                                                          tbinfo->dobj.namespace->dobj.name,
13406                                                          NULL,
13407                                                          tbinfo->rolname,
13408                                                          false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13409                                                          query->data, "", NULL,
13410                                                          &(tbinfo->dobj.dumpId), 1,
13411                                                          NULL, NULL);
13412                         }
13413                 }
13414
13415                 /* Dump Sequence Comments and Security Labels */
13416                 dumpComment(fout, labelq->data,
13417                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13418                                         tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13419                 dumpSecLabel(fout, labelq->data,
13420                                          tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13421                                          tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13422         }
13423
13424         if (!schemaOnly)
13425         {
13426                 resetPQExpBuffer(query);
13427                 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13428                 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13429                 appendPQExpBuffer(query, ", %s, %s);\n",
13430                                                   last, (called ? "true" : "false"));
13431
13432                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13433                                          tbinfo->dobj.name,
13434                                          tbinfo->dobj.namespace->dobj.name,
13435                                          NULL,
13436                                          tbinfo->rolname,
13437                                          false, "SEQUENCE SET", SECTION_PRE_DATA,
13438                                          query->data, "", NULL,
13439                                          &(tbinfo->dobj.dumpId), 1,
13440                                          NULL, NULL);
13441         }
13442
13443         PQclear(res);
13444
13445         destroyPQExpBuffer(query);
13446         destroyPQExpBuffer(delqry);
13447         destroyPQExpBuffer(labelq);
13448 }
13449
13450 static void
13451 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13452 {
13453         TableInfo  *tbinfo = tginfo->tgtable;
13454         PQExpBuffer query;
13455         PQExpBuffer delqry;
13456         PQExpBuffer labelq;
13457         char       *tgargs;
13458         size_t          lentgargs;
13459         const char *p;
13460         int                     findx;
13461
13462         if (dataOnly)
13463                 return;
13464
13465         query = createPQExpBuffer();
13466         delqry = createPQExpBuffer();
13467         labelq = createPQExpBuffer();
13468
13469         /*
13470          * DROP must be fully qualified in case same name appears in pg_catalog
13471          */
13472         appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13473                                           fmtId(tginfo->dobj.name));
13474         appendPQExpBuffer(delqry, "ON %s.",
13475                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13476         appendPQExpBuffer(delqry, "%s;\n",
13477                                           fmtId(tbinfo->dobj.name));
13478
13479         if (tginfo->tgdef)
13480         {
13481                 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13482         }
13483         else
13484         {
13485                 if (tginfo->tgisconstraint)
13486                 {
13487                         appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13488                         appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13489                 }
13490                 else
13491                 {
13492                         appendPQExpBuffer(query, "CREATE TRIGGER ");
13493                         appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13494                 }
13495                 appendPQExpBuffer(query, "\n    ");
13496
13497                 /* Trigger type */
13498                 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13499                         appendPQExpBuffer(query, "BEFORE");
13500                 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13501                         appendPQExpBuffer(query, "AFTER");
13502                 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13503                         appendPQExpBuffer(query, "INSTEAD OF");
13504                 else
13505                 {
13506                         write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13507                         exit_nicely(1);
13508                 }
13509
13510                 findx = 0;
13511                 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13512                 {
13513                         appendPQExpBuffer(query, " INSERT");
13514                         findx++;
13515                 }
13516                 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13517                 {
13518                         if (findx > 0)
13519                                 appendPQExpBuffer(query, " OR DELETE");
13520                         else
13521                                 appendPQExpBuffer(query, " DELETE");
13522                         findx++;
13523                 }
13524                 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13525                 {
13526                         if (findx > 0)
13527                                 appendPQExpBuffer(query, " OR UPDATE");
13528                         else
13529                                 appendPQExpBuffer(query, " UPDATE");
13530                         findx++;
13531                 }
13532                 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
13533                 {
13534                         if (findx > 0)
13535                                 appendPQExpBuffer(query, " OR TRUNCATE");
13536                         else
13537                                 appendPQExpBuffer(query, " TRUNCATE");
13538                         findx++;
13539                 }
13540                 appendPQExpBuffer(query, " ON %s\n",
13541                                                   fmtId(tbinfo->dobj.name));
13542
13543                 if (tginfo->tgisconstraint)
13544                 {
13545                         if (OidIsValid(tginfo->tgconstrrelid))
13546                         {
13547                                 /* If we are using regclass, name is already quoted */
13548                                 if (fout->remoteVersion >= 70300)
13549                                         appendPQExpBuffer(query, "    FROM %s\n    ",
13550                                                                           tginfo->tgconstrrelname);
13551                                 else
13552                                         appendPQExpBuffer(query, "    FROM %s\n    ",
13553                                                                           fmtId(tginfo->tgconstrrelname));
13554                         }
13555                         if (!tginfo->tgdeferrable)
13556                                 appendPQExpBuffer(query, "NOT ");
13557                         appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
13558                         if (tginfo->tginitdeferred)
13559                                 appendPQExpBuffer(query, "DEFERRED\n");
13560                         else
13561                                 appendPQExpBuffer(query, "IMMEDIATE\n");
13562                 }
13563
13564                 if (TRIGGER_FOR_ROW(tginfo->tgtype))
13565                         appendPQExpBuffer(query, "    FOR EACH ROW\n    ");
13566                 else
13567                         appendPQExpBuffer(query, "    FOR EACH STATEMENT\n    ");
13568
13569                 /* In 7.3, result of regproc is already quoted */
13570                 if (fout->remoteVersion >= 70300)
13571                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13572                                                           tginfo->tgfname);
13573                 else
13574                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13575                                                           fmtId(tginfo->tgfname));
13576
13577                 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
13578                                                                                   &lentgargs);
13579                 p = tgargs;
13580                 for (findx = 0; findx < tginfo->tgnargs; findx++)
13581                 {
13582                         /* find the embedded null that terminates this trigger argument */
13583                         size_t          tlen = strlen(p);
13584
13585                         if (p + tlen >= tgargs + lentgargs)
13586                         {
13587                                 /* hm, not found before end of bytea value... */
13588                                 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
13589                                                   tginfo->tgargs,
13590                                                   tginfo->dobj.name,
13591                                                   tbinfo->dobj.name);
13592                                 exit_nicely(1);
13593                         }
13594
13595                         if (findx > 0)
13596                                 appendPQExpBuffer(query, ", ");
13597                         appendStringLiteralAH(query, p, fout);
13598                         p += tlen + 1;
13599                 }
13600                 free(tgargs);
13601                 appendPQExpBuffer(query, ");\n");
13602         }
13603
13604         if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
13605         {
13606                 appendPQExpBuffer(query, "\nALTER TABLE %s ",
13607                                                   fmtId(tbinfo->dobj.name));
13608                 switch (tginfo->tgenabled)
13609                 {
13610                         case 'D':
13611                         case 'f':
13612                                 appendPQExpBuffer(query, "DISABLE");
13613                                 break;
13614                         case 'A':
13615                                 appendPQExpBuffer(query, "ENABLE ALWAYS");
13616                                 break;
13617                         case 'R':
13618                                 appendPQExpBuffer(query, "ENABLE REPLICA");
13619                                 break;
13620                         default:
13621                                 appendPQExpBuffer(query, "ENABLE");
13622                                 break;
13623                 }
13624                 appendPQExpBuffer(query, " TRIGGER %s;\n",
13625                                                   fmtId(tginfo->dobj.name));
13626         }
13627
13628         appendPQExpBuffer(labelq, "TRIGGER %s ",
13629                                           fmtId(tginfo->dobj.name));
13630         appendPQExpBuffer(labelq, "ON %s",
13631                                           fmtId(tbinfo->dobj.name));
13632
13633         ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
13634                                  tginfo->dobj.name,
13635                                  tbinfo->dobj.namespace->dobj.name,
13636                                  NULL,
13637                                  tbinfo->rolname, false,
13638                                  "TRIGGER", SECTION_POST_DATA,
13639                                  query->data, delqry->data, NULL,
13640                                  tginfo->dobj.dependencies, tginfo->dobj.nDeps,
13641                                  NULL, NULL);
13642
13643         dumpComment(fout, labelq->data,
13644                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13645                                 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
13646
13647         destroyPQExpBuffer(query);
13648         destroyPQExpBuffer(delqry);
13649         destroyPQExpBuffer(labelq);
13650 }
13651
13652 /*
13653  * dumpRule
13654  *              Dump a rule
13655  */
13656 static void
13657 dumpRule(Archive *fout, RuleInfo *rinfo)
13658 {
13659         TableInfo  *tbinfo = rinfo->ruletable;
13660         PQExpBuffer query;
13661         PQExpBuffer cmd;
13662         PQExpBuffer delcmd;
13663         PQExpBuffer labelq;
13664         PGresult   *res;
13665
13666         /* Skip if not to be dumped */
13667         if (!rinfo->dobj.dump || dataOnly)
13668                 return;
13669
13670         /*
13671          * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
13672          * we do not want to dump it as a separate object.
13673          */
13674         if (!rinfo->separate)
13675                 return;
13676
13677         /*
13678          * Make sure we are in proper schema.
13679          */
13680         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13681
13682         query = createPQExpBuffer();
13683         cmd = createPQExpBuffer();
13684         delcmd = createPQExpBuffer();
13685         labelq = createPQExpBuffer();
13686
13687         if (fout->remoteVersion >= 70300)
13688         {
13689                 appendPQExpBuffer(query,
13690                                                   "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
13691                                                   rinfo->dobj.catId.oid);
13692         }
13693         else
13694         {
13695                 /* Rule name was unique before 7.3 ... */
13696                 appendPQExpBuffer(query,
13697                                                   "SELECT pg_get_ruledef('%s') AS definition",
13698                                                   rinfo->dobj.name);
13699         }
13700
13701         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13702
13703         if (PQntuples(res) != 1)
13704         {
13705                 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
13706                                   rinfo->dobj.name, tbinfo->dobj.name);
13707                 exit_nicely(1);
13708         }
13709
13710         printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
13711
13712         /*
13713          * Add the command to alter the rules replication firing semantics if it
13714          * differs from the default.
13715          */
13716         if (rinfo->ev_enabled != 'O')
13717         {
13718                 appendPQExpBuffer(cmd, "ALTER TABLE %s.",
13719                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13720                 appendPQExpBuffer(cmd, "%s ",
13721                                                   fmtId(tbinfo->dobj.name));
13722                 switch (rinfo->ev_enabled)
13723                 {
13724                         case 'A':
13725                                 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
13726                                                                   fmtId(rinfo->dobj.name));
13727                                 break;
13728                         case 'R':
13729                                 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
13730                                                                   fmtId(rinfo->dobj.name));
13731                                 break;
13732                         case 'D':
13733                                 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
13734                                                                   fmtId(rinfo->dobj.name));
13735                                 break;
13736                 }
13737         }
13738
13739         /*
13740          * DROP must be fully qualified in case same name appears in pg_catalog
13741          */
13742         appendPQExpBuffer(delcmd, "DROP RULE %s ",
13743                                           fmtId(rinfo->dobj.name));
13744         appendPQExpBuffer(delcmd, "ON %s.",
13745                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13746         appendPQExpBuffer(delcmd, "%s;\n",
13747                                           fmtId(tbinfo->dobj.name));
13748
13749         appendPQExpBuffer(labelq, "RULE %s",
13750                                           fmtId(rinfo->dobj.name));
13751         appendPQExpBuffer(labelq, " ON %s",
13752                                           fmtId(tbinfo->dobj.name));
13753
13754         ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
13755                                  rinfo->dobj.name,
13756                                  tbinfo->dobj.namespace->dobj.name,
13757                                  NULL,
13758                                  tbinfo->rolname, false,
13759                                  "RULE", SECTION_POST_DATA,
13760                                  cmd->data, delcmd->data, NULL,
13761                                  rinfo->dobj.dependencies, rinfo->dobj.nDeps,
13762                                  NULL, NULL);
13763
13764         /* Dump rule comments */
13765         dumpComment(fout, labelq->data,
13766                                 tbinfo->dobj.namespace->dobj.name,
13767                                 tbinfo->rolname,
13768                                 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
13769
13770         PQclear(res);
13771
13772         destroyPQExpBuffer(query);
13773         destroyPQExpBuffer(cmd);
13774         destroyPQExpBuffer(delcmd);
13775         destroyPQExpBuffer(labelq);
13776 }
13777
13778 /*
13779  * getExtensionMembership --- obtain extension membership data
13780  */
13781 void
13782 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
13783                                            int numExtensions)
13784 {
13785         PQExpBuffer query;
13786         PGresult   *res;
13787         int                     ntups,
13788                                 i;
13789         int                     i_classid,
13790                                 i_objid,
13791                                 i_refclassid,
13792                                 i_refobjid;
13793         DumpableObject *dobj,
13794                            *refdobj;
13795
13796         /* Nothing to do if no extensions */
13797         if (numExtensions == 0)
13798                 return;
13799
13800         /* Make sure we are in proper schema */
13801         selectSourceSchema(fout, "pg_catalog");
13802
13803         query = createPQExpBuffer();
13804
13805         /* refclassid constraint is redundant but may speed the search */
13806         appendPQExpBuffer(query, "SELECT "
13807                                           "classid, objid, refclassid, refobjid "
13808                                           "FROM pg_depend "
13809                                           "WHERE refclassid = 'pg_extension'::regclass "
13810                                           "AND deptype = 'e' "
13811                                           "ORDER BY 3,4");
13812
13813         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13814
13815         ntups = PQntuples(res);
13816
13817         i_classid = PQfnumber(res, "classid");
13818         i_objid = PQfnumber(res, "objid");
13819         i_refclassid = PQfnumber(res, "refclassid");
13820         i_refobjid = PQfnumber(res, "refobjid");
13821
13822         /*
13823          * Since we ordered the SELECT by referenced ID, we can expect that
13824          * multiple entries for the same extension will appear together; this
13825          * saves on searches.
13826          */
13827         refdobj = NULL;
13828
13829         for (i = 0; i < ntups; i++)
13830         {
13831                 CatalogId       objId;
13832                 CatalogId       refobjId;
13833
13834                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
13835                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
13836                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
13837                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
13838
13839                 if (refdobj == NULL ||
13840                         refdobj->catId.tableoid != refobjId.tableoid ||
13841                         refdobj->catId.oid != refobjId.oid)
13842                         refdobj = findObjectByCatalogId(refobjId);
13843
13844                 /*
13845                  * Failure to find objects mentioned in pg_depend is not unexpected,
13846                  * since for example we don't collect info about TOAST tables.
13847                  */
13848                 if (refdobj == NULL)
13849                 {
13850 #ifdef NOT_USED
13851                         fprintf(stderr, "no referenced object %u %u\n",
13852                                         refobjId.tableoid, refobjId.oid);
13853 #endif
13854                         continue;
13855                 }
13856
13857                 dobj = findObjectByCatalogId(objId);
13858
13859                 if (dobj == NULL)
13860                 {
13861 #ifdef NOT_USED
13862                         fprintf(stderr, "no referencing object %u %u\n",
13863                                         objId.tableoid, objId.oid);
13864 #endif
13865                         continue;
13866                 }
13867
13868                 /* Record dependency so that getDependencies needn't repeat this */
13869                 addObjectDependency(dobj, refdobj->dumpId);
13870
13871                 dobj->ext_member = true;
13872
13873                 /*
13874                  * Normally, mark the member object as not to be dumped.  But in
13875                  * binary upgrades, we still dump the members individually, since the
13876                  * idea is to exactly reproduce the database contents rather than
13877                  * replace the extension contents with something different.
13878                  */
13879                 if (!binary_upgrade)
13880                         dobj->dump = false;
13881                 else
13882                         dobj->dump = refdobj->dump;
13883         }
13884
13885         PQclear(res);
13886
13887         /*
13888          * Now identify extension configuration tables and create TableDataInfo
13889          * objects for them, ensuring their data will be dumped even though the
13890          * tables themselves won't be.
13891          *
13892          * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
13893          * user data in a configuration table is treated like schema data. This
13894          * seems appropriate since system data in a config table would get
13895          * reloaded by CREATE EXTENSION.
13896          */
13897         for (i = 0; i < numExtensions; i++)
13898         {
13899                 ExtensionInfo *curext = &(extinfo[i]);
13900                 char       *extconfig = curext->extconfig;
13901                 char       *extcondition = curext->extcondition;
13902                 char      **extconfigarray = NULL;
13903                 char      **extconditionarray = NULL;
13904                 int                     nconfigitems;
13905                 int                     nconditionitems;
13906
13907                 /* Tables of not-to-be-dumped extensions shouldn't be dumped */
13908                 if (!curext->dobj.dump)
13909                         continue;
13910
13911                 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
13912                   parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
13913                         nconfigitems == nconditionitems)
13914                 {
13915                         int                     j;
13916
13917                         for (j = 0; j < nconfigitems; j++)
13918                         {
13919                                 TableInfo  *configtbl;
13920
13921                                 configtbl = findTableByOid(atooid(extconfigarray[j]));
13922                                 if (configtbl == NULL)
13923                                         continue;
13924
13925                                 /*
13926                                  * Note: config tables are dumped without OIDs regardless
13927                                  * of the --oids setting.  This is because row filtering
13928                                  * conditions aren't compatible with dumping OIDs.
13929                                  */
13930                                 makeTableDataInfo(configtbl, false);
13931                                 if (configtbl->dataObj != NULL)
13932                                 {
13933                                         if (strlen(extconditionarray[j]) > 0)
13934                                                 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
13935                                 }
13936                         }
13937                 }
13938                 if (extconfigarray)
13939                         free(extconfigarray);
13940                 if (extconditionarray)
13941                         free(extconditionarray);
13942         }
13943
13944         destroyPQExpBuffer(query);
13945 }
13946
13947 /*
13948  * getDependencies --- obtain available dependency data
13949  */
13950 static void
13951 getDependencies(Archive *fout)
13952 {
13953         PQExpBuffer query;
13954         PGresult   *res;
13955         int                     ntups,
13956                                 i;
13957         int                     i_classid,
13958                                 i_objid,
13959                                 i_refclassid,
13960                                 i_refobjid,
13961                                 i_deptype;
13962         DumpableObject *dobj,
13963                            *refdobj;
13964
13965         /* No dependency info available before 7.3 */
13966         if (fout->remoteVersion < 70300)
13967                 return;
13968
13969         if (g_verbose)
13970                 write_msg(NULL, "reading dependency data\n");
13971
13972         /* Make sure we are in proper schema */
13973         selectSourceSchema(fout, "pg_catalog");
13974
13975         query = createPQExpBuffer();
13976
13977         /*
13978          * PIN dependencies aren't interesting, and EXTENSION dependencies were
13979          * already processed by getExtensionMembership.
13980          */
13981         appendPQExpBuffer(query, "SELECT "
13982                                           "classid, objid, refclassid, refobjid, deptype "
13983                                           "FROM pg_depend "
13984                                           "WHERE deptype != 'p' AND deptype != 'e' "
13985                                           "ORDER BY 1,2");
13986
13987         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13988
13989         ntups = PQntuples(res);
13990
13991         i_classid = PQfnumber(res, "classid");
13992         i_objid = PQfnumber(res, "objid");
13993         i_refclassid = PQfnumber(res, "refclassid");
13994         i_refobjid = PQfnumber(res, "refobjid");
13995         i_deptype = PQfnumber(res, "deptype");
13996
13997         /*
13998          * Since we ordered the SELECT by referencing ID, we can expect that
13999          * multiple entries for the same object will appear together; this saves
14000          * on searches.
14001          */
14002         dobj = NULL;
14003
14004         for (i = 0; i < ntups; i++)
14005         {
14006                 CatalogId       objId;
14007                 CatalogId       refobjId;
14008                 char            deptype;
14009
14010                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14011                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14012                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14013                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14014                 deptype = *(PQgetvalue(res, i, i_deptype));
14015
14016                 if (dobj == NULL ||
14017                         dobj->catId.tableoid != objId.tableoid ||
14018                         dobj->catId.oid != objId.oid)
14019                         dobj = findObjectByCatalogId(objId);
14020
14021                 /*
14022                  * Failure to find objects mentioned in pg_depend is not unexpected,
14023                  * since for example we don't collect info about TOAST tables.
14024                  */
14025                 if (dobj == NULL)
14026                 {
14027 #ifdef NOT_USED
14028                         fprintf(stderr, "no referencing object %u %u\n",
14029                                         objId.tableoid, objId.oid);
14030 #endif
14031                         continue;
14032                 }
14033
14034                 refdobj = findObjectByCatalogId(refobjId);
14035
14036                 if (refdobj == NULL)
14037                 {
14038 #ifdef NOT_USED
14039                         fprintf(stderr, "no referenced object %u %u\n",
14040                                         refobjId.tableoid, refobjId.oid);
14041 #endif
14042                         continue;
14043                 }
14044
14045                 /*
14046                  * Ordinarily, table rowtypes have implicit dependencies on their
14047                  * tables.      However, for a composite type the implicit dependency goes
14048                  * the other way in pg_depend; which is the right thing for DROP but
14049                  * it doesn't produce the dependency ordering we need. So in that one
14050                  * case, we reverse the direction of the dependency.
14051                  */
14052                 if (deptype == 'i' &&
14053                         dobj->objType == DO_TABLE &&
14054                         refdobj->objType == DO_TYPE)
14055                         addObjectDependency(refdobj, dobj->dumpId);
14056                 else
14057                         /* normal case */
14058                         addObjectDependency(dobj, refdobj->dumpId);
14059         }
14060
14061         PQclear(res);
14062
14063         destroyPQExpBuffer(query);
14064 }
14065
14066
14067 /*
14068  * selectSourceSchema - make the specified schema the active search path
14069  * in the source database.
14070  *
14071  * NB: pg_catalog is explicitly searched after the specified schema;
14072  * so user names are only qualified if they are cross-schema references,
14073  * and system names are only qualified if they conflict with a user name
14074  * in the current schema.
14075  *
14076  * Whenever the selected schema is not pg_catalog, be careful to qualify
14077  * references to system catalogs and types in our emitted commands!
14078  */
14079 static void
14080 selectSourceSchema(Archive *fout, const char *schemaName)
14081 {
14082         static char *curSchemaName = NULL;
14083         PQExpBuffer query;
14084
14085         /* Not relevant if fetching from pre-7.3 DB */
14086         if (fout->remoteVersion < 70300)
14087                 return;
14088         /* Ignore null schema names */
14089         if (schemaName == NULL || *schemaName == '\0')
14090                 return;
14091         /* Optimize away repeated selection of same schema */
14092         if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14093                 return;
14094
14095         query = createPQExpBuffer();
14096         appendPQExpBuffer(query, "SET search_path = %s",
14097                                           fmtId(schemaName));
14098         if (strcmp(schemaName, "pg_catalog") != 0)
14099                 appendPQExpBuffer(query, ", pg_catalog");
14100
14101         ExecuteSqlStatement(fout, query->data);
14102
14103         destroyPQExpBuffer(query);
14104         if (curSchemaName)
14105                 free(curSchemaName);
14106         curSchemaName = pg_strdup(schemaName);
14107 }
14108
14109 /*
14110  * getFormattedTypeName - retrieve a nicely-formatted type name for the
14111  * given type name.
14112  *
14113  * NB: in 7.3 and up the result may depend on the currently-selected
14114  * schema; this is why we don't try to cache the names.
14115  */
14116 static char *
14117 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
14118 {
14119         char       *result;
14120         PQExpBuffer query;
14121         PGresult   *res;
14122
14123         if (oid == 0)
14124         {
14125                 if ((opts & zeroAsOpaque) != 0)
14126                         return pg_strdup(g_opaque_type);
14127                 else if ((opts & zeroAsAny) != 0)
14128                         return pg_strdup("'any'");
14129                 else if ((opts & zeroAsStar) != 0)
14130                         return pg_strdup("*");
14131                 else if ((opts & zeroAsNone) != 0)
14132                         return pg_strdup("NONE");
14133         }
14134
14135         query = createPQExpBuffer();
14136         if (fout->remoteVersion >= 70300)
14137         {
14138                 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14139                                                   oid);
14140         }
14141         else if (fout->remoteVersion >= 70100)
14142         {
14143                 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14144                                                   oid);
14145         }
14146         else
14147         {
14148                 appendPQExpBuffer(query, "SELECT typname "
14149                                                   "FROM pg_type "
14150                                                   "WHERE oid = '%u'::oid",
14151                                                   oid);
14152         }
14153
14154         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14155
14156         if (fout->remoteVersion >= 70100)
14157         {
14158                 /* already quoted */
14159                 result = pg_strdup(PQgetvalue(res, 0, 0));
14160         }
14161         else
14162         {
14163                 /* may need to quote it */
14164                 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14165         }
14166
14167         PQclear(res);
14168         destroyPQExpBuffer(query);
14169
14170         return result;
14171 }
14172
14173 /*
14174  * myFormatType --- local implementation of format_type for use with 7.0.
14175  */
14176 static char *
14177 myFormatType(const char *typname, int32 typmod)
14178 {
14179         char       *result;
14180         bool            isarray = false;
14181         PQExpBuffer buf = createPQExpBuffer();
14182
14183         /* Handle array types */
14184         if (typname[0] == '_')
14185         {
14186                 isarray = true;
14187                 typname++;
14188         }
14189
14190         /* Show lengths on bpchar and varchar */
14191         if (strcmp(typname, "bpchar") == 0)
14192         {
14193                 int                     len = (typmod - VARHDRSZ);
14194
14195                 appendPQExpBuffer(buf, "character");
14196                 if (len > 1)
14197                         appendPQExpBuffer(buf, "(%d)",
14198                                                           typmod - VARHDRSZ);
14199         }
14200         else if (strcmp(typname, "varchar") == 0)
14201         {
14202                 appendPQExpBuffer(buf, "character varying");
14203                 if (typmod != -1)
14204                         appendPQExpBuffer(buf, "(%d)",
14205                                                           typmod - VARHDRSZ);
14206         }
14207         else if (strcmp(typname, "numeric") == 0)
14208         {
14209                 appendPQExpBuffer(buf, "numeric");
14210                 if (typmod != -1)
14211                 {
14212                         int32           tmp_typmod;
14213                         int                     precision;
14214                         int                     scale;
14215
14216                         tmp_typmod = typmod - VARHDRSZ;
14217                         precision = (tmp_typmod >> 16) & 0xffff;
14218                         scale = tmp_typmod & 0xffff;
14219                         appendPQExpBuffer(buf, "(%d,%d)",
14220                                                           precision, scale);
14221                 }
14222         }
14223
14224         /*
14225          * char is an internal single-byte data type; Let's make sure we force it
14226          * through with quotes. - thomas 1998-12-13
14227          */
14228         else if (strcmp(typname, "char") == 0)
14229                 appendPQExpBuffer(buf, "\"char\"");
14230         else
14231                 appendPQExpBuffer(buf, "%s", fmtId(typname));
14232
14233         /* Append array qualifier for array types */
14234         if (isarray)
14235                 appendPQExpBuffer(buf, "[]");
14236
14237         result = pg_strdup(buf->data);
14238         destroyPQExpBuffer(buf);
14239
14240         return result;
14241 }
14242
14243 /*
14244  * fmtQualifiedId - convert a qualified name to the proper format for
14245  * the source database.
14246  *
14247  * Like fmtId, use the result before calling again.
14248  */
14249 static const char *
14250 fmtQualifiedId(Archive *fout, const char *schema, const char *id)
14251 {
14252         static PQExpBuffer id_return = NULL;
14253
14254         if (id_return)                          /* first time through? */
14255                 resetPQExpBuffer(id_return);
14256         else
14257                 id_return = createPQExpBuffer();
14258
14259         /* Suppress schema name if fetching from pre-7.3 DB */
14260         if (fout->remoteVersion >= 70300 && schema && *schema)
14261         {
14262                 appendPQExpBuffer(id_return, "%s.",
14263                                                   fmtId(schema));
14264         }
14265         appendPQExpBuffer(id_return, "%s",
14266                                           fmtId(id));
14267
14268         return id_return->data;
14269 }
14270
14271 /*
14272  * Return a column list clause for the given relation.
14273  *
14274  * Special case: if there are no undropped columns in the relation, return
14275  * "", not an invalid "()" column list.
14276  */
14277 static const char *
14278 fmtCopyColumnList(const TableInfo *ti)
14279 {
14280         static PQExpBuffer q = NULL;
14281         int                     numatts = ti->numatts;
14282         char      **attnames = ti->attnames;
14283         bool       *attisdropped = ti->attisdropped;
14284         bool            needComma;
14285         int                     i;
14286
14287         if (q)                                          /* first time through? */
14288                 resetPQExpBuffer(q);
14289         else
14290                 q = createPQExpBuffer();
14291
14292         appendPQExpBuffer(q, "(");
14293         needComma = false;
14294         for (i = 0; i < numatts; i++)
14295         {
14296                 if (attisdropped[i])
14297                         continue;
14298                 if (needComma)
14299                         appendPQExpBuffer(q, ", ");
14300                 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
14301                 needComma = true;
14302         }
14303
14304         if (!needComma)
14305                 return "";                              /* no undropped columns */
14306
14307         appendPQExpBuffer(q, ")");
14308         return q->data;
14309 }
14310
14311 /*
14312  * Execute an SQL query and verify that we got exactly one row back.
14313  */
14314 static PGresult *
14315 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
14316 {
14317         PGresult   *res;
14318         int                     ntups;
14319
14320         res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
14321
14322         /* Expecting a single result only */
14323         ntups = PQntuples(res);
14324         if (ntups != 1)
14325                 exit_horribly(NULL,
14326                                           ngettext("query returned %d row instead of one: %s\n",
14327                                                            "query returned %d rows instead of one: %s\n",
14328                                                                  ntups),
14329                                           ntups, query);
14330
14331         return res;
14332 }