]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_dump.c
Realign some --help output to have better spacing between columns
[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 and table-like objects.
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 relations that are not ordinary tables, sequences, views,
3856          * composite types, or foreign tables.
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                                  * convalidated is new in 9.2 (actually, it is there in 9.1,
5964                                  * but it wasn't ever false for check constraints until 9.2).
5965                                  */
5966                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5967                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5968                                                                   "conislocal, convalidated "
5969                                                                   "FROM pg_catalog.pg_constraint "
5970                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5971                                                                   "   AND contype = 'c' "
5972                                                                   "ORDER BY conname",
5973                                                                   tbinfo->dobj.catId.oid);
5974                         }
5975                         else if (fout->remoteVersion >= 80400)
5976                         {
5977                                 /* conislocal is new in 8.4 */
5978                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5979                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5980                                                                   "conislocal, true AS convalidated "
5981                                                                   "FROM pg_catalog.pg_constraint "
5982                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5983                                                                   "   AND contype = 'c' "
5984                                                                   "ORDER BY conname",
5985                                                                   tbinfo->dobj.catId.oid);
5986                         }
5987                         else if (fout->remoteVersion >= 70400)
5988                         {
5989                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5990                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5991                                                                   "true AS conislocal, true AS convalidated "
5992                                                                   "FROM pg_catalog.pg_constraint "
5993                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5994                                                                   "   AND contype = 'c' "
5995                                                                   "ORDER BY conname",
5996                                                                   tbinfo->dobj.catId.oid);
5997                         }
5998                         else if (fout->remoteVersion >= 70300)
5999                         {
6000                                 /* no pg_get_constraintdef, must use consrc */
6001                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6002                                                                   "'CHECK (' || consrc || ')' AS consrc, "
6003                                                                   "true AS conislocal, true AS convalidated "
6004                                                                   "FROM pg_catalog.pg_constraint "
6005                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6006                                                                   "   AND contype = 'c' "
6007                                                                   "ORDER BY conname",
6008                                                                   tbinfo->dobj.catId.oid);
6009                         }
6010                         else if (fout->remoteVersion >= 70200)
6011                         {
6012                                 /* 7.2 did not have OIDs in pg_relcheck */
6013                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6014                                                                   "rcname AS conname, "
6015                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6016                                                                   "true AS conislocal, true AS convalidated "
6017                                                                   "FROM pg_relcheck "
6018                                                                   "WHERE rcrelid = '%u'::oid "
6019                                                                   "ORDER BY rcname",
6020                                                                   tbinfo->dobj.catId.oid);
6021                         }
6022                         else if (fout->remoteVersion >= 70100)
6023                         {
6024                                 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6025                                                                   "rcname AS conname, "
6026                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6027                                                                   "true AS conislocal, true AS convalidated "
6028                                                                   "FROM pg_relcheck "
6029                                                                   "WHERE rcrelid = '%u'::oid "
6030                                                                   "ORDER BY rcname",
6031                                                                   tbinfo->dobj.catId.oid);
6032                         }
6033                         else
6034                         {
6035                                 /* no tableoid in 7.0 */
6036                                 appendPQExpBuffer(q, "SELECT "
6037                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6038                                                                   "oid, rcname AS conname, "
6039                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6040                                                                   "true AS conislocal, true AS convalidated "
6041                                                                   "FROM pg_relcheck "
6042                                                                   "WHERE rcrelid = '%u'::oid "
6043                                                                   "ORDER BY rcname",
6044                                                                   tbinfo->dobj.catId.oid);
6045                         }
6046                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6047
6048                         numConstrs = PQntuples(res);
6049                         if (numConstrs != tbinfo->ncheck)
6050                         {
6051                                 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6052                                                                                  "expected %d check constraints on table \"%s\" but found %d\n",
6053                                                                                  tbinfo->ncheck),
6054                                                   tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6055                                 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6056                                 exit_nicely(1);
6057                         }
6058
6059                         constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6060                         tbinfo->checkexprs = constrs;
6061
6062                         for (j = 0; j < numConstrs; j++)
6063                         {
6064                                 bool    validated = PQgetvalue(res, j, 5)[0] == 't';
6065
6066                                 constrs[j].dobj.objType = DO_CONSTRAINT;
6067                                 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6068                                 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6069                                 AssignDumpId(&constrs[j].dobj);
6070                                 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6071                                 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6072                                 constrs[j].contable = tbinfo;
6073                                 constrs[j].condomain = NULL;
6074                                 constrs[j].contype = 'c';
6075                                 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6076                                 constrs[j].confrelid = InvalidOid;
6077                                 constrs[j].conindex = 0;
6078                                 constrs[j].condeferrable = false;
6079                                 constrs[j].condeferred = false;
6080                                 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6081                                 /*
6082                                  * An unvalidated constraint needs to be dumped separately, so
6083                                  * that potentially-violating existing data is loaded before
6084                                  * the constraint.
6085                                  */
6086                                 constrs[j].separate = !validated;
6087
6088                                 constrs[j].dobj.dump = tbinfo->dobj.dump;
6089
6090                                 /*
6091                                  * Mark the constraint as needing to appear before the table
6092                                  * --- this is so that any other dependencies of the
6093                                  * constraint will be emitted before we try to create the
6094                                  * table.  If the constraint is to be dumped separately, it will be
6095                                  * dumped after data is loaded anyway, so don't do it.  (There's
6096                                  * an automatic dependency in the opposite direction anyway, so
6097                                  * don't need to add one manually here.)
6098                                  */
6099                                 if (!constrs[j].separate)
6100                                         addObjectDependency(&tbinfo->dobj,
6101                                                                                 constrs[j].dobj.dumpId);
6102
6103                                 /*
6104                                  * If the constraint is inherited, this will be detected later
6105                                  * (in pre-8.4 databases).      We also detect later if the
6106                                  * constraint must be split out from the table definition.
6107                                  */
6108                         }
6109                         PQclear(res);
6110                 }
6111         }
6112
6113         destroyPQExpBuffer(q);
6114 }
6115
6116 /*
6117  * Test whether a column should be printed as part of table's CREATE TABLE.
6118  * Column number is zero-based.
6119  *
6120  * Normally this is always true, but it's false for dropped columns, as well
6121  * as those that were inherited without any local definition.  (If we print
6122  * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6123  * However, in binary_upgrade mode, we must print all such columns anyway and
6124  * fix the attislocal/attisdropped state later, so as to keep control of the
6125  * physical column order.
6126  *
6127  * This function exists because there are scattered nonobvious places that
6128  * must be kept in sync with this decision.
6129  */
6130 bool
6131 shouldPrintColumn(TableInfo *tbinfo, int colno)
6132 {
6133         if (binary_upgrade)
6134                 return true;
6135         return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6136 }
6137
6138
6139 /*
6140  * getTSParsers:
6141  *        read all text search parsers in the system catalogs and return them
6142  *        in the TSParserInfo* structure
6143  *
6144  *      numTSParsers is set to the number of parsers read in
6145  */
6146 TSParserInfo *
6147 getTSParsers(Archive *fout, int *numTSParsers)
6148 {
6149         PGresult   *res;
6150         int                     ntups;
6151         int                     i;
6152         PQExpBuffer query;
6153         TSParserInfo *prsinfo;
6154         int                     i_tableoid;
6155         int                     i_oid;
6156         int                     i_prsname;
6157         int                     i_prsnamespace;
6158         int                     i_prsstart;
6159         int                     i_prstoken;
6160         int                     i_prsend;
6161         int                     i_prsheadline;
6162         int                     i_prslextype;
6163
6164         /* Before 8.3, there is no built-in text search support */
6165         if (fout->remoteVersion < 80300)
6166         {
6167                 *numTSParsers = 0;
6168                 return NULL;
6169         }
6170
6171         query = createPQExpBuffer();
6172
6173         /*
6174          * find all text search objects, including builtin ones; we filter out
6175          * system-defined objects at dump-out time.
6176          */
6177
6178         /* Make sure we are in proper schema */
6179         selectSourceSchema(fout, "pg_catalog");
6180
6181         appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6182                                           "prsstart::oid, prstoken::oid, "
6183                                           "prsend::oid, prsheadline::oid, prslextype::oid "
6184                                           "FROM pg_ts_parser");
6185
6186         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6187
6188         ntups = PQntuples(res);
6189         *numTSParsers = ntups;
6190
6191         prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6192
6193         i_tableoid = PQfnumber(res, "tableoid");
6194         i_oid = PQfnumber(res, "oid");
6195         i_prsname = PQfnumber(res, "prsname");
6196         i_prsnamespace = PQfnumber(res, "prsnamespace");
6197         i_prsstart = PQfnumber(res, "prsstart");
6198         i_prstoken = PQfnumber(res, "prstoken");
6199         i_prsend = PQfnumber(res, "prsend");
6200         i_prsheadline = PQfnumber(res, "prsheadline");
6201         i_prslextype = PQfnumber(res, "prslextype");
6202
6203         for (i = 0; i < ntups; i++)
6204         {
6205                 prsinfo[i].dobj.objType = DO_TSPARSER;
6206                 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6207                 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6208                 AssignDumpId(&prsinfo[i].dobj);
6209                 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6210                 prsinfo[i].dobj.namespace =
6211                         findNamespace(fout,
6212                                                   atooid(PQgetvalue(res, i, i_prsnamespace)),
6213                                                   prsinfo[i].dobj.catId.oid);
6214                 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6215                 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6216                 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6217                 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6218                 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6219
6220                 /* Decide whether we want to dump it */
6221                 selectDumpableObject(&(prsinfo[i].dobj));
6222         }
6223
6224         PQclear(res);
6225
6226         destroyPQExpBuffer(query);
6227
6228         return prsinfo;
6229 }
6230
6231 /*
6232  * getTSDictionaries:
6233  *        read all text search dictionaries in the system catalogs and return them
6234  *        in the TSDictInfo* structure
6235  *
6236  *      numTSDicts is set to the number of dictionaries read in
6237  */
6238 TSDictInfo *
6239 getTSDictionaries(Archive *fout, int *numTSDicts)
6240 {
6241         PGresult   *res;
6242         int                     ntups;
6243         int                     i;
6244         PQExpBuffer query;
6245         TSDictInfo *dictinfo;
6246         int                     i_tableoid;
6247         int                     i_oid;
6248         int                     i_dictname;
6249         int                     i_dictnamespace;
6250         int                     i_rolname;
6251         int                     i_dicttemplate;
6252         int                     i_dictinitoption;
6253
6254         /* Before 8.3, there is no built-in text search support */
6255         if (fout->remoteVersion < 80300)
6256         {
6257                 *numTSDicts = 0;
6258                 return NULL;
6259         }
6260
6261         query = createPQExpBuffer();
6262
6263         /* Make sure we are in proper schema */
6264         selectSourceSchema(fout, "pg_catalog");
6265
6266         appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6267                                           "dictnamespace, (%s dictowner) AS rolname, "
6268                                           "dicttemplate, dictinitoption "
6269                                           "FROM pg_ts_dict",
6270                                           username_subquery);
6271
6272         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6273
6274         ntups = PQntuples(res);
6275         *numTSDicts = ntups;
6276
6277         dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6278
6279         i_tableoid = PQfnumber(res, "tableoid");
6280         i_oid = PQfnumber(res, "oid");
6281         i_dictname = PQfnumber(res, "dictname");
6282         i_dictnamespace = PQfnumber(res, "dictnamespace");
6283         i_rolname = PQfnumber(res, "rolname");
6284         i_dictinitoption = PQfnumber(res, "dictinitoption");
6285         i_dicttemplate = PQfnumber(res, "dicttemplate");
6286
6287         for (i = 0; i < ntups; i++)
6288         {
6289                 dictinfo[i].dobj.objType = DO_TSDICT;
6290                 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6291                 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6292                 AssignDumpId(&dictinfo[i].dobj);
6293                 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6294                 dictinfo[i].dobj.namespace =
6295                         findNamespace(fout,
6296                                                   atooid(PQgetvalue(res, i, i_dictnamespace)),
6297                                                   dictinfo[i].dobj.catId.oid);
6298                 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6299                 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6300                 if (PQgetisnull(res, i, i_dictinitoption))
6301                         dictinfo[i].dictinitoption = NULL;
6302                 else
6303                         dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6304
6305                 /* Decide whether we want to dump it */
6306                 selectDumpableObject(&(dictinfo[i].dobj));
6307         }
6308
6309         PQclear(res);
6310
6311         destroyPQExpBuffer(query);
6312
6313         return dictinfo;
6314 }
6315
6316 /*
6317  * getTSTemplates:
6318  *        read all text search templates in the system catalogs and return them
6319  *        in the TSTemplateInfo* structure
6320  *
6321  *      numTSTemplates is set to the number of templates read in
6322  */
6323 TSTemplateInfo *
6324 getTSTemplates(Archive *fout, int *numTSTemplates)
6325 {
6326         PGresult   *res;
6327         int                     ntups;
6328         int                     i;
6329         PQExpBuffer query;
6330         TSTemplateInfo *tmplinfo;
6331         int                     i_tableoid;
6332         int                     i_oid;
6333         int                     i_tmplname;
6334         int                     i_tmplnamespace;
6335         int                     i_tmplinit;
6336         int                     i_tmpllexize;
6337
6338         /* Before 8.3, there is no built-in text search support */
6339         if (fout->remoteVersion < 80300)
6340         {
6341                 *numTSTemplates = 0;
6342                 return NULL;
6343         }
6344
6345         query = createPQExpBuffer();
6346
6347         /* Make sure we are in proper schema */
6348         selectSourceSchema(fout, "pg_catalog");
6349
6350         appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6351                                           "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6352                                           "FROM pg_ts_template");
6353
6354         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6355
6356         ntups = PQntuples(res);
6357         *numTSTemplates = ntups;
6358
6359         tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6360
6361         i_tableoid = PQfnumber(res, "tableoid");
6362         i_oid = PQfnumber(res, "oid");
6363         i_tmplname = PQfnumber(res, "tmplname");
6364         i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6365         i_tmplinit = PQfnumber(res, "tmplinit");
6366         i_tmpllexize = PQfnumber(res, "tmpllexize");
6367
6368         for (i = 0; i < ntups; i++)
6369         {
6370                 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6371                 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6372                 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6373                 AssignDumpId(&tmplinfo[i].dobj);
6374                 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6375                 tmplinfo[i].dobj.namespace =
6376                         findNamespace(fout,
6377                                                   atooid(PQgetvalue(res, i, i_tmplnamespace)),
6378                                                   tmplinfo[i].dobj.catId.oid);
6379                 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6380                 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6381
6382                 /* Decide whether we want to dump it */
6383                 selectDumpableObject(&(tmplinfo[i].dobj));
6384         }
6385
6386         PQclear(res);
6387
6388         destroyPQExpBuffer(query);
6389
6390         return tmplinfo;
6391 }
6392
6393 /*
6394  * getTSConfigurations:
6395  *        read all text search configurations in the system catalogs and return
6396  *        them in the TSConfigInfo* structure
6397  *
6398  *      numTSConfigs is set to the number of configurations read in
6399  */
6400 TSConfigInfo *
6401 getTSConfigurations(Archive *fout, int *numTSConfigs)
6402 {
6403         PGresult   *res;
6404         int                     ntups;
6405         int                     i;
6406         PQExpBuffer query;
6407         TSConfigInfo *cfginfo;
6408         int                     i_tableoid;
6409         int                     i_oid;
6410         int                     i_cfgname;
6411         int                     i_cfgnamespace;
6412         int                     i_rolname;
6413         int                     i_cfgparser;
6414
6415         /* Before 8.3, there is no built-in text search support */
6416         if (fout->remoteVersion < 80300)
6417         {
6418                 *numTSConfigs = 0;
6419                 return NULL;
6420         }
6421
6422         query = createPQExpBuffer();
6423
6424         /* Make sure we are in proper schema */
6425         selectSourceSchema(fout, "pg_catalog");
6426
6427         appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6428                                           "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6429                                           "FROM pg_ts_config",
6430                                           username_subquery);
6431
6432         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6433
6434         ntups = PQntuples(res);
6435         *numTSConfigs = ntups;
6436
6437         cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6438
6439         i_tableoid = PQfnumber(res, "tableoid");
6440         i_oid = PQfnumber(res, "oid");
6441         i_cfgname = PQfnumber(res, "cfgname");
6442         i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6443         i_rolname = PQfnumber(res, "rolname");
6444         i_cfgparser = PQfnumber(res, "cfgparser");
6445
6446         for (i = 0; i < ntups; i++)
6447         {
6448                 cfginfo[i].dobj.objType = DO_TSCONFIG;
6449                 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6450                 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6451                 AssignDumpId(&cfginfo[i].dobj);
6452                 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6453                 cfginfo[i].dobj.namespace =
6454                         findNamespace(fout,
6455                                                   atooid(PQgetvalue(res, i, i_cfgnamespace)),
6456                                                   cfginfo[i].dobj.catId.oid);
6457                 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6458                 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6459
6460                 /* Decide whether we want to dump it */
6461                 selectDumpableObject(&(cfginfo[i].dobj));
6462         }
6463
6464         PQclear(res);
6465
6466         destroyPQExpBuffer(query);
6467
6468         return cfginfo;
6469 }
6470
6471 /*
6472  * getForeignDataWrappers:
6473  *        read all foreign-data wrappers in the system catalogs and return
6474  *        them in the FdwInfo* structure
6475  *
6476  *      numForeignDataWrappers is set to the number of fdws read in
6477  */
6478 FdwInfo *
6479 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
6480 {
6481         PGresult   *res;
6482         int                     ntups;
6483         int                     i;
6484         PQExpBuffer query = createPQExpBuffer();
6485         FdwInfo    *fdwinfo;
6486         int                     i_tableoid;
6487         int                     i_oid;
6488         int                     i_fdwname;
6489         int                     i_rolname;
6490         int                     i_fdwhandler;
6491         int                     i_fdwvalidator;
6492         int                     i_fdwacl;
6493         int                     i_fdwoptions;
6494
6495         /* Before 8.4, there are no foreign-data wrappers */
6496         if (fout->remoteVersion < 80400)
6497         {
6498                 *numForeignDataWrappers = 0;
6499                 return NULL;
6500         }
6501
6502         /* Make sure we are in proper schema */
6503         selectSourceSchema(fout, "pg_catalog");
6504
6505         if (fout->remoteVersion >= 90100)
6506         {
6507                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6508                                                   "(%s fdwowner) AS rolname, "
6509                                                   "fdwhandler::pg_catalog.regproc, "
6510                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
6511                                                   "array_to_string(ARRAY("
6512                                                   "SELECT quote_ident(option_name) || ' ' || "
6513                                                   "quote_literal(option_value) "
6514                                                   "FROM pg_options_to_table(fdwoptions) "
6515                                                   "ORDER BY option_name"
6516                                                   "), E',\n    ') AS fdwoptions "
6517                                                   "FROM pg_foreign_data_wrapper",
6518                                                   username_subquery);
6519         }
6520         else
6521         {
6522                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6523                                                   "(%s fdwowner) AS rolname, "
6524                                                   "'-' AS fdwhandler, "
6525                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
6526                                                   "array_to_string(ARRAY("
6527                                                   "SELECT quote_ident(option_name) || ' ' || "
6528                                                   "quote_literal(option_value) "
6529                                                   "FROM pg_options_to_table(fdwoptions) "
6530                                                   "ORDER BY option_name"
6531                                                   "), E',\n    ') AS fdwoptions "
6532                                                   "FROM pg_foreign_data_wrapper",
6533                                                   username_subquery);
6534         }
6535
6536         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6537
6538         ntups = PQntuples(res);
6539         *numForeignDataWrappers = ntups;
6540
6541         fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6542
6543         i_tableoid = PQfnumber(res, "tableoid");
6544         i_oid = PQfnumber(res, "oid");
6545         i_fdwname = PQfnumber(res, "fdwname");
6546         i_rolname = PQfnumber(res, "rolname");
6547         i_fdwhandler = PQfnumber(res, "fdwhandler");
6548         i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6549         i_fdwacl = PQfnumber(res, "fdwacl");
6550         i_fdwoptions = PQfnumber(res, "fdwoptions");
6551
6552         for (i = 0; i < ntups; i++)
6553         {
6554                 fdwinfo[i].dobj.objType = DO_FDW;
6555                 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6556                 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6557                 AssignDumpId(&fdwinfo[i].dobj);
6558                 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6559                 fdwinfo[i].dobj.namespace = NULL;
6560                 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6561                 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6562                 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6563                 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6564                 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6565
6566                 /* Decide whether we want to dump it */
6567                 selectDumpableObject(&(fdwinfo[i].dobj));
6568         }
6569
6570         PQclear(res);
6571
6572         destroyPQExpBuffer(query);
6573
6574         return fdwinfo;
6575 }
6576
6577 /*
6578  * getForeignServers:
6579  *        read all foreign servers in the system catalogs and return
6580  *        them in the ForeignServerInfo * structure
6581  *
6582  *      numForeignServers is set to the number of servers read in
6583  */
6584 ForeignServerInfo *
6585 getForeignServers(Archive *fout, int *numForeignServers)
6586 {
6587         PGresult   *res;
6588         int                     ntups;
6589         int                     i;
6590         PQExpBuffer query = createPQExpBuffer();
6591         ForeignServerInfo *srvinfo;
6592         int                     i_tableoid;
6593         int                     i_oid;
6594         int                     i_srvname;
6595         int                     i_rolname;
6596         int                     i_srvfdw;
6597         int                     i_srvtype;
6598         int                     i_srvversion;
6599         int                     i_srvacl;
6600         int                     i_srvoptions;
6601
6602         /* Before 8.4, there are no foreign servers */
6603         if (fout->remoteVersion < 80400)
6604         {
6605                 *numForeignServers = 0;
6606                 return NULL;
6607         }
6608
6609         /* Make sure we are in proper schema */
6610         selectSourceSchema(fout,"pg_catalog");
6611
6612         appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6613                                           "(%s srvowner) AS rolname, "
6614                                           "srvfdw, srvtype, srvversion, srvacl,"
6615                                           "array_to_string(ARRAY("
6616                                           "SELECT quote_ident(option_name) || ' ' || "
6617                                           "quote_literal(option_value) "
6618                                           "FROM pg_options_to_table(srvoptions) "
6619                                           "ORDER BY option_name"
6620                                           "), E',\n    ') AS srvoptions "
6621                                           "FROM pg_foreign_server",
6622                                           username_subquery);
6623
6624         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6625
6626         ntups = PQntuples(res);
6627         *numForeignServers = ntups;
6628
6629         srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
6630
6631         i_tableoid = PQfnumber(res, "tableoid");
6632         i_oid = PQfnumber(res, "oid");
6633         i_srvname = PQfnumber(res, "srvname");
6634         i_rolname = PQfnumber(res, "rolname");
6635         i_srvfdw = PQfnumber(res, "srvfdw");
6636         i_srvtype = PQfnumber(res, "srvtype");
6637         i_srvversion = PQfnumber(res, "srvversion");
6638         i_srvacl = PQfnumber(res, "srvacl");
6639         i_srvoptions = PQfnumber(res, "srvoptions");
6640
6641         for (i = 0; i < ntups; i++)
6642         {
6643                 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
6644                 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6645                 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6646                 AssignDumpId(&srvinfo[i].dobj);
6647                 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
6648                 srvinfo[i].dobj.namespace = NULL;
6649                 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6650                 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
6651                 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
6652                 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
6653                 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
6654                 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
6655
6656                 /* Decide whether we want to dump it */
6657                 selectDumpableObject(&(srvinfo[i].dobj));
6658         }
6659
6660         PQclear(res);
6661
6662         destroyPQExpBuffer(query);
6663
6664         return srvinfo;
6665 }
6666
6667 /*
6668  * getDefaultACLs:
6669  *        read all default ACL information in the system catalogs and return
6670  *        them in the DefaultACLInfo structure
6671  *
6672  *      numDefaultACLs is set to the number of ACLs read in
6673  */
6674 DefaultACLInfo *
6675 getDefaultACLs(Archive *fout, int *numDefaultACLs)
6676 {
6677         DefaultACLInfo *daclinfo;
6678         PQExpBuffer query;
6679         PGresult   *res;
6680         int                     i_oid;
6681         int                     i_tableoid;
6682         int                     i_defaclrole;
6683         int                     i_defaclnamespace;
6684         int                     i_defaclobjtype;
6685         int                     i_defaclacl;
6686         int                     i,
6687                                 ntups;
6688
6689         if (fout->remoteVersion < 90000)
6690         {
6691                 *numDefaultACLs = 0;
6692                 return NULL;
6693         }
6694
6695         query = createPQExpBuffer();
6696
6697         /* Make sure we are in proper schema */
6698         selectSourceSchema(fout, "pg_catalog");
6699
6700         appendPQExpBuffer(query, "SELECT oid, tableoid, "
6701                                           "(%s defaclrole) AS defaclrole, "
6702                                           "defaclnamespace, "
6703                                           "defaclobjtype, "
6704                                           "defaclacl "
6705                                           "FROM pg_default_acl",
6706                                           username_subquery);
6707
6708         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6709
6710         ntups = PQntuples(res);
6711         *numDefaultACLs = ntups;
6712
6713         daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
6714
6715         i_oid = PQfnumber(res, "oid");
6716         i_tableoid = PQfnumber(res, "tableoid");
6717         i_defaclrole = PQfnumber(res, "defaclrole");
6718         i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6719         i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6720         i_defaclacl = PQfnumber(res, "defaclacl");
6721
6722         for (i = 0; i < ntups; i++)
6723         {
6724                 Oid                     nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6725
6726                 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6727                 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6728                 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6729                 AssignDumpId(&daclinfo[i].dobj);
6730                 /* cheesy ... is it worth coming up with a better object name? */
6731                 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
6732
6733                 if (nspid != InvalidOid)
6734                         daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
6735                                                                                                  daclinfo[i].dobj.catId.oid);
6736                 else
6737                         daclinfo[i].dobj.namespace = NULL;
6738
6739                 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
6740                 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6741                 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
6742
6743                 /* Decide whether we want to dump it */
6744                 selectDumpableDefaultACL(&(daclinfo[i]));
6745         }
6746
6747         PQclear(res);
6748
6749         destroyPQExpBuffer(query);
6750
6751         return daclinfo;
6752 }
6753
6754 /*
6755  * dumpComment --
6756  *
6757  * This routine is used to dump any comments associated with the
6758  * object handed to this routine. The routine takes a constant character
6759  * string for the target part of the comment-creation command, plus
6760  * the namespace and owner of the object (for labeling the ArchiveEntry),
6761  * plus catalog ID and subid which are the lookup key for pg_description,
6762  * plus the dump ID for the object (for setting a dependency).
6763  * If a matching pg_description entry is found, it is dumped.
6764  *
6765  * Note: although this routine takes a dumpId for dependency purposes,
6766  * that purpose is just to mark the dependency in the emitted dump file
6767  * for possible future use by pg_restore.  We do NOT use it for determining
6768  * ordering of the comment in the dump file, because this routine is called
6769  * after dependency sorting occurs.  This routine should be called just after
6770  * calling ArchiveEntry() for the specified object.
6771  */
6772 static void
6773 dumpComment(Archive *fout, const char *target,
6774                         const char *namespace, const char *owner,
6775                         CatalogId catalogId, int subid, DumpId dumpId)
6776 {
6777         CommentItem *comments;
6778         int                     ncomments;
6779
6780         /* Comments are schema not data ... except blob comments are data */
6781         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6782         {
6783                 if (dataOnly)
6784                         return;
6785         }
6786         else
6787         {
6788                 if (schemaOnly)
6789                         return;
6790         }
6791
6792         /* Search for comments associated with catalogId, using table */
6793         ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6794                                                          &comments);
6795
6796         /* Is there one matching the subid? */
6797         while (ncomments > 0)
6798         {
6799                 if (comments->objsubid == subid)
6800                         break;
6801                 comments++;
6802                 ncomments--;
6803         }
6804
6805         /* If a comment exists, build COMMENT ON statement */
6806         if (ncomments > 0)
6807         {
6808                 PQExpBuffer query = createPQExpBuffer();
6809
6810                 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
6811                 appendStringLiteralAH(query, comments->descr, fout);
6812                 appendPQExpBuffer(query, ";\n");
6813
6814                 /*
6815                  * We mark comments as SECTION_NONE because they really belong in the
6816                  * same section as their parent, whether that is pre-data or
6817                  * post-data.
6818                  */
6819                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6820                                          target, namespace, NULL, owner,
6821                                          false, "COMMENT", SECTION_NONE,
6822                                          query->data, "", NULL,
6823                                          &(dumpId), 1,
6824                                          NULL, NULL);
6825
6826                 destroyPQExpBuffer(query);
6827         }
6828 }
6829
6830 /*
6831  * dumpTableComment --
6832  *
6833  * As above, but dump comments for both the specified table (or view)
6834  * and its columns.
6835  */
6836 static void
6837 dumpTableComment(Archive *fout, TableInfo *tbinfo,
6838                                  const char *reltypename)
6839 {
6840         CommentItem *comments;
6841         int                     ncomments;
6842         PQExpBuffer query;
6843         PQExpBuffer target;
6844
6845         /* Comments are SCHEMA not data */
6846         if (dataOnly)
6847                 return;
6848
6849         /* Search for comments associated with relation, using table */
6850         ncomments = findComments(fout,
6851                                                          tbinfo->dobj.catId.tableoid,
6852                                                          tbinfo->dobj.catId.oid,
6853                                                          &comments);
6854
6855         /* If comments exist, build COMMENT ON statements */
6856         if (ncomments <= 0)
6857                 return;
6858
6859         query = createPQExpBuffer();
6860         target = createPQExpBuffer();
6861
6862         while (ncomments > 0)
6863         {
6864                 const char *descr = comments->descr;
6865                 int                     objsubid = comments->objsubid;
6866
6867                 if (objsubid == 0)
6868                 {
6869                         resetPQExpBuffer(target);
6870                         appendPQExpBuffer(target, "%s %s", reltypename,
6871                                                           fmtId(tbinfo->dobj.name));
6872
6873                         resetPQExpBuffer(query);
6874                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6875                         appendStringLiteralAH(query, descr, fout);
6876                         appendPQExpBuffer(query, ";\n");
6877
6878                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
6879                                                  target->data,
6880                                                  tbinfo->dobj.namespace->dobj.name,
6881                                                  NULL, tbinfo->rolname,
6882                                                  false, "COMMENT", SECTION_NONE,
6883                                                  query->data, "", NULL,
6884                                                  &(tbinfo->dobj.dumpId), 1,
6885                                                  NULL, NULL);
6886                 }
6887                 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
6888                 {
6889                         resetPQExpBuffer(target);
6890                         appendPQExpBuffer(target, "COLUMN %s.",
6891                                                           fmtId(tbinfo->dobj.name));
6892                         appendPQExpBuffer(target, "%s",
6893                                                           fmtId(tbinfo->attnames[objsubid - 1]));
6894
6895                         resetPQExpBuffer(query);
6896                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6897                         appendStringLiteralAH(query, descr, fout);
6898                         appendPQExpBuffer(query, ";\n");
6899
6900                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
6901                                                  target->data,
6902                                                  tbinfo->dobj.namespace->dobj.name,
6903                                                  NULL, tbinfo->rolname,
6904                                                  false, "COMMENT", SECTION_NONE,
6905                                                  query->data, "", NULL,
6906                                                  &(tbinfo->dobj.dumpId), 1,
6907                                                  NULL, NULL);
6908                 }
6909
6910                 comments++;
6911                 ncomments--;
6912         }
6913
6914         destroyPQExpBuffer(query);
6915         destroyPQExpBuffer(target);
6916 }
6917
6918 /*
6919  * findComments --
6920  *
6921  * Find the comment(s), if any, associated with the given object.  All the
6922  * objsubid values associated with the given classoid/objoid are found with
6923  * one search.
6924  */
6925 static int
6926 findComments(Archive *fout, Oid classoid, Oid objoid,
6927                          CommentItem **items)
6928 {
6929         /* static storage for table of comments */
6930         static CommentItem *comments = NULL;
6931         static int      ncomments = -1;
6932
6933         CommentItem *middle = NULL;
6934         CommentItem *low;
6935         CommentItem *high;
6936         int                     nmatch;
6937
6938         /* Get comments if we didn't already */
6939         if (ncomments < 0)
6940                 ncomments = collectComments(fout, &comments);
6941
6942         /*
6943          * Pre-7.2, pg_description does not contain classoid, so collectComments
6944          * just stores a zero.  If there's a collision on object OID, well, you
6945          * get duplicate comments.
6946          */
6947         if (fout->remoteVersion < 70200)
6948                 classoid = 0;
6949
6950         /*
6951          * Do binary search to find some item matching the object.
6952          */
6953         low = &comments[0];
6954         high = &comments[ncomments - 1];
6955         while (low <= high)
6956         {
6957                 middle = low + (high - low) / 2;
6958
6959                 if (classoid < middle->classoid)
6960                         high = middle - 1;
6961                 else if (classoid > middle->classoid)
6962                         low = middle + 1;
6963                 else if (objoid < middle->objoid)
6964                         high = middle - 1;
6965                 else if (objoid > middle->objoid)
6966                         low = middle + 1;
6967                 else
6968                         break;                          /* found a match */
6969         }
6970
6971         if (low > high)                         /* no matches */
6972         {
6973                 *items = NULL;
6974                 return 0;
6975         }
6976
6977         /*
6978          * Now determine how many items match the object.  The search loop
6979          * invariant still holds: only items between low and high inclusive could
6980          * match.
6981          */
6982         nmatch = 1;
6983         while (middle > low)
6984         {
6985                 if (classoid != middle[-1].classoid ||
6986                         objoid != middle[-1].objoid)
6987                         break;
6988                 middle--;
6989                 nmatch++;
6990         }
6991
6992         *items = middle;
6993
6994         middle += nmatch;
6995         while (middle <= high)
6996         {
6997                 if (classoid != middle->classoid ||
6998                         objoid != middle->objoid)
6999                         break;
7000                 middle++;
7001                 nmatch++;
7002         }
7003
7004         return nmatch;
7005 }
7006
7007 /*
7008  * collectComments --
7009  *
7010  * Construct a table of all comments available for database objects.
7011  * We used to do per-object queries for the comments, but it's much faster
7012  * to pull them all over at once, and on most databases the memory cost
7013  * isn't high.
7014  *
7015  * The table is sorted by classoid/objid/objsubid for speed in lookup.
7016  */
7017 static int
7018 collectComments(Archive *fout, CommentItem **items)
7019 {
7020         PGresult   *res;
7021         PQExpBuffer query;
7022         int                     i_description;
7023         int                     i_classoid;
7024         int                     i_objoid;
7025         int                     i_objsubid;
7026         int                     ntups;
7027         int                     i;
7028         CommentItem *comments;
7029
7030         /*
7031          * Note we do NOT change source schema here; preserve the caller's
7032          * setting, instead.
7033          */
7034
7035         query = createPQExpBuffer();
7036
7037         if (fout->remoteVersion >= 70300)
7038         {
7039                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7040                                                   "FROM pg_catalog.pg_description "
7041                                                   "ORDER BY classoid, objoid, objsubid");
7042         }
7043         else if (fout->remoteVersion >= 70200)
7044         {
7045                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7046                                                   "FROM pg_description "
7047                                                   "ORDER BY classoid, objoid, objsubid");
7048         }
7049         else
7050         {
7051                 /* Note: this will fail to find attribute comments in pre-7.2... */
7052                 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7053                                                   "FROM pg_description "
7054                                                   "ORDER BY objoid");
7055         }
7056
7057         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7058
7059         /* Construct lookup table containing OIDs in numeric form */
7060
7061         i_description = PQfnumber(res, "description");
7062         i_classoid = PQfnumber(res, "classoid");
7063         i_objoid = PQfnumber(res, "objoid");
7064         i_objsubid = PQfnumber(res, "objsubid");
7065
7066         ntups = PQntuples(res);
7067
7068         comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7069
7070         for (i = 0; i < ntups; i++)
7071         {
7072                 comments[i].descr = PQgetvalue(res, i, i_description);
7073                 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7074                 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7075                 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7076         }
7077
7078         /* Do NOT free the PGresult since we are keeping pointers into it */
7079         destroyPQExpBuffer(query);
7080
7081         *items = comments;
7082         return ntups;
7083 }
7084
7085 /*
7086  * dumpDumpableObject
7087  *
7088  * This routine and its subsidiaries are responsible for creating
7089  * ArchiveEntries (TOC objects) for each object to be dumped.
7090  */
7091 static void
7092 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7093 {
7094
7095         bool skip = false;
7096
7097         switch (dobj->objType)
7098         {
7099                 case DO_INDEX:
7100                 case DO_TRIGGER:
7101                 case DO_CONSTRAINT:
7102                 case DO_FK_CONSTRAINT:
7103                 case DO_RULE:
7104                         skip = !(dumpSections & DUMP_POST_DATA);
7105                         break;
7106                 case DO_TABLE_DATA:
7107                         skip = !(dumpSections & DUMP_DATA);
7108                         break;
7109                 default:
7110                         skip = !(dumpSections & DUMP_PRE_DATA);
7111         }
7112
7113         if (skip)
7114                 return;
7115
7116         switch (dobj->objType)
7117         {
7118                 case DO_NAMESPACE:
7119                         dumpNamespace(fout, (NamespaceInfo *) dobj);
7120                         break;
7121                 case DO_EXTENSION:
7122                         dumpExtension(fout, (ExtensionInfo *) dobj);
7123                         break;
7124                 case DO_TYPE:
7125                         dumpType(fout, (TypeInfo *) dobj);
7126                         break;
7127                 case DO_SHELL_TYPE:
7128                         dumpShellType(fout, (ShellTypeInfo *) dobj);
7129                         break;
7130                 case DO_FUNC:
7131                         dumpFunc(fout, (FuncInfo *) dobj);
7132                         break;
7133                 case DO_AGG:
7134                         dumpAgg(fout, (AggInfo *) dobj);
7135                         break;
7136                 case DO_OPERATOR:
7137                         dumpOpr(fout, (OprInfo *) dobj);
7138                         break;
7139                 case DO_OPCLASS:
7140                         dumpOpclass(fout, (OpclassInfo *) dobj);
7141                         break;
7142                 case DO_OPFAMILY:
7143                         dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7144                         break;
7145                 case DO_COLLATION:
7146                         dumpCollation(fout, (CollInfo *) dobj);
7147                         break;
7148                 case DO_CONVERSION:
7149                         dumpConversion(fout, (ConvInfo *) dobj);
7150                         break;
7151                 case DO_TABLE:
7152                         dumpTable(fout, (TableInfo *) dobj);
7153                         break;
7154                 case DO_ATTRDEF:
7155                         dumpAttrDef(fout, (AttrDefInfo *) dobj);
7156                         break;
7157                 case DO_INDEX:
7158                         dumpIndex(fout, (IndxInfo *) dobj);
7159                         break;
7160                 case DO_RULE:
7161                         dumpRule(fout, (RuleInfo *) dobj);
7162                         break;
7163                 case DO_TRIGGER:
7164                         dumpTrigger(fout, (TriggerInfo *) dobj);
7165                         break;
7166                 case DO_CONSTRAINT:
7167                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7168                         break;
7169                 case DO_FK_CONSTRAINT:
7170                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7171                         break;
7172                 case DO_PROCLANG:
7173                         dumpProcLang(fout, (ProcLangInfo *) dobj);
7174                         break;
7175                 case DO_CAST:
7176                         dumpCast(fout, (CastInfo *) dobj);
7177                         break;
7178                 case DO_TABLE_DATA:
7179                         dumpTableData(fout, (TableDataInfo *) dobj);
7180                         break;
7181                 case DO_DUMMY_TYPE:
7182                         /* table rowtypes and array types are never dumped separately */
7183                         break;
7184                 case DO_TSPARSER:
7185                         dumpTSParser(fout, (TSParserInfo *) dobj);
7186                         break;
7187                 case DO_TSDICT:
7188                         dumpTSDictionary(fout, (TSDictInfo *) dobj);
7189                         break;
7190                 case DO_TSTEMPLATE:
7191                         dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7192                         break;
7193                 case DO_TSCONFIG:
7194                         dumpTSConfig(fout, (TSConfigInfo *) dobj);
7195                         break;
7196                 case DO_FDW:
7197                         dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7198                         break;
7199                 case DO_FOREIGN_SERVER:
7200                         dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7201                         break;
7202                 case DO_DEFAULT_ACL:
7203                         dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7204                         break;
7205                 case DO_BLOB:
7206                         dumpBlob(fout, (BlobInfo *) dobj);
7207                         break;
7208                 case DO_BLOB_DATA:
7209                         ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7210                                                  dobj->name, NULL, NULL, "",
7211                                                  false, "BLOBS", SECTION_DATA,
7212                                                  "", "", NULL,
7213                                                  dobj->dependencies, dobj->nDeps,
7214                                                  dumpBlobs, NULL);
7215                         break;
7216         }
7217 }
7218
7219 /*
7220  * dumpNamespace
7221  *        writes out to fout the queries to recreate a user-defined namespace
7222  */
7223 static void
7224 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7225 {
7226         PQExpBuffer q;
7227         PQExpBuffer delq;
7228         PQExpBuffer labelq;
7229         char       *qnspname;
7230
7231         /* Skip if not to be dumped */
7232         if (!nspinfo->dobj.dump || dataOnly)
7233                 return;
7234
7235         /* don't dump dummy namespace from pre-7.3 source */
7236         if (strlen(nspinfo->dobj.name) == 0)
7237                 return;
7238
7239         q = createPQExpBuffer();
7240         delq = createPQExpBuffer();
7241         labelq = createPQExpBuffer();
7242
7243         qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7244
7245         appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7246
7247         appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7248
7249         appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7250
7251         if (binary_upgrade)
7252                 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7253
7254         ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7255                                  nspinfo->dobj.name,
7256                                  NULL, NULL,
7257                                  nspinfo->rolname,
7258                                  false, "SCHEMA", SECTION_PRE_DATA,
7259                                  q->data, delq->data, NULL,
7260                                  nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
7261                                  NULL, NULL);
7262
7263         /* Dump Schema Comments and Security Labels */
7264         dumpComment(fout, labelq->data,
7265                                 NULL, nspinfo->rolname,
7266                                 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7267         dumpSecLabel(fout, labelq->data,
7268                                  NULL, nspinfo->rolname,
7269                                  nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7270
7271         dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7272                         qnspname, NULL, nspinfo->dobj.name, NULL,
7273                         nspinfo->rolname, nspinfo->nspacl);
7274
7275         free(qnspname);
7276
7277         destroyPQExpBuffer(q);
7278         destroyPQExpBuffer(delq);
7279         destroyPQExpBuffer(labelq);
7280 }
7281
7282 /*
7283  * dumpExtension
7284  *        writes out to fout the queries to recreate an extension
7285  */
7286 static void
7287 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7288 {
7289         PQExpBuffer q;
7290         PQExpBuffer delq;
7291         PQExpBuffer labelq;
7292         char       *qextname;
7293
7294         /* Skip if not to be dumped */
7295         if (!extinfo->dobj.dump || dataOnly)
7296                 return;
7297
7298         q = createPQExpBuffer();
7299         delq = createPQExpBuffer();
7300         labelq = createPQExpBuffer();
7301
7302         qextname = pg_strdup(fmtId(extinfo->dobj.name));
7303
7304         appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7305
7306         if (!binary_upgrade)
7307         {
7308                 /*
7309                  * In a regular dump, we use IF NOT EXISTS so that there isn't a
7310                  * problem if the extension already exists in the target database;
7311                  * this is essential for installed-by-default extensions such as
7312                  * plpgsql.
7313                  *
7314                  * In binary-upgrade mode, that doesn't work well, so instead we skip
7315                  * built-in extensions based on their OIDs; see
7316                  * selectDumpableExtension.
7317                  */
7318                 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7319                                                   qextname, fmtId(extinfo->namespace));
7320         }
7321         else
7322         {
7323                 int                     i;
7324                 int                     n;
7325
7326                 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7327                 appendPQExpBuffer(q,
7328                                                   "SELECT binary_upgrade.create_empty_extension(");
7329                 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7330                 appendPQExpBuffer(q, ", ");
7331                 appendStringLiteralAH(q, extinfo->namespace, fout);
7332                 appendPQExpBuffer(q, ", ");
7333                 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7334                 appendStringLiteralAH(q, extinfo->extversion, fout);
7335                 appendPQExpBuffer(q, ", ");
7336
7337                 /*
7338                  * Note that we're pushing extconfig (an OID array) back into
7339                  * pg_extension exactly as-is.  This is OK because pg_class OIDs are
7340                  * preserved in binary upgrade.
7341                  */
7342                 if (strlen(extinfo->extconfig) > 2)
7343                         appendStringLiteralAH(q, extinfo->extconfig, fout);
7344                 else
7345                         appendPQExpBuffer(q, "NULL");
7346                 appendPQExpBuffer(q, ", ");
7347                 if (strlen(extinfo->extcondition) > 2)
7348                         appendStringLiteralAH(q, extinfo->extcondition, fout);
7349                 else
7350                         appendPQExpBuffer(q, "NULL");
7351                 appendPQExpBuffer(q, ", ");
7352                 appendPQExpBuffer(q, "ARRAY[");
7353                 n = 0;
7354                 for (i = 0; i < extinfo->dobj.nDeps; i++)
7355                 {
7356                         DumpableObject *extobj;
7357
7358                         extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7359                         if (extobj && extobj->objType == DO_EXTENSION)
7360                         {
7361                                 if (n++ > 0)
7362                                         appendPQExpBuffer(q, ",");
7363                                 appendStringLiteralAH(q, extobj->name, fout);
7364                         }
7365                 }
7366                 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7367                 appendPQExpBuffer(q, ");\n");
7368         }
7369
7370         appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7371
7372         ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7373                                  extinfo->dobj.name,
7374                                  NULL, NULL,
7375                                  "",
7376                                  false, "EXTENSION", SECTION_PRE_DATA,
7377                                  q->data, delq->data, NULL,
7378                                  extinfo->dobj.dependencies, extinfo->dobj.nDeps,
7379                                  NULL, NULL);
7380
7381         /* Dump Extension Comments and Security Labels */
7382         dumpComment(fout, labelq->data,
7383                                 NULL, "",
7384                                 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7385         dumpSecLabel(fout, labelq->data,
7386                                  NULL, "",
7387                                  extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7388
7389         free(qextname);
7390
7391         destroyPQExpBuffer(q);
7392         destroyPQExpBuffer(delq);
7393         destroyPQExpBuffer(labelq);
7394 }
7395
7396 /*
7397  * dumpType
7398  *        writes out to fout the queries to recreate a user-defined type
7399  */
7400 static void
7401 dumpType(Archive *fout, TypeInfo *tyinfo)
7402 {
7403         /* Skip if not to be dumped */
7404         if (!tyinfo->dobj.dump || dataOnly)
7405                 return;
7406
7407         /* Dump out in proper style */
7408         if (tyinfo->typtype == TYPTYPE_BASE)
7409                 dumpBaseType(fout, tyinfo);
7410         else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7411                 dumpDomain(fout, tyinfo);
7412         else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7413                 dumpCompositeType(fout, tyinfo);
7414         else if (tyinfo->typtype == TYPTYPE_ENUM)
7415                 dumpEnumType(fout, tyinfo);
7416         else if (tyinfo->typtype == TYPTYPE_RANGE)
7417                 dumpRangeType(fout, tyinfo);
7418         else
7419                 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7420                                   tyinfo->dobj.name);
7421 }
7422
7423 /*
7424  * dumpEnumType
7425  *        writes out to fout the queries to recreate a user-defined enum type
7426  */
7427 static void
7428 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7429 {
7430         PQExpBuffer q = createPQExpBuffer();
7431         PQExpBuffer delq = createPQExpBuffer();
7432         PQExpBuffer labelq = createPQExpBuffer();
7433         PQExpBuffer query = createPQExpBuffer();
7434         PGresult   *res;
7435         int                     num,
7436                                 i;
7437         Oid                     enum_oid;
7438         char       *label;
7439
7440         /* Set proper schema search path */
7441         selectSourceSchema(fout, "pg_catalog");
7442
7443         if (fout->remoteVersion >= 90100)
7444                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7445                                                   "FROM pg_catalog.pg_enum "
7446                                                   "WHERE enumtypid = '%u'"
7447                                                   "ORDER BY enumsortorder",
7448                                                   tyinfo->dobj.catId.oid);
7449         else
7450                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7451                                                   "FROM pg_catalog.pg_enum "
7452                                                   "WHERE enumtypid = '%u'"
7453                                                   "ORDER BY oid",
7454                                                   tyinfo->dobj.catId.oid);
7455
7456         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7457
7458         num = PQntuples(res);
7459
7460         /*
7461          * DROP must be fully qualified in case same name appears in pg_catalog.
7462          * CASCADE shouldn't be required here as for normal types since the I/O
7463          * functions are generic and do not get dropped.
7464          */
7465         appendPQExpBuffer(delq, "DROP TYPE %s.",
7466                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7467         appendPQExpBuffer(delq, "%s;\n",
7468                                           fmtId(tyinfo->dobj.name));
7469
7470         if (binary_upgrade)
7471                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7472                                                                                                  tyinfo->dobj.catId.oid);
7473
7474         appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7475                                           fmtId(tyinfo->dobj.name));
7476
7477         if (!binary_upgrade)
7478         {
7479                 /* Labels with server-assigned oids */
7480                 for (i = 0; i < num; i++)
7481                 {
7482                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7483                         if (i > 0)
7484                                 appendPQExpBuffer(q, ",");
7485                         appendPQExpBuffer(q, "\n    ");
7486                         appendStringLiteralAH(q, label, fout);
7487                 }
7488         }
7489
7490         appendPQExpBuffer(q, "\n);\n");
7491
7492         if (binary_upgrade)
7493         {
7494                 /* Labels with dump-assigned (preserved) oids */
7495                 for (i = 0; i < num; i++)
7496                 {
7497                         enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7498                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7499
7500                         if (i == 0)
7501                                 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7502                         appendPQExpBuffer(q,
7503                                                           "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7504                                                           enum_oid);
7505                         appendPQExpBuffer(q, "ALTER TYPE %s.",
7506                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7507                         appendPQExpBuffer(q, "%s ADD VALUE ",
7508                                                           fmtId(tyinfo->dobj.name));
7509                         appendStringLiteralAH(q, label, fout);
7510                         appendPQExpBuffer(q, ";\n\n");
7511                 }
7512         }
7513
7514         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7515
7516         if (binary_upgrade)
7517                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7518
7519         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7520                                  tyinfo->dobj.name,
7521                                  tyinfo->dobj.namespace->dobj.name,
7522                                  NULL,
7523                                  tyinfo->rolname, false,
7524                                  "TYPE", SECTION_PRE_DATA,
7525                                  q->data, delq->data, NULL,
7526                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7527                                  NULL, NULL);
7528
7529         /* Dump Type Comments and Security Labels */
7530         dumpComment(fout, labelq->data,
7531                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7532                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7533         dumpSecLabel(fout, labelq->data,
7534                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7535                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7536
7537         PQclear(res);
7538         destroyPQExpBuffer(q);
7539         destroyPQExpBuffer(delq);
7540         destroyPQExpBuffer(labelq);
7541         destroyPQExpBuffer(query);
7542 }
7543
7544 /*
7545  * dumpRangeType
7546  *        writes out to fout the queries to recreate a user-defined range type
7547  */
7548 static void
7549 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7550 {
7551         PQExpBuffer q = createPQExpBuffer();
7552         PQExpBuffer delq = createPQExpBuffer();
7553         PQExpBuffer labelq = createPQExpBuffer();
7554         PQExpBuffer query = createPQExpBuffer();
7555         PGresult   *res;
7556         Oid                     collationOid;
7557         char       *procname;
7558
7559         /*
7560          * select appropriate schema to ensure names in CREATE are properly
7561          * qualified
7562          */
7563         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7564
7565         appendPQExpBuffer(query,
7566                                           "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7567                                           "opc.opcname AS opcname, "
7568                                           "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7569                                           "  WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7570                                           "opc.opcdefault, "
7571                                           "CASE WHEN rngcollation = st.typcollation THEN 0 "
7572                                           "     ELSE rngcollation END AS collation, "
7573                                           "rngcanonical, rngsubdiff "
7574                                           "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7575                                           "     pg_catalog.pg_opclass opc "
7576                                           "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7577                                           "rngtypid = '%u'",
7578                                           tyinfo->dobj.catId.oid);
7579
7580         res = ExecuteSqlQueryForSingleRow(fout, query->data);
7581
7582         /*
7583          * DROP must be fully qualified in case same name appears in pg_catalog.
7584          * CASCADE shouldn't be required here as for normal types since the I/O
7585          * functions are generic and do not get dropped.
7586          */
7587         appendPQExpBuffer(delq, "DROP TYPE %s.",
7588                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7589         appendPQExpBuffer(delq, "%s;\n",
7590                                           fmtId(tyinfo->dobj.name));
7591
7592         if (binary_upgrade)
7593                 binary_upgrade_set_type_oids_by_type_oid(fout,
7594                                                                                                  q, tyinfo->dobj.catId.oid);
7595
7596         appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7597                                           fmtId(tyinfo->dobj.name));
7598
7599         appendPQExpBuffer(q, "\n    subtype = %s",
7600                                           PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7601
7602         /* print subtype_opclass only if not default for subtype */
7603         if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7604         {
7605                 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7606                 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7607
7608                 /* always schema-qualify, don't try to be smart */
7609                 appendPQExpBuffer(q, ",\n    subtype_opclass = %s.",
7610                                                   fmtId(nspname));
7611                 appendPQExpBuffer(q, "%s", fmtId(opcname));
7612         }
7613
7614         collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
7615         if (OidIsValid(collationOid))
7616         {
7617                 CollInfo   *coll = findCollationByOid(collationOid);
7618
7619                 if (coll)
7620                 {
7621                         /* always schema-qualify, don't try to be smart */
7622                         appendPQExpBuffer(q, ",\n    collation = %s.",
7623                                                           fmtId(coll->dobj.namespace->dobj.name));
7624                         appendPQExpBuffer(q, "%s",
7625                                                           fmtId(coll->dobj.name));
7626                 }
7627         }
7628
7629         procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
7630         if (strcmp(procname, "-") != 0)
7631                 appendPQExpBuffer(q, ",\n    canonical = %s", procname);
7632
7633         procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
7634         if (strcmp(procname, "-") != 0)
7635                 appendPQExpBuffer(q, ",\n    subtype_diff = %s", procname);
7636
7637         appendPQExpBuffer(q, "\n);\n");
7638
7639         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7640
7641         if (binary_upgrade)
7642                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7643
7644         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7645                                  tyinfo->dobj.name,
7646                                  tyinfo->dobj.namespace->dobj.name,
7647                                  NULL,
7648                                  tyinfo->rolname, false,
7649                                  "TYPE", SECTION_PRE_DATA,
7650                                  q->data, delq->data, NULL,
7651                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7652                                  NULL, NULL);
7653
7654         /* Dump Type Comments and Security Labels */
7655         dumpComment(fout, labelq->data,
7656                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7657                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7658         dumpSecLabel(fout, labelq->data,
7659                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7660                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7661
7662         PQclear(res);
7663         destroyPQExpBuffer(q);
7664         destroyPQExpBuffer(delq);
7665         destroyPQExpBuffer(labelq);
7666         destroyPQExpBuffer(query);
7667 }
7668
7669 /*
7670  * dumpBaseType
7671  *        writes out to fout the queries to recreate a user-defined base type
7672  */
7673 static void
7674 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
7675 {
7676         PQExpBuffer q = createPQExpBuffer();
7677         PQExpBuffer delq = createPQExpBuffer();
7678         PQExpBuffer labelq = createPQExpBuffer();
7679         PQExpBuffer query = createPQExpBuffer();
7680         PGresult   *res;
7681         char       *typlen;
7682         char       *typinput;
7683         char       *typoutput;
7684         char       *typreceive;
7685         char       *typsend;
7686         char       *typmodin;
7687         char       *typmodout;
7688         char       *typanalyze;
7689         Oid                     typreceiveoid;
7690         Oid                     typsendoid;
7691         Oid                     typmodinoid;
7692         Oid                     typmodoutoid;
7693         Oid                     typanalyzeoid;
7694         char       *typcategory;
7695         char       *typispreferred;
7696         char       *typdelim;
7697         char       *typbyval;
7698         char       *typalign;
7699         char       *typstorage;
7700         char       *typcollatable;
7701         char       *typdefault;
7702         bool            typdefault_is_literal = false;
7703
7704         /* Set proper schema search path so regproc references list correctly */
7705         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7706
7707         /* Fetch type-specific details */
7708         if (fout->remoteVersion >= 90100)
7709         {
7710                 appendPQExpBuffer(query, "SELECT typlen, "
7711                                                   "typinput, typoutput, typreceive, typsend, "
7712                                                   "typmodin, typmodout, typanalyze, "
7713                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7714                                                   "typsend::pg_catalog.oid AS typsendoid, "
7715                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7716                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7717                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7718                                                   "typcategory, typispreferred, "
7719                                                   "typdelim, typbyval, typalign, typstorage, "
7720                                                   "(typcollation <> 0) AS typcollatable, "
7721                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7722                                                   "FROM pg_catalog.pg_type "
7723                                                   "WHERE oid = '%u'::pg_catalog.oid",
7724                                                   tyinfo->dobj.catId.oid);
7725         }
7726         else if (fout->remoteVersion >= 80400)
7727         {
7728                 appendPQExpBuffer(query, "SELECT typlen, "
7729                                                   "typinput, typoutput, typreceive, typsend, "
7730                                                   "typmodin, typmodout, typanalyze, "
7731                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7732                                                   "typsend::pg_catalog.oid AS typsendoid, "
7733                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7734                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7735                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7736                                                   "typcategory, typispreferred, "
7737                                                   "typdelim, typbyval, typalign, typstorage, "
7738                                                   "false AS typcollatable, "
7739                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7740                                                   "FROM pg_catalog.pg_type "
7741                                                   "WHERE oid = '%u'::pg_catalog.oid",
7742                                                   tyinfo->dobj.catId.oid);
7743         }
7744         else if (fout->remoteVersion >= 80300)
7745         {
7746                 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
7747                 appendPQExpBuffer(query, "SELECT typlen, "
7748                                                   "typinput, typoutput, typreceive, typsend, "
7749                                                   "typmodin, typmodout, typanalyze, "
7750                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7751                                                   "typsend::pg_catalog.oid AS typsendoid, "
7752                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7753                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7754                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7755                                                   "'U' AS typcategory, false AS typispreferred, "
7756                                                   "typdelim, typbyval, typalign, typstorage, "
7757                                                   "false AS typcollatable, "
7758                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7759                                                   "FROM pg_catalog.pg_type "
7760                                                   "WHERE oid = '%u'::pg_catalog.oid",
7761                                                   tyinfo->dobj.catId.oid);
7762         }
7763         else if (fout->remoteVersion >= 80000)
7764         {
7765                 appendPQExpBuffer(query, "SELECT typlen, "
7766                                                   "typinput, typoutput, typreceive, typsend, "
7767                                                   "'-' AS typmodin, '-' AS typmodout, "
7768                                                   "typanalyze, "
7769                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7770                                                   "typsend::pg_catalog.oid AS typsendoid, "
7771                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7772                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7773                                                   "'U' AS typcategory, false AS typispreferred, "
7774                                                   "typdelim, typbyval, typalign, typstorage, "
7775                                                   "false AS typcollatable, "
7776                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7777                                                   "FROM pg_catalog.pg_type "
7778                                                   "WHERE oid = '%u'::pg_catalog.oid",
7779                                                   tyinfo->dobj.catId.oid);
7780         }
7781         else if (fout->remoteVersion >= 70400)
7782         {
7783                 appendPQExpBuffer(query, "SELECT typlen, "
7784                                                   "typinput, typoutput, typreceive, typsend, "
7785                                                   "'-' AS typmodin, '-' AS typmodout, "
7786                                                   "'-' AS typanalyze, "
7787                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7788                                                   "typsend::pg_catalog.oid AS typsendoid, "
7789                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7790                                                   "0 AS typanalyzeoid, "
7791                                                   "'U' AS typcategory, false AS typispreferred, "
7792                                                   "typdelim, typbyval, typalign, typstorage, "
7793                                                   "false AS typcollatable, "
7794                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7795                                                   "FROM pg_catalog.pg_type "
7796                                                   "WHERE oid = '%u'::pg_catalog.oid",
7797                                                   tyinfo->dobj.catId.oid);
7798         }
7799         else if (fout->remoteVersion >= 70300)
7800         {
7801                 appendPQExpBuffer(query, "SELECT typlen, "
7802                                                   "typinput, typoutput, "
7803                                                   "'-' AS typreceive, '-' AS typsend, "
7804                                                   "'-' AS typmodin, '-' AS typmodout, "
7805                                                   "'-' AS typanalyze, "
7806                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7807                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7808                                                   "0 AS typanalyzeoid, "
7809                                                   "'U' AS typcategory, false AS typispreferred, "
7810                                                   "typdelim, typbyval, typalign, typstorage, "
7811                                                   "false AS typcollatable, "
7812                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7813                                                   "FROM pg_catalog.pg_type "
7814                                                   "WHERE oid = '%u'::pg_catalog.oid",
7815                                                   tyinfo->dobj.catId.oid);
7816         }
7817         else if (fout->remoteVersion >= 70200)
7818         {
7819                 /*
7820                  * Note: although pre-7.3 catalogs contain typreceive and typsend,
7821                  * ignore them because they are not right.
7822                  */
7823                 appendPQExpBuffer(query, "SELECT typlen, "
7824                                                   "typinput, typoutput, "
7825                                                   "'-' AS typreceive, '-' AS typsend, "
7826                                                   "'-' AS typmodin, '-' AS typmodout, "
7827                                                   "'-' AS typanalyze, "
7828                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7829                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7830                                                   "0 AS typanalyzeoid, "
7831                                                   "'U' AS typcategory, false AS typispreferred, "
7832                                                   "typdelim, typbyval, typalign, typstorage, "
7833                                                   "false AS typcollatable, "
7834                                                   "NULL AS typdefaultbin, typdefault "
7835                                                   "FROM pg_type "
7836                                                   "WHERE oid = '%u'::oid",
7837                                                   tyinfo->dobj.catId.oid);
7838         }
7839         else if (fout->remoteVersion >= 70100)
7840         {
7841                 /*
7842                  * Ignore pre-7.2 typdefault; the field exists but has an unusable
7843                  * representation.
7844                  */
7845                 appendPQExpBuffer(query, "SELECT typlen, "
7846                                                   "typinput, typoutput, "
7847                                                   "'-' AS typreceive, '-' AS typsend, "
7848                                                   "'-' AS typmodin, '-' AS typmodout, "
7849                                                   "'-' AS typanalyze, "
7850                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7851                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7852                                                   "0 AS typanalyzeoid, "
7853                                                   "'U' AS typcategory, false AS typispreferred, "
7854                                                   "typdelim, typbyval, typalign, typstorage, "
7855                                                   "false AS typcollatable, "
7856                                                   "NULL AS typdefaultbin, NULL AS typdefault "
7857                                                   "FROM pg_type "
7858                                                   "WHERE oid = '%u'::oid",
7859                                                   tyinfo->dobj.catId.oid);
7860         }
7861         else
7862         {
7863                 appendPQExpBuffer(query, "SELECT typlen, "
7864                                                   "typinput, typoutput, "
7865                                                   "'-' AS typreceive, '-' AS typsend, "
7866                                                   "'-' AS typmodin, '-' AS typmodout, "
7867                                                   "'-' AS typanalyze, "
7868                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7869                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7870                                                   "0 AS typanalyzeoid, "
7871                                                   "'U' AS typcategory, false AS typispreferred, "
7872                                                   "typdelim, typbyval, typalign, "
7873                                                   "'p'::char AS typstorage, "
7874                                                   "false AS typcollatable, "
7875                                                   "NULL AS typdefaultbin, NULL AS typdefault "
7876                                                   "FROM pg_type "
7877                                                   "WHERE oid = '%u'::oid",
7878                                                   tyinfo->dobj.catId.oid);
7879         }
7880
7881         res = ExecuteSqlQueryForSingleRow(fout, query->data);
7882
7883         typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
7884         typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
7885         typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
7886         typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
7887         typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
7888         typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
7889         typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
7890         typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
7891         typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
7892         typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
7893         typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
7894         typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
7895         typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
7896         typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
7897         typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
7898         typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
7899         typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
7900         typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
7901         typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
7902         typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
7903         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
7904                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
7905         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
7906         {
7907                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
7908                 typdefault_is_literal = true;   /* it needs quotes */
7909         }
7910         else
7911                 typdefault = NULL;
7912
7913         /*
7914          * DROP must be fully qualified in case same name appears in pg_catalog.
7915          * The reason we include CASCADE is that the circular dependency between
7916          * the type and its I/O functions makes it impossible to drop the type any
7917          * other way.
7918          */
7919         appendPQExpBuffer(delq, "DROP TYPE %s.",
7920                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7921         appendPQExpBuffer(delq, "%s CASCADE;\n",
7922                                           fmtId(tyinfo->dobj.name));
7923
7924         /* We might already have a shell type, but setting pg_type_oid is harmless */
7925         if (binary_upgrade)
7926                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7927                                                                                                  tyinfo->dobj.catId.oid);
7928
7929         appendPQExpBuffer(q,
7930                                           "CREATE TYPE %s (\n"
7931                                           "    INTERNALLENGTH = %s",
7932                                           fmtId(tyinfo->dobj.name),
7933                                           (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
7934
7935         if (fout->remoteVersion >= 70300)
7936         {
7937                 /* regproc result is correctly quoted as of 7.3 */
7938                 appendPQExpBuffer(q, ",\n    INPUT = %s", typinput);
7939                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", typoutput);
7940                 if (OidIsValid(typreceiveoid))
7941                         appendPQExpBuffer(q, ",\n    RECEIVE = %s", typreceive);
7942                 if (OidIsValid(typsendoid))
7943                         appendPQExpBuffer(q, ",\n    SEND = %s", typsend);
7944                 if (OidIsValid(typmodinoid))
7945                         appendPQExpBuffer(q, ",\n    TYPMOD_IN = %s", typmodin);
7946                 if (OidIsValid(typmodoutoid))
7947                         appendPQExpBuffer(q, ",\n    TYPMOD_OUT = %s", typmodout);
7948                 if (OidIsValid(typanalyzeoid))
7949                         appendPQExpBuffer(q, ",\n    ANALYZE = %s", typanalyze);
7950         }
7951         else
7952         {
7953                 /* regproc delivers an unquoted name before 7.3 */
7954                 /* cannot combine these because fmtId uses static result area */
7955                 appendPQExpBuffer(q, ",\n    INPUT = %s", fmtId(typinput));
7956                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", fmtId(typoutput));
7957                 /* receive/send/typmodin/typmodout/analyze need not be printed */
7958         }
7959
7960         if (strcmp(typcollatable, "t") == 0)
7961                 appendPQExpBuffer(q, ",\n    COLLATABLE = true");
7962
7963         if (typdefault != NULL)
7964         {
7965                 appendPQExpBuffer(q, ",\n    DEFAULT = ");
7966                 if (typdefault_is_literal)
7967                         appendStringLiteralAH(q, typdefault, fout);
7968                 else
7969                         appendPQExpBufferStr(q, typdefault);
7970         }
7971
7972         if (OidIsValid(tyinfo->typelem))
7973         {
7974                 char       *elemType;
7975
7976                 /* reselect schema in case changed by function dump */
7977                 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7978                 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
7979                 appendPQExpBuffer(q, ",\n    ELEMENT = %s", elemType);
7980                 free(elemType);
7981         }
7982
7983         if (strcmp(typcategory, "U") != 0)
7984         {
7985                 appendPQExpBuffer(q, ",\n    CATEGORY = ");
7986                 appendStringLiteralAH(q, typcategory, fout);
7987         }
7988
7989         if (strcmp(typispreferred, "t") == 0)
7990                 appendPQExpBuffer(q, ",\n    PREFERRED = true");
7991
7992         if (typdelim && strcmp(typdelim, ",") != 0)
7993         {
7994                 appendPQExpBuffer(q, ",\n    DELIMITER = ");
7995                 appendStringLiteralAH(q, typdelim, fout);
7996         }
7997
7998         if (strcmp(typalign, "c") == 0)
7999                 appendPQExpBuffer(q, ",\n    ALIGNMENT = char");
8000         else if (strcmp(typalign, "s") == 0)
8001                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int2");
8002         else if (strcmp(typalign, "i") == 0)
8003                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int4");
8004         else if (strcmp(typalign, "d") == 0)
8005                 appendPQExpBuffer(q, ",\n    ALIGNMENT = double");
8006
8007         if (strcmp(typstorage, "p") == 0)
8008                 appendPQExpBuffer(q, ",\n    STORAGE = plain");
8009         else if (strcmp(typstorage, "e") == 0)
8010                 appendPQExpBuffer(q, ",\n    STORAGE = external");
8011         else if (strcmp(typstorage, "x") == 0)
8012                 appendPQExpBuffer(q, ",\n    STORAGE = extended");
8013         else if (strcmp(typstorage, "m") == 0)
8014                 appendPQExpBuffer(q, ",\n    STORAGE = main");
8015
8016         if (strcmp(typbyval, "t") == 0)
8017                 appendPQExpBuffer(q, ",\n    PASSEDBYVALUE");
8018
8019         appendPQExpBuffer(q, "\n);\n");
8020
8021         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8022
8023         if (binary_upgrade)
8024                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8025
8026         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8027                                  tyinfo->dobj.name,
8028                                  tyinfo->dobj.namespace->dobj.name,
8029                                  NULL,
8030                                  tyinfo->rolname, false,
8031                                  "TYPE", SECTION_PRE_DATA,
8032                                  q->data, delq->data, NULL,
8033                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8034                                  NULL, NULL);
8035
8036         /* Dump Type Comments and Security Labels */
8037         dumpComment(fout, labelq->data,
8038                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8039                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8040         dumpSecLabel(fout, labelq->data,
8041                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8042                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8043
8044         PQclear(res);
8045         destroyPQExpBuffer(q);
8046         destroyPQExpBuffer(delq);
8047         destroyPQExpBuffer(labelq);
8048         destroyPQExpBuffer(query);
8049 }
8050
8051 /*
8052  * dumpDomain
8053  *        writes out to fout the queries to recreate a user-defined domain
8054  */
8055 static void
8056 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8057 {
8058         PQExpBuffer q = createPQExpBuffer();
8059         PQExpBuffer delq = createPQExpBuffer();
8060         PQExpBuffer labelq = createPQExpBuffer();
8061         PQExpBuffer query = createPQExpBuffer();
8062         PGresult   *res;
8063         int                     i;
8064         char       *typnotnull;
8065         char       *typdefn;
8066         char       *typdefault;
8067         Oid                     typcollation;
8068         bool            typdefault_is_literal = false;
8069
8070         /* Set proper schema search path so type references list correctly */
8071         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8072
8073         /* Fetch domain specific details */
8074         if (fout->remoteVersion >= 90100)
8075         {
8076                 /* typcollation is new in 9.1 */
8077                 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8078                         "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8079                                                   "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8080                                                   "t.typdefault, "
8081                                                   "CASE WHEN t.typcollation <> u.typcollation "
8082                                                   "THEN t.typcollation ELSE 0 END AS typcollation "
8083                                                   "FROM pg_catalog.pg_type t "
8084                                  "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8085                                                   "WHERE t.oid = '%u'::pg_catalog.oid",
8086                                                   tyinfo->dobj.catId.oid);
8087         }
8088         else
8089         {
8090                 /* We assume here that remoteVersion must be at least 70300 */
8091                 appendPQExpBuffer(query, "SELECT typnotnull, "
8092                                 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8093                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8094                                                   "typdefault, 0 AS typcollation "
8095                                                   "FROM pg_catalog.pg_type "
8096                                                   "WHERE oid = '%u'::pg_catalog.oid",
8097                                                   tyinfo->dobj.catId.oid);
8098         }
8099
8100         res = ExecuteSqlQueryForSingleRow(fout, query->data);
8101
8102         typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8103         typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8104         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8105                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8106         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8107         {
8108                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8109                 typdefault_is_literal = true;   /* it needs quotes */
8110         }
8111         else
8112                 typdefault = NULL;
8113         typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8114
8115         if (binary_upgrade)
8116                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8117                                                                                                  tyinfo->dobj.catId.oid);
8118
8119         appendPQExpBuffer(q,
8120                                           "CREATE DOMAIN %s AS %s",
8121                                           fmtId(tyinfo->dobj.name),
8122                                           typdefn);
8123
8124         /* Print collation only if different from base type's collation */
8125         if (OidIsValid(typcollation))
8126         {
8127                 CollInfo   *coll;
8128
8129                 coll = findCollationByOid(typcollation);
8130                 if (coll)
8131                 {
8132                         /* always schema-qualify, don't try to be smart */
8133                         appendPQExpBuffer(q, " COLLATE %s.",
8134                                                           fmtId(coll->dobj.namespace->dobj.name));
8135                         appendPQExpBuffer(q, "%s",
8136                                                           fmtId(coll->dobj.name));
8137                 }
8138         }
8139
8140         if (typnotnull[0] == 't')
8141                 appendPQExpBuffer(q, " NOT NULL");
8142
8143         if (typdefault != NULL)
8144         {
8145                 appendPQExpBuffer(q, " DEFAULT ");
8146                 if (typdefault_is_literal)
8147                         appendStringLiteralAH(q, typdefault, fout);
8148                 else
8149                         appendPQExpBufferStr(q, typdefault);
8150         }
8151
8152         PQclear(res);
8153
8154         /*
8155          * Add any CHECK constraints for the domain
8156          */
8157         for (i = 0; i < tyinfo->nDomChecks; i++)
8158         {
8159                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8160
8161                 if (!domcheck->separate)
8162                         appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8163                                                           fmtId(domcheck->dobj.name), domcheck->condef);
8164         }
8165
8166         appendPQExpBuffer(q, ";\n");
8167
8168         /*
8169          * DROP must be fully qualified in case same name appears in pg_catalog
8170          */
8171         appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8172                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8173         appendPQExpBuffer(delq, "%s;\n",
8174                                           fmtId(tyinfo->dobj.name));
8175
8176         appendPQExpBuffer(labelq, "DOMAIN %s", fmtId(tyinfo->dobj.name));
8177
8178         if (binary_upgrade)
8179                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8180
8181         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8182                                  tyinfo->dobj.name,
8183                                  tyinfo->dobj.namespace->dobj.name,
8184                                  NULL,
8185                                  tyinfo->rolname, false,
8186                                  "DOMAIN", SECTION_PRE_DATA,
8187                                  q->data, delq->data, NULL,
8188                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8189                                  NULL, NULL);
8190
8191         /* Dump Domain Comments and Security Labels */
8192         dumpComment(fout, labelq->data,
8193                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8194                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8195         dumpSecLabel(fout, labelq->data,
8196                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8197                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8198
8199         destroyPQExpBuffer(q);
8200         destroyPQExpBuffer(delq);
8201         destroyPQExpBuffer(labelq);
8202         destroyPQExpBuffer(query);
8203 }
8204
8205 /*
8206  * dumpCompositeType
8207  *        writes out to fout the queries to recreate a user-defined stand-alone
8208  *        composite type
8209  */
8210 static void
8211 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8212 {
8213         PQExpBuffer q = createPQExpBuffer();
8214         PQExpBuffer dropped = createPQExpBuffer();
8215         PQExpBuffer delq = createPQExpBuffer();
8216         PQExpBuffer labelq = createPQExpBuffer();
8217         PQExpBuffer query = createPQExpBuffer();
8218         PGresult   *res;
8219         int                     ntups;
8220         int                     i_attname;
8221         int                     i_atttypdefn;
8222         int                     i_attlen;
8223         int                     i_attalign;
8224         int                     i_attisdropped;
8225         int                     i_attcollation;
8226         int                     i_typrelid;
8227         int                     i;
8228         int                     actual_atts;
8229
8230         /* Set proper schema search path so type references list correctly */
8231         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8232
8233         /* Fetch type specific details */
8234         if (fout->remoteVersion >= 90100)
8235         {
8236                 /*
8237                  * attcollation is new in 9.1.  Since we only want to dump COLLATE
8238                  * clauses for attributes whose collation is different from their
8239                  * type's default, we use a CASE here to suppress uninteresting
8240                  * attcollations cheaply.  atttypid will be 0 for dropped columns;
8241                  * collation does not matter for those.
8242                  */
8243                 appendPQExpBuffer(query, "SELECT a.attname, "
8244                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8245                                                   "a.attlen, a.attalign, a.attisdropped, "
8246                                                   "CASE WHEN a.attcollation <> at.typcollation "
8247                                                   "THEN a.attcollation ELSE 0 END AS attcollation, "
8248                                                   "ct.typrelid "
8249                                                   "FROM pg_catalog.pg_type ct "
8250                                 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8251                                         "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8252                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8253                                                   "ORDER BY a.attnum ",
8254                                                   tyinfo->dobj.catId.oid);
8255         }
8256         else
8257         {
8258                 /*
8259                  * We assume here that remoteVersion must be at least 70300.  Since
8260                  * ALTER TYPE could not drop columns until 9.1, attisdropped should
8261                  * always be false.
8262                  */
8263                 appendPQExpBuffer(query, "SELECT a.attname, "
8264                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8265                                                   "a.attlen, a.attalign, a.attisdropped, "
8266                                                   "0 AS attcollation, "
8267                                                   "ct.typrelid "
8268                                          "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8269                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8270                                                   "AND a.attrelid = ct.typrelid "
8271                                                   "ORDER BY a.attnum ",
8272                                                   tyinfo->dobj.catId.oid);
8273         }
8274
8275         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8276
8277         ntups = PQntuples(res);
8278
8279         i_attname = PQfnumber(res, "attname");
8280         i_atttypdefn = PQfnumber(res, "atttypdefn");
8281         i_attlen = PQfnumber(res, "attlen");
8282         i_attalign = PQfnumber(res, "attalign");
8283         i_attisdropped = PQfnumber(res, "attisdropped");
8284         i_attcollation = PQfnumber(res, "attcollation");
8285         i_typrelid = PQfnumber(res, "typrelid");
8286
8287         if (binary_upgrade)
8288         {
8289                 Oid                     typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8290
8291                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8292                                                                                                  tyinfo->dobj.catId.oid);
8293                 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8294         }
8295
8296         appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8297                                           fmtId(tyinfo->dobj.name));
8298
8299         actual_atts = 0;
8300         for (i = 0; i < ntups; i++)
8301         {
8302                 char       *attname;
8303                 char       *atttypdefn;
8304                 char       *attlen;
8305                 char       *attalign;
8306                 bool            attisdropped;
8307                 Oid                     attcollation;
8308
8309                 attname = PQgetvalue(res, i, i_attname);
8310                 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8311                 attlen = PQgetvalue(res, i, i_attlen);
8312                 attalign = PQgetvalue(res, i, i_attalign);
8313                 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8314                 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8315
8316                 if (attisdropped && !binary_upgrade)
8317                         continue;
8318
8319                 /* Format properly if not first attr */
8320                 if (actual_atts++ > 0)
8321                         appendPQExpBuffer(q, ",");
8322                 appendPQExpBuffer(q, "\n\t");
8323
8324                 if (!attisdropped)
8325                 {
8326                         appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8327
8328                         /* Add collation if not default for the column type */
8329                         if (OidIsValid(attcollation))
8330                         {
8331                                 CollInfo   *coll;
8332
8333                                 coll = findCollationByOid(attcollation);
8334                                 if (coll)
8335                                 {
8336                                         /* always schema-qualify, don't try to be smart */
8337                                         appendPQExpBuffer(q, " COLLATE %s.",
8338                                                                           fmtId(coll->dobj.namespace->dobj.name));
8339                                         appendPQExpBuffer(q, "%s",
8340                                                                           fmtId(coll->dobj.name));
8341                                 }
8342                         }
8343                 }
8344                 else
8345                 {
8346                         /*
8347                          * This is a dropped attribute and we're in binary_upgrade mode.
8348                          * Insert a placeholder for it in the CREATE TYPE command, and set
8349                          * length and alignment with direct UPDATE to the catalogs
8350                          * afterwards. See similar code in dumpTableSchema().
8351                          */
8352                         appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8353
8354                         /* stash separately for insertion after the CREATE TYPE */
8355                         appendPQExpBuffer(dropped,
8356                                           "\n-- For binary upgrade, recreate dropped column.\n");
8357                         appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8358                                                           "SET attlen = %s, "
8359                                                           "attalign = '%s', attbyval = false\n"
8360                                                           "WHERE attname = ", attlen, attalign);
8361                         appendStringLiteralAH(dropped, attname, fout);
8362                         appendPQExpBuffer(dropped, "\n  AND attrelid = ");
8363                         appendStringLiteralAH(dropped, fmtId(tyinfo->dobj.name), fout);
8364                         appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8365
8366                         appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8367                                                           fmtId(tyinfo->dobj.name));
8368                         appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8369                                                           fmtId(attname));
8370                 }
8371         }
8372         appendPQExpBuffer(q, "\n);\n");
8373         appendPQExpBufferStr(q, dropped->data);
8374
8375         /*
8376          * DROP must be fully qualified in case same name appears in pg_catalog
8377          */
8378         appendPQExpBuffer(delq, "DROP TYPE %s.",
8379                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8380         appendPQExpBuffer(delq, "%s;\n",
8381                                           fmtId(tyinfo->dobj.name));
8382
8383         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8384
8385         if (binary_upgrade)
8386                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8387
8388         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8389                                  tyinfo->dobj.name,
8390                                  tyinfo->dobj.namespace->dobj.name,
8391                                  NULL,
8392                                  tyinfo->rolname, false,
8393                                  "TYPE", SECTION_PRE_DATA,
8394                                  q->data, delq->data, NULL,
8395                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8396                                  NULL, NULL);
8397
8398
8399         /* Dump Type Comments and Security Labels */
8400         dumpComment(fout, labelq->data,
8401                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8402                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8403         dumpSecLabel(fout, labelq->data,
8404                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8405                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8406
8407         PQclear(res);
8408         destroyPQExpBuffer(q);
8409         destroyPQExpBuffer(dropped);
8410         destroyPQExpBuffer(delq);
8411         destroyPQExpBuffer(labelq);
8412         destroyPQExpBuffer(query);
8413
8414         /* Dump any per-column comments */
8415         dumpCompositeTypeColComments(fout, tyinfo);
8416 }
8417
8418 /*
8419  * dumpCompositeTypeColComments
8420  *        writes out to fout the queries to recreate comments on the columns of
8421  *        a user-defined stand-alone composite type
8422  */
8423 static void
8424 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8425 {
8426         CommentItem *comments;
8427         int                     ncomments;
8428         PGresult   *res;
8429         PQExpBuffer query;
8430         PQExpBuffer target;
8431         Oid                     pgClassOid;
8432         int                     i;
8433         int                     ntups;
8434         int                     i_attname;
8435         int                     i_attnum;
8436
8437         query = createPQExpBuffer();
8438
8439         /* We assume here that remoteVersion must be at least 70300 */
8440         appendPQExpBuffer(query,
8441                                           "SELECT c.tableoid, a.attname, a.attnum "
8442                                           "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8443                                           "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8444                                           "  AND NOT a.attisdropped "
8445                                           "ORDER BY a.attnum ",
8446                                           tyinfo->typrelid);
8447
8448         /* Fetch column attnames */
8449         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8450
8451         ntups = PQntuples(res);
8452         if (ntups < 1)
8453         {
8454                 PQclear(res);
8455                 destroyPQExpBuffer(query);
8456                 return;
8457         }
8458
8459         pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8460
8461         /* Search for comments associated with type's pg_class OID */
8462         ncomments = findComments(fout,
8463                                                          pgClassOid,
8464                                                          tyinfo->typrelid,
8465                                                          &comments);
8466
8467         /* If no comments exist, we're done */
8468         if (ncomments <= 0)
8469         {
8470                 PQclear(res);
8471                 destroyPQExpBuffer(query);
8472                 return;
8473         }
8474
8475         /* Build COMMENT ON statements */
8476         target = createPQExpBuffer();
8477
8478         i_attnum = PQfnumber(res, "attnum");
8479         i_attname = PQfnumber(res, "attname");
8480         while (ncomments > 0)
8481         {
8482                 const char *attname;
8483
8484                 attname = NULL;
8485                 for (i = 0; i < ntups; i++)
8486                 {
8487                         if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8488                         {
8489                                 attname = PQgetvalue(res, i, i_attname);
8490                                 break;
8491                         }
8492                 }
8493                 if (attname)                    /* just in case we don't find it */
8494                 {
8495                         const char *descr = comments->descr;
8496
8497                         resetPQExpBuffer(target);
8498                         appendPQExpBuffer(target, "COLUMN %s.",
8499                                                           fmtId(tyinfo->dobj.name));
8500                         appendPQExpBuffer(target, "%s",
8501                                                           fmtId(attname));
8502
8503                         resetPQExpBuffer(query);
8504                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8505                         appendStringLiteralAH(query, descr, fout);
8506                         appendPQExpBuffer(query, ";\n");
8507
8508                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
8509                                                  target->data,
8510                                                  tyinfo->dobj.namespace->dobj.name,
8511                                                  NULL, tyinfo->rolname,
8512                                                  false, "COMMENT", SECTION_NONE,
8513                                                  query->data, "", NULL,
8514                                                  &(tyinfo->dobj.dumpId), 1,
8515                                                  NULL, NULL);
8516                 }
8517
8518                 comments++;
8519                 ncomments--;
8520         }
8521
8522         PQclear(res);
8523         destroyPQExpBuffer(query);
8524         destroyPQExpBuffer(target);
8525 }
8526
8527 /*
8528  * dumpShellType
8529  *        writes out to fout the queries to create a shell type
8530  *
8531  * We dump a shell definition in advance of the I/O functions for the type.
8532  */
8533 static void
8534 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8535 {
8536         PQExpBuffer q;
8537
8538         /* Skip if not to be dumped */
8539         if (!stinfo->dobj.dump || dataOnly)
8540                 return;
8541
8542         q = createPQExpBuffer();
8543
8544         /*
8545          * Note the lack of a DROP command for the shell type; any required DROP
8546          * is driven off the base type entry, instead.  This interacts with
8547          * _printTocEntry()'s use of the presence of a DROP command to decide
8548          * whether an entry needs an ALTER OWNER command.  We don't want to alter
8549          * the shell type's owner immediately on creation; that should happen only
8550          * after it's filled in, otherwise the backend complains.
8551          */
8552
8553         if (binary_upgrade)
8554                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8555                                                                                    stinfo->baseType->dobj.catId.oid);
8556
8557         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8558                                           fmtId(stinfo->dobj.name));
8559
8560         ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8561                                  stinfo->dobj.name,
8562                                  stinfo->dobj.namespace->dobj.name,
8563                                  NULL,
8564                                  stinfo->baseType->rolname, false,
8565                                  "SHELL TYPE", SECTION_PRE_DATA,
8566                                  q->data, "", NULL,
8567                                  stinfo->dobj.dependencies, stinfo->dobj.nDeps,
8568                                  NULL, NULL);
8569
8570         destroyPQExpBuffer(q);
8571 }
8572
8573 /*
8574  * Determine whether we want to dump definitions for procedural languages.
8575  * Since the languages themselves don't have schemas, we can't rely on
8576  * the normal schema-based selection mechanism.  We choose to dump them
8577  * whenever neither --schema nor --table was given.  (Before 8.1, we used
8578  * the dump flag of the PL's call handler function, but in 8.1 this will
8579  * probably always be false since call handlers are created in pg_catalog.)
8580  *
8581  * For some backwards compatibility with the older behavior, we forcibly
8582  * dump a PL if its handler function (and validator if any) are in a
8583  * dumpable namespace.  That case is not checked here.
8584  *
8585  * Also, if the PL belongs to an extension, we do not use this heuristic.
8586  * That case isn't checked here either.
8587  */
8588 static bool
8589 shouldDumpProcLangs(void)
8590 {
8591         if (!include_everything)
8592                 return false;
8593         /* And they're schema not data */
8594         if (dataOnly)
8595                 return false;
8596         return true;
8597 }
8598
8599 /*
8600  * dumpProcLang
8601  *                writes out to fout the queries to recreate a user-defined
8602  *                procedural language
8603  */
8604 static void
8605 dumpProcLang(Archive *fout, ProcLangInfo *plang)
8606 {
8607         PQExpBuffer defqry;
8608         PQExpBuffer delqry;
8609         PQExpBuffer labelq;
8610         bool            useParams;
8611         char       *qlanname;
8612         char       *lanschema;
8613         FuncInfo   *funcInfo;
8614         FuncInfo   *inlineInfo = NULL;
8615         FuncInfo   *validatorInfo = NULL;
8616
8617         /* Skip if not to be dumped */
8618         if (!plang->dobj.dump || dataOnly)
8619                 return;
8620
8621         /*
8622          * Try to find the support function(s).  It is not an error if we don't
8623          * find them --- if the functions are in the pg_catalog schema, as is
8624          * standard in 8.1 and up, then we won't have loaded them. (In this case
8625          * we will emit a parameterless CREATE LANGUAGE command, which will
8626          * require PL template knowledge in the backend to reload.)
8627          */
8628
8629         funcInfo = findFuncByOid(plang->lanplcallfoid);
8630         if (funcInfo != NULL && !funcInfo->dobj.dump)
8631                 funcInfo = NULL;                /* treat not-dumped same as not-found */
8632
8633         if (OidIsValid(plang->laninline))
8634         {
8635                 inlineInfo = findFuncByOid(plang->laninline);
8636                 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
8637                         inlineInfo = NULL;
8638         }
8639
8640         if (OidIsValid(plang->lanvalidator))
8641         {
8642                 validatorInfo = findFuncByOid(plang->lanvalidator);
8643                 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
8644                         validatorInfo = NULL;
8645         }
8646
8647         /*
8648          * If the functions are dumpable then emit a traditional CREATE LANGUAGE
8649          * with parameters.  Otherwise, dump only if shouldDumpProcLangs() says to
8650          * dump it.
8651          *
8652          * However, for a language that belongs to an extension, we must not use
8653          * the shouldDumpProcLangs heuristic, but just dump the language iff we're
8654          * told to (via dobj.dump).  Generally the support functions will belong
8655          * to the same extension and so have the same dump flags ... if they
8656          * don't, this might not work terribly nicely.
8657          */
8658         useParams = (funcInfo != NULL &&
8659                                  (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
8660                                  (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
8661
8662         if (!plang->dobj.ext_member)
8663         {
8664                 if (!useParams && !shouldDumpProcLangs())
8665                         return;
8666         }
8667
8668         defqry = createPQExpBuffer();
8669         delqry = createPQExpBuffer();
8670         labelq = createPQExpBuffer();
8671
8672         qlanname = pg_strdup(fmtId(plang->dobj.name));
8673
8674         /*
8675          * If dumping a HANDLER clause, treat the language as being in the handler
8676          * function's schema; this avoids cluttering the HANDLER clause. Otherwise
8677          * it doesn't really have a schema.
8678          */
8679         if (useParams)
8680                 lanschema = funcInfo->dobj.namespace->dobj.name;
8681         else
8682                 lanschema = NULL;
8683
8684         appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
8685                                           qlanname);
8686
8687         if (useParams)
8688         {
8689                 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
8690                                                   plang->lanpltrusted ? "TRUSTED " : "",
8691                                                   qlanname);
8692                 appendPQExpBuffer(defqry, " HANDLER %s",
8693                                                   fmtId(funcInfo->dobj.name));
8694                 if (OidIsValid(plang->laninline))
8695                 {
8696                         appendPQExpBuffer(defqry, " INLINE ");
8697                         /* Cope with possibility that inline is in different schema */
8698                         if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
8699                                 appendPQExpBuffer(defqry, "%s.",
8700                                                            fmtId(inlineInfo->dobj.namespace->dobj.name));
8701                         appendPQExpBuffer(defqry, "%s",
8702                                                           fmtId(inlineInfo->dobj.name));
8703                 }
8704                 if (OidIsValid(plang->lanvalidator))
8705                 {
8706                         appendPQExpBuffer(defqry, " VALIDATOR ");
8707                         /* Cope with possibility that validator is in different schema */
8708                         if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
8709                                 appendPQExpBuffer(defqry, "%s.",
8710                                                         fmtId(validatorInfo->dobj.namespace->dobj.name));
8711                         appendPQExpBuffer(defqry, "%s",
8712                                                           fmtId(validatorInfo->dobj.name));
8713                 }
8714         }
8715         else
8716         {
8717                 /*
8718                  * If not dumping parameters, then use CREATE OR REPLACE so that the
8719                  * command will not fail if the language is preinstalled in the target
8720                  * database.  We restrict the use of REPLACE to this case so as to
8721                  * eliminate the risk of replacing a language with incompatible
8722                  * parameter settings: this command will only succeed at all if there
8723                  * is a pg_pltemplate entry, and if there is one, the existing entry
8724                  * must match it too.
8725                  */
8726                 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
8727                                                   qlanname);
8728         }
8729         appendPQExpBuffer(defqry, ";\n");
8730
8731         appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
8732
8733         if (binary_upgrade)
8734                 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
8735
8736         ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
8737                                  plang->dobj.name,
8738                                  lanschema, NULL, plang->lanowner,
8739                                  false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
8740                                  defqry->data, delqry->data, NULL,
8741                                  plang->dobj.dependencies, plang->dobj.nDeps,
8742                                  NULL, NULL);
8743
8744         /* Dump Proc Lang Comments and Security Labels */
8745         dumpComment(fout, labelq->data,
8746                                 NULL, "",
8747                                 plang->dobj.catId, 0, plang->dobj.dumpId);
8748         dumpSecLabel(fout, labelq->data,
8749                                  NULL, "",
8750                                  plang->dobj.catId, 0, plang->dobj.dumpId);
8751
8752         if (plang->lanpltrusted)
8753                 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
8754                                 qlanname, NULL, plang->dobj.name,
8755                                 lanschema,
8756                                 plang->lanowner, plang->lanacl);
8757
8758         free(qlanname);
8759
8760         destroyPQExpBuffer(defqry);
8761         destroyPQExpBuffer(delqry);
8762         destroyPQExpBuffer(labelq);
8763 }
8764
8765 /*
8766  * format_function_arguments: generate function name and argument list
8767  *
8768  * This is used when we can rely on pg_get_function_arguments to format
8769  * the argument list.
8770  */
8771 static char *
8772 format_function_arguments(FuncInfo *finfo, char *funcargs)
8773 {
8774         PQExpBufferData fn;
8775
8776         initPQExpBuffer(&fn);
8777         appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
8778         return fn.data;
8779 }
8780
8781 /*
8782  * format_function_arguments_old: generate function name and argument list
8783  *
8784  * The argument type names are qualified if needed.  The function name
8785  * is never qualified.
8786  *
8787  * This is used only with pre-8.4 servers, so we aren't expecting to see
8788  * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
8789  *
8790  * Any or all of allargtypes, argmodes, argnames may be NULL.
8791  */
8792 static char *
8793 format_function_arguments_old(Archive *fout,
8794                                                           FuncInfo *finfo, int nallargs,
8795                                                           char **allargtypes,
8796                                                           char **argmodes,
8797                                                           char **argnames)
8798 {
8799         PQExpBufferData fn;
8800         int                     j;
8801
8802         initPQExpBuffer(&fn);
8803         appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8804         for (j = 0; j < nallargs; j++)
8805         {
8806                 Oid                     typid;
8807                 char       *typname;
8808                 const char *argmode;
8809                 const char *argname;
8810
8811                 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
8812                 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
8813
8814                 if (argmodes)
8815                 {
8816                         switch (argmodes[j][0])
8817                         {
8818                                 case PROARGMODE_IN:
8819                                         argmode = "";
8820                                         break;
8821                                 case PROARGMODE_OUT:
8822                                         argmode = "OUT ";
8823                                         break;
8824                                 case PROARGMODE_INOUT:
8825                                         argmode = "INOUT ";
8826                                         break;
8827                                 default:
8828                                         write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
8829                                         argmode = "";
8830                                         break;
8831                         }
8832                 }
8833                 else
8834                         argmode = "";
8835
8836                 argname = argnames ? argnames[j] : (char *) NULL;
8837                 if (argname && argname[0] == '\0')
8838                         argname = NULL;
8839
8840                 appendPQExpBuffer(&fn, "%s%s%s%s%s",
8841                                                   (j > 0) ? ", " : "",
8842                                                   argmode,
8843                                                   argname ? fmtId(argname) : "",
8844                                                   argname ? " " : "",
8845                                                   typname);
8846                 free(typname);
8847         }
8848         appendPQExpBuffer(&fn, ")");
8849         return fn.data;
8850 }
8851
8852 /*
8853  * format_function_signature: generate function name and argument list
8854  *
8855  * This is like format_function_arguments_old except that only a minimal
8856  * list of input argument types is generated; this is sufficient to
8857  * reference the function, but not to define it.
8858  *
8859  * If honor_quotes is false then the function name is never quoted.
8860  * This is appropriate for use in TOC tags, but not in SQL commands.
8861  */
8862 static char *
8863 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
8864 {
8865         PQExpBufferData fn;
8866         int                     j;
8867
8868         initPQExpBuffer(&fn);
8869         if (honor_quotes)
8870                 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8871         else
8872                 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
8873         for (j = 0; j < finfo->nargs; j++)
8874         {
8875                 char       *typname;
8876
8877                 typname = getFormattedTypeName(fout, finfo->argtypes[j],
8878                                                                            zeroAsOpaque);
8879
8880                 appendPQExpBuffer(&fn, "%s%s",
8881                                                   (j > 0) ? ", " : "",
8882                                                   typname);
8883                 free(typname);
8884         }
8885         appendPQExpBuffer(&fn, ")");
8886         return fn.data;
8887 }
8888
8889
8890 /*
8891  * dumpFunc:
8892  *        dump out one function
8893  */
8894 static void
8895 dumpFunc(Archive *fout, FuncInfo *finfo)
8896 {
8897         PQExpBuffer query;
8898         PQExpBuffer q;
8899         PQExpBuffer delqry;
8900         PQExpBuffer labelq;
8901         PQExpBuffer asPart;
8902         PGresult   *res;
8903         char       *funcsig;            /* identity signature */
8904         char       *funcfullsig;        /* full signature */
8905         char       *funcsig_tag;
8906         char       *proretset;
8907         char       *prosrc;
8908         char       *probin;
8909         char       *funcargs;
8910         char       *funciargs;
8911         char       *funcresult;
8912         char       *proallargtypes;
8913         char       *proargmodes;
8914         char       *proargnames;
8915         char       *proiswindow;
8916         char       *provolatile;
8917         char       *proisstrict;
8918         char       *prosecdef;
8919         char       *proleakproof;
8920         char       *proconfig;
8921         char       *procost;
8922         char       *prorows;
8923         char       *lanname;
8924         char       *rettypename;
8925         int                     nallargs;
8926         char      **allargtypes = NULL;
8927         char      **argmodes = NULL;
8928         char      **argnames = NULL;
8929         char      **configitems = NULL;
8930         int                     nconfigitems = 0;
8931         int                     i;
8932
8933         /* Skip if not to be dumped */
8934         if (!finfo->dobj.dump || dataOnly)
8935                 return;
8936
8937         query = createPQExpBuffer();
8938         q = createPQExpBuffer();
8939         delqry = createPQExpBuffer();
8940         labelq = createPQExpBuffer();
8941         asPart = createPQExpBuffer();
8942
8943         /* Set proper schema search path so type references list correctly */
8944         selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
8945
8946         /* Fetch function-specific details */
8947         if (fout->remoteVersion >= 90200)
8948         {
8949                 /*
8950                  * proleakproof was added at v9.2
8951                  */
8952                 appendPQExpBuffer(query,
8953                                                   "SELECT proretset, prosrc, probin, "
8954                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8955                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8956                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8957                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
8958                                                   "proleakproof, proconfig, procost, prorows, "
8959                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8960                                                   "FROM pg_catalog.pg_proc "
8961                                                   "WHERE oid = '%u'::pg_catalog.oid",
8962                                                   finfo->dobj.catId.oid);
8963         }
8964         else if (fout->remoteVersion >= 80400)
8965         {
8966                 /*
8967                  * In 8.4 and up we rely on pg_get_function_arguments and
8968                  * pg_get_function_result instead of examining proallargtypes etc.
8969                  */
8970                 appendPQExpBuffer(query,
8971                                                   "SELECT proretset, prosrc, probin, "
8972                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8973                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8974                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8975                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
8976                                                   "false AS proleakproof, "
8977                                                   " proconfig, procost, prorows, "
8978                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8979                                                   "FROM pg_catalog.pg_proc "
8980                                                   "WHERE oid = '%u'::pg_catalog.oid",
8981                                                   finfo->dobj.catId.oid);
8982         }
8983         else if (fout->remoteVersion >= 80300)
8984         {
8985                 appendPQExpBuffer(query,
8986                                                   "SELECT proretset, prosrc, probin, "
8987                                                   "proallargtypes, proargmodes, proargnames, "
8988                                                   "false AS proiswindow, "
8989                                                   "provolatile, proisstrict, prosecdef, "
8990                                                   "false AS proleakproof, "
8991                                                   "proconfig, procost, prorows, "
8992                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8993                                                   "FROM pg_catalog.pg_proc "
8994                                                   "WHERE oid = '%u'::pg_catalog.oid",
8995                                                   finfo->dobj.catId.oid);
8996         }
8997         else if (fout->remoteVersion >= 80100)
8998         {
8999                 appendPQExpBuffer(query,
9000                                                   "SELECT proretset, prosrc, probin, "
9001                                                   "proallargtypes, proargmodes, proargnames, "
9002                                                   "false AS proiswindow, "
9003                                                   "provolatile, proisstrict, prosecdef, "
9004                                                   "false AS proleakproof, "
9005                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9006                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9007                                                   "FROM pg_catalog.pg_proc "
9008                                                   "WHERE oid = '%u'::pg_catalog.oid",
9009                                                   finfo->dobj.catId.oid);
9010         }
9011         else if (fout->remoteVersion >= 80000)
9012         {
9013                 appendPQExpBuffer(query,
9014                                                   "SELECT proretset, prosrc, probin, "
9015                                                   "null AS proallargtypes, "
9016                                                   "null AS proargmodes, "
9017                                                   "proargnames, "
9018                                                   "false AS proiswindow, "
9019                                                   "provolatile, proisstrict, prosecdef, "
9020                                                   "false AS proleakproof, "
9021                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9022                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9023                                                   "FROM pg_catalog.pg_proc "
9024                                                   "WHERE oid = '%u'::pg_catalog.oid",
9025                                                   finfo->dobj.catId.oid);
9026         }
9027         else if (fout->remoteVersion >= 70300)
9028         {
9029                 appendPQExpBuffer(query,
9030                                                   "SELECT proretset, prosrc, probin, "
9031                                                   "null AS proallargtypes, "
9032                                                   "null AS proargmodes, "
9033                                                   "null AS proargnames, "
9034                                                   "false AS proiswindow, "
9035                                                   "provolatile, proisstrict, prosecdef, "
9036                                                   "false AS proleakproof, "
9037                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9038                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9039                                                   "FROM pg_catalog.pg_proc "
9040                                                   "WHERE oid = '%u'::pg_catalog.oid",
9041                                                   finfo->dobj.catId.oid);
9042         }
9043         else if (fout->remoteVersion >= 70100)
9044         {
9045                 appendPQExpBuffer(query,
9046                                                   "SELECT proretset, prosrc, probin, "
9047                                                   "null AS proallargtypes, "
9048                                                   "null AS proargmodes, "
9049                                                   "null AS proargnames, "
9050                                                   "false AS proiswindow, "
9051                          "case when proiscachable then 'i' else 'v' end AS provolatile, "
9052                                                   "proisstrict, "
9053                                                   "false AS prosecdef, "
9054                                                   "false AS proleakproof, "
9055                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9056                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9057                                                   "FROM pg_proc "
9058                                                   "WHERE oid = '%u'::oid",
9059                                                   finfo->dobj.catId.oid);
9060         }
9061         else
9062         {
9063                 appendPQExpBuffer(query,
9064                                                   "SELECT proretset, prosrc, probin, "
9065                                                   "null AS proallargtypes, "
9066                                                   "null AS proargmodes, "
9067                                                   "null AS proargnames, "
9068                                                   "false AS proiswindow, "
9069                          "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9070                                                   "false AS proisstrict, "
9071                                                   "false AS prosecdef, "
9072                                                   "false AS proleakproof, "
9073                                                   "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9074                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9075                                                   "FROM pg_proc "
9076                                                   "WHERE oid = '%u'::oid",
9077                                                   finfo->dobj.catId.oid);
9078         }
9079
9080         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9081
9082         proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9083         prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9084         probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9085         if (fout->remoteVersion >= 80400)
9086         {
9087                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9088                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9089                 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9090                 proallargtypes = proargmodes = proargnames = NULL;
9091         }
9092         else
9093         {
9094                 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9095                 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9096                 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9097                 funcargs = funciargs = funcresult = NULL;
9098         }
9099         proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9100         provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9101         proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9102         prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9103         proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9104         proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9105         procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9106         prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9107         lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9108
9109         /*
9110          * See backend/commands/functioncmds.c for details of how the 'AS' clause
9111          * is used.  In 8.4 and up, an unused probin is NULL (here ""); previous
9112          * versions would set it to "-".  There are no known cases in which prosrc
9113          * is unused, so the tests below for "-" are probably useless.
9114          */
9115         if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9116         {
9117                 appendPQExpBuffer(asPart, "AS ");
9118                 appendStringLiteralAH(asPart, probin, fout);
9119                 if (strcmp(prosrc, "-") != 0)
9120                 {
9121                         appendPQExpBuffer(asPart, ", ");
9122
9123                         /*
9124                          * where we have bin, use dollar quoting if allowed and src
9125                          * contains quote or backslash; else use regular quoting.
9126                          */
9127                         if (disable_dollar_quoting ||
9128                           (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9129                                 appendStringLiteralAH(asPart, prosrc, fout);
9130                         else
9131                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9132                 }
9133         }
9134         else
9135         {
9136                 if (strcmp(prosrc, "-") != 0)
9137                 {
9138                         appendPQExpBuffer(asPart, "AS ");
9139                         /* with no bin, dollar quote src unconditionally if allowed */
9140                         if (disable_dollar_quoting)
9141                                 appendStringLiteralAH(asPart, prosrc, fout);
9142                         else
9143                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9144                 }
9145         }
9146
9147         nallargs = finfo->nargs;        /* unless we learn different from allargs */
9148
9149         if (proallargtypes && *proallargtypes)
9150         {
9151                 int                     nitems = 0;
9152
9153                 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9154                         nitems < finfo->nargs)
9155                 {
9156                         write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9157                         if (allargtypes)
9158                                 free(allargtypes);
9159                         allargtypes = NULL;
9160                 }
9161                 else
9162                         nallargs = nitems;
9163         }
9164
9165         if (proargmodes && *proargmodes)
9166         {
9167                 int                     nitems = 0;
9168
9169                 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9170                         nitems != nallargs)
9171                 {
9172                         write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9173                         if (argmodes)
9174                                 free(argmodes);
9175                         argmodes = NULL;
9176                 }
9177         }
9178
9179         if (proargnames && *proargnames)
9180         {
9181                 int                     nitems = 0;
9182
9183                 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9184                         nitems != nallargs)
9185                 {
9186                         write_msg(NULL, "WARNING: could not parse proargnames array\n");
9187                         if (argnames)
9188                                 free(argnames);
9189                         argnames = NULL;
9190                 }
9191         }
9192
9193         if (proconfig && *proconfig)
9194         {
9195                 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9196                 {
9197                         write_msg(NULL, "WARNING: could not parse proconfig array\n");
9198                         if (configitems)
9199                                 free(configitems);
9200                         configitems = NULL;
9201                         nconfigitems = 0;
9202                 }
9203         }
9204
9205         if (funcargs)
9206         {
9207                 /* 8.4 or later; we rely on server-side code for most of the work */
9208                 funcfullsig = format_function_arguments(finfo, funcargs);
9209                 funcsig = format_function_arguments(finfo, funciargs);
9210         }
9211         else
9212         {
9213                 /* pre-8.4, do it ourselves */
9214                 funcsig = format_function_arguments_old(fout,
9215                                                                                                 finfo, nallargs, allargtypes,
9216                                                                                                 argmodes, argnames);
9217                 funcfullsig = funcsig;
9218         }
9219
9220         funcsig_tag = format_function_signature(fout, finfo, false);
9221
9222         /*
9223          * DROP must be fully qualified in case same name appears in pg_catalog
9224          */
9225         appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9226                                           fmtId(finfo->dobj.namespace->dobj.name),
9227                                           funcsig);
9228
9229         appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9230         if (funcresult)
9231                 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9232         else
9233         {
9234                 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9235                                                                                    zeroAsOpaque);
9236                 appendPQExpBuffer(q, "RETURNS %s%s",
9237                                                   (proretset[0] == 't') ? "SETOF " : "",
9238                                                   rettypename);
9239                 free(rettypename);
9240         }
9241
9242         appendPQExpBuffer(q, "\n    LANGUAGE %s", fmtId(lanname));
9243
9244         if (proiswindow[0] == 't')
9245                 appendPQExpBuffer(q, " WINDOW");
9246
9247         if (provolatile[0] != PROVOLATILE_VOLATILE)
9248         {
9249                 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9250                         appendPQExpBuffer(q, " IMMUTABLE");
9251                 else if (provolatile[0] == PROVOLATILE_STABLE)
9252                         appendPQExpBuffer(q, " STABLE");
9253                 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9254                         exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9255                                                   finfo->dobj.name);
9256         }
9257
9258         if (proisstrict[0] == 't')
9259                 appendPQExpBuffer(q, " STRICT");
9260
9261         if (prosecdef[0] == 't')
9262                 appendPQExpBuffer(q, " SECURITY DEFINER");
9263
9264         if (proleakproof[0] == 't')
9265                 appendPQExpBuffer(q, " LEAKPROOF");
9266
9267         /*
9268          * COST and ROWS are emitted only if present and not default, so as not to
9269          * break backwards-compatibility of the dump without need.      Keep this code
9270          * in sync with the defaults in functioncmds.c.
9271          */
9272         if (strcmp(procost, "0") != 0)
9273         {
9274                 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9275                 {
9276                         /* default cost is 1 */
9277                         if (strcmp(procost, "1") != 0)
9278                                 appendPQExpBuffer(q, " COST %s", procost);
9279                 }
9280                 else
9281                 {
9282                         /* default cost is 100 */
9283                         if (strcmp(procost, "100") != 0)
9284                                 appendPQExpBuffer(q, " COST %s", procost);
9285                 }
9286         }
9287         if (proretset[0] == 't' &&
9288                 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9289                 appendPQExpBuffer(q, " ROWS %s", prorows);
9290
9291         for (i = 0; i < nconfigitems; i++)
9292         {
9293                 /* we feel free to scribble on configitems[] here */
9294                 char       *configitem = configitems[i];
9295                 char       *pos;
9296
9297                 pos = strchr(configitem, '=');
9298                 if (pos == NULL)
9299                         continue;
9300                 *pos++ = '\0';
9301                 appendPQExpBuffer(q, "\n    SET %s TO ", fmtId(configitem));
9302
9303                 /*
9304                  * Some GUC variable names are 'LIST' type and hence must not be
9305                  * quoted.
9306                  */
9307                 if (pg_strcasecmp(configitem, "DateStyle") == 0
9308                         || pg_strcasecmp(configitem, "search_path") == 0)
9309                         appendPQExpBuffer(q, "%s", pos);
9310                 else
9311                         appendStringLiteralAH(q, pos, fout);
9312         }
9313
9314         appendPQExpBuffer(q, "\n    %s;\n", asPart->data);
9315
9316         appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9317
9318         if (binary_upgrade)
9319                 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9320
9321         ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9322                                  funcsig_tag,
9323                                  finfo->dobj.namespace->dobj.name,
9324                                  NULL,
9325                                  finfo->rolname, false,
9326                                  "FUNCTION", SECTION_PRE_DATA,
9327                                  q->data, delqry->data, NULL,
9328                                  finfo->dobj.dependencies, finfo->dobj.nDeps,
9329                                  NULL, NULL);
9330
9331         /* Dump Function Comments and Security Labels */
9332         dumpComment(fout, labelq->data,
9333                                 finfo->dobj.namespace->dobj.name, finfo->rolname,
9334                                 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9335         dumpSecLabel(fout, labelq->data,
9336                                  finfo->dobj.namespace->dobj.name, finfo->rolname,
9337                                  finfo->dobj.catId, 0, finfo->dobj.dumpId);
9338
9339         dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9340                         funcsig, NULL, funcsig_tag,
9341                         finfo->dobj.namespace->dobj.name,
9342                         finfo->rolname, finfo->proacl);
9343
9344         PQclear(res);
9345
9346         destroyPQExpBuffer(query);
9347         destroyPQExpBuffer(q);
9348         destroyPQExpBuffer(delqry);
9349         destroyPQExpBuffer(labelq);
9350         destroyPQExpBuffer(asPart);
9351         free(funcsig);
9352         free(funcsig_tag);
9353         if (allargtypes)
9354                 free(allargtypes);
9355         if (argmodes)
9356                 free(argmodes);
9357         if (argnames)
9358                 free(argnames);
9359         if (configitems)
9360                 free(configitems);
9361 }
9362
9363
9364 /*
9365  * Dump a user-defined cast
9366  */
9367 static void
9368 dumpCast(Archive *fout, CastInfo *cast)
9369 {
9370         PQExpBuffer defqry;
9371         PQExpBuffer delqry;
9372         PQExpBuffer labelq;
9373         FuncInfo   *funcInfo = NULL;
9374
9375         /* Skip if not to be dumped */
9376         if (!cast->dobj.dump || dataOnly)
9377                 return;
9378
9379         /* Cannot dump if we don't have the cast function's info */
9380         if (OidIsValid(cast->castfunc))
9381         {
9382                 funcInfo = findFuncByOid(cast->castfunc);
9383                 if (funcInfo == NULL)
9384                         return;
9385         }
9386
9387         /*
9388          * As per discussion we dump casts if one or more of the underlying
9389          * objects (the conversion function and the two data types) are not
9390          * builtin AND if all of the non-builtin objects are included in the dump.
9391          * Builtin meaning, the namespace name does not start with "pg_".
9392          *
9393          * However, for a cast that belongs to an extension, we must not use this
9394          * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9395          */
9396         if (!cast->dobj.ext_member)
9397         {
9398                 TypeInfo   *sourceInfo = findTypeByOid(cast->castsource);
9399                 TypeInfo   *targetInfo = findTypeByOid(cast->casttarget);
9400
9401                 if (sourceInfo == NULL || targetInfo == NULL)
9402                         return;
9403
9404                 /*
9405                  * Skip this cast if all objects are from pg_
9406                  */
9407                 if ((funcInfo == NULL ||
9408                          strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9409                         strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9410                         strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9411                         return;
9412
9413                 /*
9414                  * Skip cast if function isn't from pg_ and is not to be dumped.
9415                  */
9416                 if (funcInfo &&
9417                         strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9418                         !funcInfo->dobj.dump)
9419                         return;
9420
9421                 /*
9422                  * Same for the source type
9423                  */
9424                 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9425                         !sourceInfo->dobj.dump)
9426                         return;
9427
9428                 /*
9429                  * and the target type.
9430                  */
9431                 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9432                         !targetInfo->dobj.dump)
9433                         return;
9434         }
9435
9436         /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9437         selectSourceSchema(fout, "pg_catalog");
9438
9439         defqry = createPQExpBuffer();
9440         delqry = createPQExpBuffer();
9441         labelq = createPQExpBuffer();
9442
9443         appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9444                                   getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9445                                   getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9446
9447         appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9448                                   getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9449                                   getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9450
9451         switch (cast->castmethod)
9452         {
9453                 case COERCION_METHOD_BINARY:
9454                         appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9455                         break;
9456                 case COERCION_METHOD_INOUT:
9457                         appendPQExpBuffer(defqry, "WITH INOUT");
9458                         break;
9459                 case COERCION_METHOD_FUNCTION:
9460                         if (funcInfo)
9461                         {
9462                                 char   *fsig = format_function_signature(fout, funcInfo, true);
9463
9464                                 /*
9465                                  * Always qualify the function name, in case it is not in
9466                                  * pg_catalog schema (format_function_signature won't qualify it).
9467                                  */
9468                                 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
9469                                                                   fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
9470                                 free(fsig);
9471                         }
9472                         else
9473                                 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
9474                         break;
9475                 default:
9476                         write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9477         }
9478
9479         if (cast->castcontext == 'a')
9480                 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9481         else if (cast->castcontext == 'i')
9482                 appendPQExpBuffer(defqry, " AS IMPLICIT");
9483         appendPQExpBuffer(defqry, ";\n");
9484
9485         appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9486                                   getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9487                                   getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9488
9489         if (binary_upgrade)
9490                 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9491
9492         ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9493                                  labelq->data,
9494                                  "pg_catalog", NULL, "",
9495                                  false, "CAST", SECTION_PRE_DATA,
9496                                  defqry->data, delqry->data, NULL,
9497                                  cast->dobj.dependencies, cast->dobj.nDeps,
9498                                  NULL, NULL);
9499
9500         /* Dump Cast Comments */
9501         dumpComment(fout, labelq->data,
9502                                 NULL, "",
9503                                 cast->dobj.catId, 0, cast->dobj.dumpId);
9504
9505         destroyPQExpBuffer(defqry);
9506         destroyPQExpBuffer(delqry);
9507         destroyPQExpBuffer(labelq);
9508 }
9509
9510 /*
9511  * dumpOpr
9512  *        write out a single operator definition
9513  */
9514 static void
9515 dumpOpr(Archive *fout, OprInfo *oprinfo)
9516 {
9517         PQExpBuffer query;
9518         PQExpBuffer q;
9519         PQExpBuffer delq;
9520         PQExpBuffer labelq;
9521         PQExpBuffer oprid;
9522         PQExpBuffer details;
9523         const char *name;
9524         PGresult   *res;
9525         int                     i_oprkind;
9526         int                     i_oprcode;
9527         int                     i_oprleft;
9528         int                     i_oprright;
9529         int                     i_oprcom;
9530         int                     i_oprnegate;
9531         int                     i_oprrest;
9532         int                     i_oprjoin;
9533         int                     i_oprcanmerge;
9534         int                     i_oprcanhash;
9535         char       *oprkind;
9536         char       *oprcode;
9537         char       *oprleft;
9538         char       *oprright;
9539         char       *oprcom;
9540         char       *oprnegate;
9541         char       *oprrest;
9542         char       *oprjoin;
9543         char       *oprcanmerge;
9544         char       *oprcanhash;
9545
9546         /* Skip if not to be dumped */
9547         if (!oprinfo->dobj.dump || dataOnly)
9548                 return;
9549
9550         /*
9551          * some operators are invalid because they were the result of user
9552          * defining operators before commutators exist
9553          */
9554         if (!OidIsValid(oprinfo->oprcode))
9555                 return;
9556
9557         query = createPQExpBuffer();
9558         q = createPQExpBuffer();
9559         delq = createPQExpBuffer();
9560         labelq = createPQExpBuffer();
9561         oprid = createPQExpBuffer();
9562         details = createPQExpBuffer();
9563
9564         /* Make sure we are in proper schema so regoperator works correctly */
9565         selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
9566
9567         if (fout->remoteVersion >= 80300)
9568         {
9569                 appendPQExpBuffer(query, "SELECT oprkind, "
9570                                                   "oprcode::pg_catalog.regprocedure, "
9571                                                   "oprleft::pg_catalog.regtype, "
9572                                                   "oprright::pg_catalog.regtype, "
9573                                                   "oprcom::pg_catalog.regoperator, "
9574                                                   "oprnegate::pg_catalog.regoperator, "
9575                                                   "oprrest::pg_catalog.regprocedure, "
9576                                                   "oprjoin::pg_catalog.regprocedure, "
9577                                                   "oprcanmerge, oprcanhash "
9578                                                   "FROM pg_catalog.pg_operator "
9579                                                   "WHERE oid = '%u'::pg_catalog.oid",
9580                                                   oprinfo->dobj.catId.oid);
9581         }
9582         else if (fout->remoteVersion >= 70300)
9583         {
9584                 appendPQExpBuffer(query, "SELECT oprkind, "
9585                                                   "oprcode::pg_catalog.regprocedure, "
9586                                                   "oprleft::pg_catalog.regtype, "
9587                                                   "oprright::pg_catalog.regtype, "
9588                                                   "oprcom::pg_catalog.regoperator, "
9589                                                   "oprnegate::pg_catalog.regoperator, "
9590                                                   "oprrest::pg_catalog.regprocedure, "
9591                                                   "oprjoin::pg_catalog.regprocedure, "
9592                                                   "(oprlsortop != 0) AS oprcanmerge, "
9593                                                   "oprcanhash "
9594                                                   "FROM pg_catalog.pg_operator "
9595                                                   "WHERE oid = '%u'::pg_catalog.oid",
9596                                                   oprinfo->dobj.catId.oid);
9597         }
9598         else if (fout->remoteVersion >= 70100)
9599         {
9600                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9601                                                   "CASE WHEN oprleft = 0 THEN '-' "
9602                                                   "ELSE format_type(oprleft, NULL) END AS oprleft, "
9603                                                   "CASE WHEN oprright = 0 THEN '-' "
9604                                                   "ELSE format_type(oprright, NULL) END AS oprright, "
9605                                                   "oprcom, oprnegate, oprrest, oprjoin, "
9606                                                   "(oprlsortop != 0) AS oprcanmerge, "
9607                                                   "oprcanhash "
9608                                                   "FROM pg_operator "
9609                                                   "WHERE oid = '%u'::oid",
9610                                                   oprinfo->dobj.catId.oid);
9611         }
9612         else
9613         {
9614                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9615                                                   "CASE WHEN oprleft = 0 THEN '-'::name "
9616                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
9617                                                   "CASE WHEN oprright = 0 THEN '-'::name "
9618                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
9619                                                   "oprcom, oprnegate, oprrest, oprjoin, "
9620                                                   "(oprlsortop != 0) AS oprcanmerge, "
9621                                                   "oprcanhash "
9622                                                   "FROM pg_operator "
9623                                                   "WHERE oid = '%u'::oid",
9624                                                   oprinfo->dobj.catId.oid);
9625         }
9626
9627         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9628
9629         i_oprkind = PQfnumber(res, "oprkind");
9630         i_oprcode = PQfnumber(res, "oprcode");
9631         i_oprleft = PQfnumber(res, "oprleft");
9632         i_oprright = PQfnumber(res, "oprright");
9633         i_oprcom = PQfnumber(res, "oprcom");
9634         i_oprnegate = PQfnumber(res, "oprnegate");
9635         i_oprrest = PQfnumber(res, "oprrest");
9636         i_oprjoin = PQfnumber(res, "oprjoin");
9637         i_oprcanmerge = PQfnumber(res, "oprcanmerge");
9638         i_oprcanhash = PQfnumber(res, "oprcanhash");
9639
9640         oprkind = PQgetvalue(res, 0, i_oprkind);
9641         oprcode = PQgetvalue(res, 0, i_oprcode);
9642         oprleft = PQgetvalue(res, 0, i_oprleft);
9643         oprright = PQgetvalue(res, 0, i_oprright);
9644         oprcom = PQgetvalue(res, 0, i_oprcom);
9645         oprnegate = PQgetvalue(res, 0, i_oprnegate);
9646         oprrest = PQgetvalue(res, 0, i_oprrest);
9647         oprjoin = PQgetvalue(res, 0, i_oprjoin);
9648         oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
9649         oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
9650
9651         appendPQExpBuffer(details, "    PROCEDURE = %s",
9652                                           convertRegProcReference(fout, oprcode));
9653
9654         appendPQExpBuffer(oprid, "%s (",
9655                                           oprinfo->dobj.name);
9656
9657         /*
9658          * right unary means there's a left arg and left unary means there's a
9659          * right arg
9660          */
9661         if (strcmp(oprkind, "r") == 0 ||
9662                 strcmp(oprkind, "b") == 0)
9663         {
9664                 if (fout->remoteVersion >= 70100)
9665                         name = oprleft;
9666                 else
9667                         name = fmtId(oprleft);
9668                 appendPQExpBuffer(details, ",\n    LEFTARG = %s", name);
9669                 appendPQExpBuffer(oprid, "%s", name);
9670         }
9671         else
9672                 appendPQExpBuffer(oprid, "NONE");
9673
9674         if (strcmp(oprkind, "l") == 0 ||
9675                 strcmp(oprkind, "b") == 0)
9676         {
9677                 if (fout->remoteVersion >= 70100)
9678                         name = oprright;
9679                 else
9680                         name = fmtId(oprright);
9681                 appendPQExpBuffer(details, ",\n    RIGHTARG = %s", name);
9682                 appendPQExpBuffer(oprid, ", %s)", name);
9683         }
9684         else
9685                 appendPQExpBuffer(oprid, ", NONE)");
9686
9687         name = convertOperatorReference(fout, oprcom);
9688         if (name)
9689                 appendPQExpBuffer(details, ",\n    COMMUTATOR = %s", name);
9690
9691         name = convertOperatorReference(fout, oprnegate);
9692         if (name)
9693                 appendPQExpBuffer(details, ",\n    NEGATOR = %s", name);
9694
9695         if (strcmp(oprcanmerge, "t") == 0)
9696                 appendPQExpBuffer(details, ",\n    MERGES");
9697
9698         if (strcmp(oprcanhash, "t") == 0)
9699                 appendPQExpBuffer(details, ",\n    HASHES");
9700
9701         name = convertRegProcReference(fout, oprrest);
9702         if (name)
9703                 appendPQExpBuffer(details, ",\n    RESTRICT = %s", name);
9704
9705         name = convertRegProcReference(fout, oprjoin);
9706         if (name)
9707                 appendPQExpBuffer(details, ",\n    JOIN = %s", name);
9708
9709         /*
9710          * DROP must be fully qualified in case same name appears in pg_catalog
9711          */
9712         appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
9713                                           fmtId(oprinfo->dobj.namespace->dobj.name),
9714                                           oprid->data);
9715
9716         appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
9717                                           oprinfo->dobj.name, details->data);
9718
9719         appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
9720
9721         if (binary_upgrade)
9722                 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
9723
9724         ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
9725                                  oprinfo->dobj.name,
9726                                  oprinfo->dobj.namespace->dobj.name,
9727                                  NULL,
9728                                  oprinfo->rolname,
9729                                  false, "OPERATOR", SECTION_PRE_DATA,
9730                                  q->data, delq->data, NULL,
9731                                  oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
9732                                  NULL, NULL);
9733
9734         /* Dump Operator Comments */
9735         dumpComment(fout, labelq->data,
9736                                 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
9737                                 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
9738
9739         PQclear(res);
9740
9741         destroyPQExpBuffer(query);
9742         destroyPQExpBuffer(q);
9743         destroyPQExpBuffer(delq);
9744         destroyPQExpBuffer(labelq);
9745         destroyPQExpBuffer(oprid);
9746         destroyPQExpBuffer(details);
9747 }
9748
9749 /*
9750  * Convert a function reference obtained from pg_operator
9751  *
9752  * Returns what to print, or NULL if function references is InvalidOid
9753  *
9754  * In 7.3 the input is a REGPROCEDURE display; we have to strip the
9755  * argument-types part.  In prior versions, the input is a REGPROC display.
9756  */
9757 static const char *
9758 convertRegProcReference(Archive *fout, const char *proc)
9759 {
9760         /* In all cases "-" means a null reference */
9761         if (strcmp(proc, "-") == 0)
9762                 return NULL;
9763
9764         if (fout->remoteVersion >= 70300)
9765         {
9766                 char       *name;
9767                 char       *paren;
9768                 bool            inquote;
9769
9770                 name = pg_strdup(proc);
9771                 /* find non-double-quoted left paren */
9772                 inquote = false;
9773                 for (paren = name; *paren; paren++)
9774                 {
9775                         if (*paren == '(' && !inquote)
9776                         {
9777                                 *paren = '\0';
9778                                 break;
9779                         }
9780                         if (*paren == '"')
9781                                 inquote = !inquote;
9782                 }
9783                 return name;
9784         }
9785
9786         /* REGPROC before 7.3 does not quote its result */
9787         return fmtId(proc);
9788 }
9789
9790 /*
9791  * Convert an operator cross-reference obtained from pg_operator
9792  *
9793  * Returns what to print, or NULL to print nothing
9794  *
9795  * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
9796  * argument-types part, and add OPERATOR() decoration if the name is
9797  * schema-qualified.  In older versions, the input is just a numeric OID,
9798  * which we search our operator list for.
9799  */
9800 static const char *
9801 convertOperatorReference(Archive *fout, const char *opr)
9802 {
9803         OprInfo    *oprInfo;
9804
9805         /* In all cases "0" means a null reference */
9806         if (strcmp(opr, "0") == 0)
9807                 return NULL;
9808
9809         if (fout->remoteVersion >= 70300)
9810         {
9811                 char       *name;
9812                 char       *oname;
9813                 char       *ptr;
9814                 bool            inquote;
9815                 bool            sawdot;
9816
9817                 name = pg_strdup(opr);
9818                 /* find non-double-quoted left paren, and check for non-quoted dot */
9819                 inquote = false;
9820                 sawdot = false;
9821                 for (ptr = name; *ptr; ptr++)
9822                 {
9823                         if (*ptr == '"')
9824                                 inquote = !inquote;
9825                         else if (*ptr == '.' && !inquote)
9826                                 sawdot = true;
9827                         else if (*ptr == '(' && !inquote)
9828                         {
9829                                 *ptr = '\0';
9830                                 break;
9831                         }
9832                 }
9833                 /* If not schema-qualified, don't need to add OPERATOR() */
9834                 if (!sawdot)
9835                         return name;
9836                 oname = pg_malloc(strlen(name) + 11);
9837                 sprintf(oname, "OPERATOR(%s)", name);
9838                 free(name);
9839                 return oname;
9840         }
9841
9842         oprInfo = findOprByOid(atooid(opr));
9843         if (oprInfo == NULL)
9844         {
9845                 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
9846                                   opr);
9847                 return NULL;
9848         }
9849         return oprInfo->dobj.name;
9850 }
9851
9852 /*
9853  * Convert a function OID obtained from pg_ts_parser or pg_ts_template
9854  *
9855  * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
9856  * argument lists of these functions are predetermined.  Note that the
9857  * caller should ensure we are in the proper schema, because the results
9858  * are search path dependent!
9859  */
9860 static const char *
9861 convertTSFunction(Archive *fout, Oid funcOid)
9862 {
9863         char       *result;
9864         char            query[128];
9865         PGresult   *res;
9866
9867         snprintf(query, sizeof(query),
9868                          "SELECT '%u'::pg_catalog.regproc", funcOid);
9869         res = ExecuteSqlQueryForSingleRow(fout, query);
9870
9871         result = pg_strdup(PQgetvalue(res, 0, 0));
9872
9873         PQclear(res);
9874
9875         return result;
9876 }
9877
9878
9879 /*
9880  * dumpOpclass
9881  *        write out a single operator class definition
9882  */
9883 static void
9884 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
9885 {
9886         PQExpBuffer query;
9887         PQExpBuffer q;
9888         PQExpBuffer delq;
9889         PQExpBuffer labelq;
9890         PGresult   *res;
9891         int                     ntups;
9892         int                     i_opcintype;
9893         int                     i_opckeytype;
9894         int                     i_opcdefault;
9895         int                     i_opcfamily;
9896         int                     i_opcfamilyname;
9897         int                     i_opcfamilynsp;
9898         int                     i_amname;
9899         int                     i_amopstrategy;
9900         int                     i_amopreqcheck;
9901         int                     i_amopopr;
9902         int                     i_sortfamily;
9903         int                     i_sortfamilynsp;
9904         int                     i_amprocnum;
9905         int                     i_amproc;
9906         int                     i_amproclefttype;
9907         int                     i_amprocrighttype;
9908         char       *opcintype;
9909         char       *opckeytype;
9910         char       *opcdefault;
9911         char       *opcfamily;
9912         char       *opcfamilyname;
9913         char       *opcfamilynsp;
9914         char       *amname;
9915         char       *amopstrategy;
9916         char       *amopreqcheck;
9917         char       *amopopr;
9918         char       *sortfamily;
9919         char       *sortfamilynsp;
9920         char       *amprocnum;
9921         char       *amproc;
9922         char       *amproclefttype;
9923         char       *amprocrighttype;
9924         bool            needComma;
9925         int                     i;
9926
9927         /* Skip if not to be dumped */
9928         if (!opcinfo->dobj.dump || dataOnly)
9929                 return;
9930
9931         /*
9932          * XXX currently we do not implement dumping of operator classes from
9933          * pre-7.3 databases.  This could be done but it seems not worth the
9934          * trouble.
9935          */
9936         if (fout->remoteVersion < 70300)
9937                 return;
9938
9939         query = createPQExpBuffer();
9940         q = createPQExpBuffer();
9941         delq = createPQExpBuffer();
9942         labelq = createPQExpBuffer();
9943
9944         /* Make sure we are in proper schema so regoperator works correctly */
9945         selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
9946
9947         /* Get additional fields from the pg_opclass row */
9948         if (fout->remoteVersion >= 80300)
9949         {
9950                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9951                                                   "opckeytype::pg_catalog.regtype, "
9952                                                   "opcdefault, opcfamily, "
9953                                                   "opfname AS opcfamilyname, "
9954                                                   "nspname AS opcfamilynsp, "
9955                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
9956                                                   "FROM pg_catalog.pg_opclass c "
9957                                    "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
9958                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
9959                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
9960                                                   opcinfo->dobj.catId.oid);
9961         }
9962         else
9963         {
9964                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9965                                                   "opckeytype::pg_catalog.regtype, "
9966                                                   "opcdefault, NULL AS opcfamily, "
9967                                                   "NULL AS opcfamilyname, "
9968                                                   "NULL AS opcfamilynsp, "
9969                 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
9970                                                   "FROM pg_catalog.pg_opclass "
9971                                                   "WHERE oid = '%u'::pg_catalog.oid",
9972                                                   opcinfo->dobj.catId.oid);
9973         }
9974
9975         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9976
9977         i_opcintype = PQfnumber(res, "opcintype");
9978         i_opckeytype = PQfnumber(res, "opckeytype");
9979         i_opcdefault = PQfnumber(res, "opcdefault");
9980         i_opcfamily = PQfnumber(res, "opcfamily");
9981         i_opcfamilyname = PQfnumber(res, "opcfamilyname");
9982         i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
9983         i_amname = PQfnumber(res, "amname");
9984
9985         opcintype = PQgetvalue(res, 0, i_opcintype);
9986         opckeytype = PQgetvalue(res, 0, i_opckeytype);
9987         opcdefault = PQgetvalue(res, 0, i_opcdefault);
9988         /* opcfamily will still be needed after we PQclear res */
9989         opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
9990         opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
9991         opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
9992         /* amname will still be needed after we PQclear res */
9993         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
9994
9995         /*
9996          * DROP must be fully qualified in case same name appears in pg_catalog
9997          */
9998         appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
9999                                           fmtId(opcinfo->dobj.namespace->dobj.name));
10000         appendPQExpBuffer(delq, ".%s",
10001                                           fmtId(opcinfo->dobj.name));
10002         appendPQExpBuffer(delq, " USING %s;\n",
10003                                           fmtId(amname));
10004
10005         /* Build the fixed portion of the CREATE command */
10006         appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n    ",
10007                                           fmtId(opcinfo->dobj.name));
10008         if (strcmp(opcdefault, "t") == 0)
10009                 appendPQExpBuffer(q, "DEFAULT ");
10010         appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10011                                           opcintype,
10012                                           fmtId(amname));
10013         if (strlen(opcfamilyname) > 0 &&
10014                 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10015                  strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10016         {
10017                 appendPQExpBuffer(q, " FAMILY ");
10018                 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10019                         appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10020                 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10021         }
10022         appendPQExpBuffer(q, " AS\n    ");
10023
10024         needComma = false;
10025
10026         if (strcmp(opckeytype, "-") != 0)
10027         {
10028                 appendPQExpBuffer(q, "STORAGE %s",
10029                                                   opckeytype);
10030                 needComma = true;
10031         }
10032
10033         PQclear(res);
10034
10035         /*
10036          * Now fetch and print the OPERATOR entries (pg_amop rows).
10037          *
10038          * Print only those opfamily members that are tied to the opclass by
10039          * pg_depend entries.
10040          *
10041          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10042          * older server's opclass in which it is used.  This is to avoid
10043          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10044          * older server and then reload into that old version.  This can go away
10045          * once 8.3 is so old as to not be of interest to anyone.
10046          */
10047         resetPQExpBuffer(query);
10048
10049         if (fout->remoteVersion >= 90100)
10050         {
10051                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10052                                                   "amopopr::pg_catalog.regoperator, "
10053                                                   "opfname AS sortfamily, "
10054                                                   "nspname AS sortfamilynsp "
10055                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10056                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10057                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10058                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10059                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10060                                                   "AND refobjid = '%u'::pg_catalog.oid "
10061                                                   "AND amopfamily = '%s'::pg_catalog.oid "
10062                                                   "ORDER BY amopstrategy",
10063                                                   opcinfo->dobj.catId.oid,
10064                                                   opcfamily);
10065         }
10066         else if (fout->remoteVersion >= 80400)
10067         {
10068                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10069                                                   "amopopr::pg_catalog.regoperator, "
10070                                                   "NULL AS sortfamily, "
10071                                                   "NULL AS sortfamilynsp "
10072                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10073                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10074                                                   "AND refobjid = '%u'::pg_catalog.oid "
10075                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10076                                                   "AND objid = ao.oid "
10077                                                   "ORDER BY amopstrategy",
10078                                                   opcinfo->dobj.catId.oid);
10079         }
10080         else if (fout->remoteVersion >= 80300)
10081         {
10082                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10083                                                   "amopopr::pg_catalog.regoperator, "
10084                                                   "NULL AS sortfamily, "
10085                                                   "NULL AS sortfamilynsp "
10086                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10087                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10088                                                   "AND refobjid = '%u'::pg_catalog.oid "
10089                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10090                                                   "AND objid = ao.oid "
10091                                                   "ORDER BY amopstrategy",
10092                                                   opcinfo->dobj.catId.oid);
10093         }
10094         else
10095         {
10096                 /*
10097                  * Here, we print all entries since there are no opfamilies and hence
10098                  * no loose operators to worry about.
10099                  */
10100                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10101                                                   "amopopr::pg_catalog.regoperator, "
10102                                                   "NULL AS sortfamily, "
10103                                                   "NULL AS sortfamilynsp "
10104                                                   "FROM pg_catalog.pg_amop "
10105                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10106                                                   "ORDER BY amopstrategy",
10107                                                   opcinfo->dobj.catId.oid);
10108         }
10109
10110         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10111
10112         ntups = PQntuples(res);
10113
10114         i_amopstrategy = PQfnumber(res, "amopstrategy");
10115         i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10116         i_amopopr = PQfnumber(res, "amopopr");
10117         i_sortfamily = PQfnumber(res, "sortfamily");
10118         i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10119
10120         for (i = 0; i < ntups; i++)
10121         {
10122                 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10123                 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10124                 amopopr = PQgetvalue(res, i, i_amopopr);
10125                 sortfamily = PQgetvalue(res, i, i_sortfamily);
10126                 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10127
10128                 if (needComma)
10129                         appendPQExpBuffer(q, " ,\n    ");
10130
10131                 appendPQExpBuffer(q, "OPERATOR %s %s",
10132                                                   amopstrategy, amopopr);
10133
10134                 if (strlen(sortfamily) > 0)
10135                 {
10136                         appendPQExpBuffer(q, " FOR ORDER BY ");
10137                         if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10138                                 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10139                         appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10140                 }
10141
10142                 if (strcmp(amopreqcheck, "t") == 0)
10143                         appendPQExpBuffer(q, " RECHECK");
10144
10145                 needComma = true;
10146         }
10147
10148         PQclear(res);
10149
10150         /*
10151          * Now fetch and print the FUNCTION entries (pg_amproc rows).
10152          *
10153          * Print only those opfamily members that are tied to the opclass by
10154          * pg_depend entries.
10155          *
10156          * We print the amproclefttype/amprocrighttype even though in most cases
10157          * the backend could deduce the right values, because of the corner case
10158          * of a btree sort support function for a cross-type comparison.  That's
10159          * only allowed in 9.2 and later, but for simplicity print them in all
10160          * versions that have the columns.
10161          */
10162         resetPQExpBuffer(query);
10163
10164         if (fout->remoteVersion >= 80300)
10165         {
10166                 appendPQExpBuffer(query, "SELECT amprocnum, "
10167                                                   "amproc::pg_catalog.regprocedure, "
10168                                                   "amproclefttype::pg_catalog.regtype, "
10169                                                   "amprocrighttype::pg_catalog.regtype "
10170                                                 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10171                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10172                                                   "AND refobjid = '%u'::pg_catalog.oid "
10173                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10174                                                   "AND objid = ap.oid "
10175                                                   "ORDER BY amprocnum",
10176                                                   opcinfo->dobj.catId.oid);
10177         }
10178         else
10179         {
10180                 appendPQExpBuffer(query, "SELECT amprocnum, "
10181                                                   "amproc::pg_catalog.regprocedure, "
10182                                                   "'' AS amproclefttype, "
10183                                                   "'' AS amprocrighttype "
10184                                                   "FROM pg_catalog.pg_amproc "
10185                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10186                                                   "ORDER BY amprocnum",
10187                                                   opcinfo->dobj.catId.oid);
10188         }
10189
10190         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10191
10192         ntups = PQntuples(res);
10193
10194         i_amprocnum = PQfnumber(res, "amprocnum");
10195         i_amproc = PQfnumber(res, "amproc");
10196         i_amproclefttype = PQfnumber(res, "amproclefttype");
10197         i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10198
10199         for (i = 0; i < ntups; i++)
10200         {
10201                 amprocnum = PQgetvalue(res, i, i_amprocnum);
10202                 amproc = PQgetvalue(res, i, i_amproc);
10203                 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10204                 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10205
10206                 if (needComma)
10207                         appendPQExpBuffer(q, " ,\n    ");
10208
10209                 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10210
10211                 if (*amproclefttype && *amprocrighttype)
10212                         appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10213
10214                 appendPQExpBuffer(q, " %s", amproc);
10215
10216                 needComma = true;
10217         }
10218
10219         PQclear(res);
10220
10221         appendPQExpBuffer(q, ";\n");
10222
10223         appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10224                                           fmtId(opcinfo->dobj.name));
10225         appendPQExpBuffer(labelq, " USING %s",
10226                                           fmtId(amname));
10227
10228         if (binary_upgrade)
10229                 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10230
10231         ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10232                                  opcinfo->dobj.name,
10233                                  opcinfo->dobj.namespace->dobj.name,
10234                                  NULL,
10235                                  opcinfo->rolname,
10236                                  false, "OPERATOR CLASS", SECTION_PRE_DATA,
10237                                  q->data, delq->data, NULL,
10238                                  opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
10239                                  NULL, NULL);
10240
10241         /* Dump Operator Class Comments */
10242         dumpComment(fout, labelq->data,
10243                                 NULL, opcinfo->rolname,
10244                                 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10245
10246         free(amname);
10247         destroyPQExpBuffer(query);
10248         destroyPQExpBuffer(q);
10249         destroyPQExpBuffer(delq);
10250         destroyPQExpBuffer(labelq);
10251 }
10252
10253 /*
10254  * dumpOpfamily
10255  *        write out a single operator family definition
10256  *
10257  * Note: this also dumps any "loose" operator members that aren't bound to a
10258  * specific opclass within the opfamily.
10259  */
10260 static void
10261 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10262 {
10263         PQExpBuffer query;
10264         PQExpBuffer q;
10265         PQExpBuffer delq;
10266         PQExpBuffer labelq;
10267         PGresult   *res;
10268         PGresult   *res_ops;
10269         PGresult   *res_procs;
10270         int                     ntups;
10271         int                     i_amname;
10272         int                     i_amopstrategy;
10273         int                     i_amopreqcheck;
10274         int                     i_amopopr;
10275         int                     i_sortfamily;
10276         int                     i_sortfamilynsp;
10277         int                     i_amprocnum;
10278         int                     i_amproc;
10279         int                     i_amproclefttype;
10280         int                     i_amprocrighttype;
10281         char       *amname;
10282         char       *amopstrategy;
10283         char       *amopreqcheck;
10284         char       *amopopr;
10285         char       *sortfamily;
10286         char       *sortfamilynsp;
10287         char       *amprocnum;
10288         char       *amproc;
10289         char       *amproclefttype;
10290         char       *amprocrighttype;
10291         bool            needComma;
10292         int                     i;
10293
10294         /* Skip if not to be dumped */
10295         if (!opfinfo->dobj.dump || dataOnly)
10296                 return;
10297
10298         /*
10299          * We want to dump the opfamily only if (1) it contains "loose" operators
10300          * or functions, or (2) it contains an opclass with a different name or
10301          * owner.  Otherwise it's sufficient to let it be created during creation
10302          * of the contained opclass, and not dumping it improves portability of
10303          * the dump.  Since we have to fetch the loose operators/funcs anyway, do
10304          * that first.
10305          */
10306
10307         query = createPQExpBuffer();
10308         q = createPQExpBuffer();
10309         delq = createPQExpBuffer();
10310         labelq = createPQExpBuffer();
10311
10312         /* Make sure we are in proper schema so regoperator works correctly */
10313         selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10314
10315         /*
10316          * Fetch only those opfamily members that are tied directly to the
10317          * opfamily by pg_depend entries.
10318          *
10319          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10320          * older server's opclass in which it is used.  This is to avoid
10321          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10322          * older server and then reload into that old version.  This can go away
10323          * once 8.3 is so old as to not be of interest to anyone.
10324          */
10325         if (fout->remoteVersion >= 90100)
10326         {
10327                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10328                                                   "amopopr::pg_catalog.regoperator, "
10329                                                   "opfname AS sortfamily, "
10330                                                   "nspname AS sortfamilynsp "
10331                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10332                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10333                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10334                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10335                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10336                                                   "AND refobjid = '%u'::pg_catalog.oid "
10337                                                   "AND amopfamily = '%u'::pg_catalog.oid "
10338                                                   "ORDER BY amopstrategy",
10339                                                   opfinfo->dobj.catId.oid,
10340                                                   opfinfo->dobj.catId.oid);
10341         }
10342         else if (fout->remoteVersion >= 80400)
10343         {
10344                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10345                                                   "amopopr::pg_catalog.regoperator, "
10346                                                   "NULL AS sortfamily, "
10347                                                   "NULL AS sortfamilynsp "
10348                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10349                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10350                                                   "AND refobjid = '%u'::pg_catalog.oid "
10351                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10352                                                   "AND objid = ao.oid "
10353                                                   "ORDER BY amopstrategy",
10354                                                   opfinfo->dobj.catId.oid);
10355         }
10356         else
10357         {
10358                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10359                                                   "amopopr::pg_catalog.regoperator, "
10360                                                   "NULL AS sortfamily, "
10361                                                   "NULL AS sortfamilynsp "
10362                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10363                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10364                                                   "AND refobjid = '%u'::pg_catalog.oid "
10365                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10366                                                   "AND objid = ao.oid "
10367                                                   "ORDER BY amopstrategy",
10368                                                   opfinfo->dobj.catId.oid);
10369         }
10370
10371         res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10372
10373         resetPQExpBuffer(query);
10374
10375         appendPQExpBuffer(query, "SELECT amprocnum, "
10376                                           "amproc::pg_catalog.regprocedure, "
10377                                           "amproclefttype::pg_catalog.regtype, "
10378                                           "amprocrighttype::pg_catalog.regtype "
10379                                           "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10380                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10381                                           "AND refobjid = '%u'::pg_catalog.oid "
10382                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10383                                           "AND objid = ap.oid "
10384                                           "ORDER BY amprocnum",
10385                                           opfinfo->dobj.catId.oid);
10386
10387         res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10388
10389         if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10390         {
10391                 /* No loose members, so check contained opclasses */
10392                 resetPQExpBuffer(query);
10393
10394                 appendPQExpBuffer(query, "SELECT 1 "
10395                                                   "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10396                                                   "WHERE f.oid = '%u'::pg_catalog.oid "
10397                         "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10398                                                   "AND refobjid = f.oid "
10399                                 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10400                                                   "AND objid = c.oid "
10401                                                   "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10402                                                   "LIMIT 1",
10403                                                   opfinfo->dobj.catId.oid);
10404
10405                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10406
10407                 if (PQntuples(res) == 0)
10408                 {
10409                         /* no need to dump it, so bail out */
10410                         PQclear(res);
10411                         PQclear(res_ops);
10412                         PQclear(res_procs);
10413                         destroyPQExpBuffer(query);
10414                         destroyPQExpBuffer(q);
10415                         destroyPQExpBuffer(delq);
10416                         destroyPQExpBuffer(labelq);
10417                         return;
10418                 }
10419
10420                 PQclear(res);
10421         }
10422
10423         /* Get additional fields from the pg_opfamily row */
10424         resetPQExpBuffer(query);
10425
10426         appendPQExpBuffer(query, "SELECT "
10427          "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10428                                           "FROM pg_catalog.pg_opfamily "
10429                                           "WHERE oid = '%u'::pg_catalog.oid",
10430                                           opfinfo->dobj.catId.oid);
10431
10432         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10433
10434         i_amname = PQfnumber(res, "amname");
10435
10436         /* amname will still be needed after we PQclear res */
10437         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10438
10439         /*
10440          * DROP must be fully qualified in case same name appears in pg_catalog
10441          */
10442         appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10443                                           fmtId(opfinfo->dobj.namespace->dobj.name));
10444         appendPQExpBuffer(delq, ".%s",
10445                                           fmtId(opfinfo->dobj.name));
10446         appendPQExpBuffer(delq, " USING %s;\n",
10447                                           fmtId(amname));
10448
10449         /* Build the fixed portion of the CREATE command */
10450         appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10451                                           fmtId(opfinfo->dobj.name));
10452         appendPQExpBuffer(q, " USING %s;\n",
10453                                           fmtId(amname));
10454
10455         PQclear(res);
10456
10457         /* Do we need an ALTER to add loose members? */
10458         if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10459         {
10460                 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10461                                                   fmtId(opfinfo->dobj.name));
10462                 appendPQExpBuffer(q, " USING %s ADD\n    ",
10463                                                   fmtId(amname));
10464
10465                 needComma = false;
10466
10467                 /*
10468                  * Now fetch and print the OPERATOR entries (pg_amop rows).
10469                  */
10470                 ntups = PQntuples(res_ops);
10471
10472                 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10473                 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10474                 i_amopopr = PQfnumber(res_ops, "amopopr");
10475                 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10476                 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10477
10478                 for (i = 0; i < ntups; i++)
10479                 {
10480                         amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10481                         amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10482                         amopopr = PQgetvalue(res_ops, i, i_amopopr);
10483                         sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10484                         sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10485
10486                         if (needComma)
10487                                 appendPQExpBuffer(q, " ,\n    ");
10488
10489                         appendPQExpBuffer(q, "OPERATOR %s %s",
10490                                                           amopstrategy, amopopr);
10491
10492                         if (strlen(sortfamily) > 0)
10493                         {
10494                                 appendPQExpBuffer(q, " FOR ORDER BY ");
10495                                 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10496                                         appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10497                                 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10498                         }
10499
10500                         if (strcmp(amopreqcheck, "t") == 0)
10501                                 appendPQExpBuffer(q, " RECHECK");
10502
10503                         needComma = true;
10504                 }
10505
10506                 /*
10507                  * Now fetch and print the FUNCTION entries (pg_amproc rows).
10508                  */
10509                 ntups = PQntuples(res_procs);
10510
10511                 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10512                 i_amproc = PQfnumber(res_procs, "amproc");
10513                 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10514                 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10515
10516                 for (i = 0; i < ntups; i++)
10517                 {
10518                         amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10519                         amproc = PQgetvalue(res_procs, i, i_amproc);
10520                         amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10521                         amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10522
10523                         if (needComma)
10524                                 appendPQExpBuffer(q, " ,\n    ");
10525
10526                         appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10527                                                           amprocnum, amproclefttype, amprocrighttype,
10528                                                           amproc);
10529
10530                         needComma = true;
10531                 }
10532
10533                 appendPQExpBuffer(q, ";\n");
10534         }
10535
10536         appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10537                                           fmtId(opfinfo->dobj.name));
10538         appendPQExpBuffer(labelq, " USING %s",
10539                                           fmtId(amname));
10540
10541         if (binary_upgrade)
10542                 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10543
10544         ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10545                                  opfinfo->dobj.name,
10546                                  opfinfo->dobj.namespace->dobj.name,
10547                                  NULL,
10548                                  opfinfo->rolname,
10549                                  false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10550                                  q->data, delq->data, NULL,
10551                                  opfinfo->dobj.dependencies, opfinfo->dobj.nDeps,
10552                                  NULL, NULL);
10553
10554         /* Dump Operator Family Comments */
10555         dumpComment(fout, labelq->data,
10556                                 NULL, opfinfo->rolname,
10557                                 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10558
10559         free(amname);
10560         PQclear(res_ops);
10561         PQclear(res_procs);
10562         destroyPQExpBuffer(query);
10563         destroyPQExpBuffer(q);
10564         destroyPQExpBuffer(delq);
10565         destroyPQExpBuffer(labelq);
10566 }
10567
10568 /*
10569  * dumpCollation
10570  *        write out a single collation definition
10571  */
10572 static void
10573 dumpCollation(Archive *fout, CollInfo *collinfo)
10574 {
10575         PQExpBuffer query;
10576         PQExpBuffer q;
10577         PQExpBuffer delq;
10578         PQExpBuffer labelq;
10579         PGresult   *res;
10580         int                     i_collcollate;
10581         int                     i_collctype;
10582         const char *collcollate;
10583         const char *collctype;
10584
10585         /* Skip if not to be dumped */
10586         if (!collinfo->dobj.dump || dataOnly)
10587                 return;
10588
10589         query = createPQExpBuffer();
10590         q = createPQExpBuffer();
10591         delq = createPQExpBuffer();
10592         labelq = createPQExpBuffer();
10593
10594         /* Make sure we are in proper schema */
10595         selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
10596
10597         /* Get conversion-specific details */
10598         appendPQExpBuffer(query, "SELECT "
10599                                           "collcollate, "
10600                                           "collctype "
10601                                           "FROM pg_catalog.pg_collation c "
10602                                           "WHERE c.oid = '%u'::pg_catalog.oid",
10603                                           collinfo->dobj.catId.oid);
10604
10605         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10606
10607         i_collcollate = PQfnumber(res, "collcollate");
10608         i_collctype = PQfnumber(res, "collctype");
10609
10610         collcollate = PQgetvalue(res, 0, i_collcollate);
10611         collctype = PQgetvalue(res, 0, i_collctype);
10612
10613         /*
10614          * DROP must be fully qualified in case same name appears in pg_catalog
10615          */
10616         appendPQExpBuffer(delq, "DROP COLLATION %s",
10617                                           fmtId(collinfo->dobj.namespace->dobj.name));
10618         appendPQExpBuffer(delq, ".%s;\n",
10619                                           fmtId(collinfo->dobj.name));
10620
10621         appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
10622                                           fmtId(collinfo->dobj.name));
10623         appendStringLiteralAH(q, collcollate, fout);
10624         appendPQExpBuffer(q, ", lc_ctype = ");
10625         appendStringLiteralAH(q, collctype, fout);
10626         appendPQExpBuffer(q, ");\n");
10627
10628         appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
10629
10630         if (binary_upgrade)
10631                 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
10632
10633         ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
10634                                  collinfo->dobj.name,
10635                                  collinfo->dobj.namespace->dobj.name,
10636                                  NULL,
10637                                  collinfo->rolname,
10638                                  false, "COLLATION", SECTION_PRE_DATA,
10639                                  q->data, delq->data, NULL,
10640                                  collinfo->dobj.dependencies, collinfo->dobj.nDeps,
10641                                  NULL, NULL);
10642
10643         /* Dump Collation Comments */
10644         dumpComment(fout, labelq->data,
10645                                 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
10646                                 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
10647
10648         PQclear(res);
10649
10650         destroyPQExpBuffer(query);
10651         destroyPQExpBuffer(q);
10652         destroyPQExpBuffer(delq);
10653         destroyPQExpBuffer(labelq);
10654 }
10655
10656 /*
10657  * dumpConversion
10658  *        write out a single conversion definition
10659  */
10660 static void
10661 dumpConversion(Archive *fout, ConvInfo *convinfo)
10662 {
10663         PQExpBuffer query;
10664         PQExpBuffer q;
10665         PQExpBuffer delq;
10666         PQExpBuffer labelq;
10667         PGresult   *res;
10668         int                     i_conforencoding;
10669         int                     i_contoencoding;
10670         int                     i_conproc;
10671         int                     i_condefault;
10672         const char *conforencoding;
10673         const char *contoencoding;
10674         const char *conproc;
10675         bool            condefault;
10676
10677         /* Skip if not to be dumped */
10678         if (!convinfo->dobj.dump || dataOnly)
10679                 return;
10680
10681         query = createPQExpBuffer();
10682         q = createPQExpBuffer();
10683         delq = createPQExpBuffer();
10684         labelq = createPQExpBuffer();
10685
10686         /* Make sure we are in proper schema */
10687         selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
10688
10689         /* Get conversion-specific details */
10690         appendPQExpBuffer(query, "SELECT "
10691                  "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
10692                    "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
10693                                           "conproc, condefault "
10694                                           "FROM pg_catalog.pg_conversion c "
10695                                           "WHERE c.oid = '%u'::pg_catalog.oid",
10696                                           convinfo->dobj.catId.oid);
10697
10698         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10699
10700         i_conforencoding = PQfnumber(res, "conforencoding");
10701         i_contoencoding = PQfnumber(res, "contoencoding");
10702         i_conproc = PQfnumber(res, "conproc");
10703         i_condefault = PQfnumber(res, "condefault");
10704
10705         conforencoding = PQgetvalue(res, 0, i_conforencoding);
10706         contoencoding = PQgetvalue(res, 0, i_contoencoding);
10707         conproc = PQgetvalue(res, 0, i_conproc);
10708         condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
10709
10710         /*
10711          * DROP must be fully qualified in case same name appears in pg_catalog
10712          */
10713         appendPQExpBuffer(delq, "DROP CONVERSION %s",
10714                                           fmtId(convinfo->dobj.namespace->dobj.name));
10715         appendPQExpBuffer(delq, ".%s;\n",
10716                                           fmtId(convinfo->dobj.name));
10717
10718         appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
10719                                           (condefault) ? "DEFAULT " : "",
10720                                           fmtId(convinfo->dobj.name));
10721         appendStringLiteralAH(q, conforencoding, fout);
10722         appendPQExpBuffer(q, " TO ");
10723         appendStringLiteralAH(q, contoencoding, fout);
10724         /* regproc is automatically quoted in 7.3 and above */
10725         appendPQExpBuffer(q, " FROM %s;\n", conproc);
10726
10727         appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
10728
10729         if (binary_upgrade)
10730                 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
10731
10732         ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
10733                                  convinfo->dobj.name,
10734                                  convinfo->dobj.namespace->dobj.name,
10735                                  NULL,
10736                                  convinfo->rolname,
10737                                  false, "CONVERSION", SECTION_PRE_DATA,
10738                                  q->data, delq->data, NULL,
10739                                  convinfo->dobj.dependencies, convinfo->dobj.nDeps,
10740                                  NULL, NULL);
10741
10742         /* Dump Conversion Comments */
10743         dumpComment(fout, labelq->data,
10744                                 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
10745                                 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
10746
10747         PQclear(res);
10748
10749         destroyPQExpBuffer(query);
10750         destroyPQExpBuffer(q);
10751         destroyPQExpBuffer(delq);
10752         destroyPQExpBuffer(labelq);
10753 }
10754
10755 /*
10756  * format_aggregate_signature: generate aggregate name and argument list
10757  *
10758  * The argument type names are qualified if needed.  The aggregate name
10759  * is never qualified.
10760  */
10761 static char *
10762 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
10763 {
10764         PQExpBufferData buf;
10765         int                     j;
10766
10767         initPQExpBuffer(&buf);
10768         if (honor_quotes)
10769                 appendPQExpBuffer(&buf, "%s",
10770                                                   fmtId(agginfo->aggfn.dobj.name));
10771         else
10772                 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
10773
10774         if (agginfo->aggfn.nargs == 0)
10775                 appendPQExpBuffer(&buf, "(*)");
10776         else
10777         {
10778                 appendPQExpBuffer(&buf, "(");
10779                 for (j = 0; j < agginfo->aggfn.nargs; j++)
10780                 {
10781                         char       *typname;
10782
10783                         typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
10784                                                                                    zeroAsOpaque);
10785
10786                         appendPQExpBuffer(&buf, "%s%s",
10787                                                           (j > 0) ? ", " : "",
10788                                                           typname);
10789                         free(typname);
10790                 }
10791                 appendPQExpBuffer(&buf, ")");
10792         }
10793         return buf.data;
10794 }
10795
10796 /*
10797  * dumpAgg
10798  *        write out a single aggregate definition
10799  */
10800 static void
10801 dumpAgg(Archive *fout, AggInfo *agginfo)
10802 {
10803         PQExpBuffer query;
10804         PQExpBuffer q;
10805         PQExpBuffer delq;
10806         PQExpBuffer labelq;
10807         PQExpBuffer details;
10808         char       *aggsig;
10809         char       *aggsig_tag;
10810         PGresult   *res;
10811         int                     i_aggtransfn;
10812         int                     i_aggfinalfn;
10813         int                     i_aggsortop;
10814         int                     i_aggtranstype;
10815         int                     i_agginitval;
10816         int                     i_convertok;
10817         const char *aggtransfn;
10818         const char *aggfinalfn;
10819         const char *aggsortop;
10820         const char *aggtranstype;
10821         const char *agginitval;
10822         bool            convertok;
10823
10824         /* Skip if not to be dumped */
10825         if (!agginfo->aggfn.dobj.dump || dataOnly)
10826                 return;
10827
10828         query = createPQExpBuffer();
10829         q = createPQExpBuffer();
10830         delq = createPQExpBuffer();
10831         labelq = createPQExpBuffer();
10832         details = createPQExpBuffer();
10833
10834         /* Make sure we are in proper schema */
10835         selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
10836
10837         /* Get aggregate-specific details */
10838         if (fout->remoteVersion >= 80100)
10839         {
10840                 appendPQExpBuffer(query, "SELECT aggtransfn, "
10841                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10842                                                   "aggsortop::pg_catalog.regoperator, "
10843                                                   "agginitval, "
10844                                                   "'t'::boolean AS convertok "
10845                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10846                                                   "WHERE a.aggfnoid = p.oid "
10847                                                   "AND p.oid = '%u'::pg_catalog.oid",
10848                                                   agginfo->aggfn.dobj.catId.oid);
10849         }
10850         else if (fout->remoteVersion >= 70300)
10851         {
10852                 appendPQExpBuffer(query, "SELECT aggtransfn, "
10853                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10854                                                   "0 AS aggsortop, "
10855                                                   "agginitval, "
10856                                                   "'t'::boolean AS convertok "
10857                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10858                                                   "WHERE a.aggfnoid = p.oid "
10859                                                   "AND p.oid = '%u'::pg_catalog.oid",
10860                                                   agginfo->aggfn.dobj.catId.oid);
10861         }
10862         else if (fout->remoteVersion >= 70100)
10863         {
10864                 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
10865                                                   "format_type(aggtranstype, NULL) AS aggtranstype, "
10866                                                   "0 AS aggsortop, "
10867                                                   "agginitval, "
10868                                                   "'t'::boolean AS convertok "
10869                                                   "FROM pg_aggregate "
10870                                                   "WHERE oid = '%u'::oid",
10871                                                   agginfo->aggfn.dobj.catId.oid);
10872         }
10873         else
10874         {
10875                 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
10876                                                   "aggfinalfn, "
10877                                                   "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
10878                                                   "0 AS aggsortop, "
10879                                                   "agginitval1 AS agginitval, "
10880                                                   "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
10881                                                   "FROM pg_aggregate "
10882                                                   "WHERE oid = '%u'::oid",
10883                                                   agginfo->aggfn.dobj.catId.oid);
10884         }
10885
10886         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10887
10888         i_aggtransfn = PQfnumber(res, "aggtransfn");
10889         i_aggfinalfn = PQfnumber(res, "aggfinalfn");
10890         i_aggsortop = PQfnumber(res, "aggsortop");
10891         i_aggtranstype = PQfnumber(res, "aggtranstype");
10892         i_agginitval = PQfnumber(res, "agginitval");
10893         i_convertok = PQfnumber(res, "convertok");
10894
10895         aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
10896         aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
10897         aggsortop = PQgetvalue(res, 0, i_aggsortop);
10898         aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
10899         agginitval = PQgetvalue(res, 0, i_agginitval);
10900         convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
10901
10902         aggsig = format_aggregate_signature(agginfo, fout, true);
10903         aggsig_tag = format_aggregate_signature(agginfo, fout, false);
10904
10905         if (!convertok)
10906         {
10907                 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
10908                                   aggsig);
10909                 return;
10910         }
10911
10912         if (fout->remoteVersion >= 70300)
10913         {
10914                 /* If using 7.3's regproc or regtype, data is already quoted */
10915                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
10916                                                   aggtransfn,
10917                                                   aggtranstype);
10918         }
10919         else if (fout->remoteVersion >= 70100)
10920         {
10921                 /* format_type quotes, regproc does not */
10922                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
10923                                                   fmtId(aggtransfn),
10924                                                   aggtranstype);
10925         }
10926         else
10927         {
10928                 /* need quotes all around */
10929                 appendPQExpBuffer(details, "    SFUNC = %s,\n",
10930                                                   fmtId(aggtransfn));
10931                 appendPQExpBuffer(details, "    STYPE = %s",
10932                                                   fmtId(aggtranstype));
10933         }
10934
10935         if (!PQgetisnull(res, 0, i_agginitval))
10936         {
10937                 appendPQExpBuffer(details, ",\n    INITCOND = ");
10938                 appendStringLiteralAH(details, agginitval, fout);
10939         }
10940
10941         if (strcmp(aggfinalfn, "-") != 0)
10942         {
10943                 appendPQExpBuffer(details, ",\n    FINALFUNC = %s",
10944                                                   aggfinalfn);
10945         }
10946
10947         aggsortop = convertOperatorReference(fout, aggsortop);
10948         if (aggsortop)
10949         {
10950                 appendPQExpBuffer(details, ",\n    SORTOP = %s",
10951                                                   aggsortop);
10952         }
10953
10954         /*
10955          * DROP must be fully qualified in case same name appears in pg_catalog
10956          */
10957         appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
10958                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
10959                                           aggsig);
10960
10961         appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
10962                                           aggsig, details->data);
10963
10964         appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
10965
10966         if (binary_upgrade)
10967                 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
10968
10969         ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
10970                                  aggsig_tag,
10971                                  agginfo->aggfn.dobj.namespace->dobj.name,
10972                                  NULL,
10973                                  agginfo->aggfn.rolname,
10974                                  false, "AGGREGATE", SECTION_PRE_DATA,
10975                                  q->data, delq->data, NULL,
10976                                  agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
10977                                  NULL, NULL);
10978
10979         /* Dump Aggregate Comments */
10980         dumpComment(fout, labelq->data,
10981                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
10982                                 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
10983         dumpSecLabel(fout, labelq->data,
10984                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
10985                                  agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
10986
10987         /*
10988          * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
10989          * command look like a function's GRANT; in particular this affects the
10990          * syntax for zero-argument aggregates.
10991          */
10992         free(aggsig);
10993         free(aggsig_tag);
10994
10995         aggsig = format_function_signature(fout, &agginfo->aggfn, true);
10996         aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
10997
10998         dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
10999                         "FUNCTION",
11000                         aggsig, NULL, aggsig_tag,
11001                         agginfo->aggfn.dobj.namespace->dobj.name,
11002                         agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11003
11004         free(aggsig);
11005         free(aggsig_tag);
11006
11007         PQclear(res);
11008
11009         destroyPQExpBuffer(query);
11010         destroyPQExpBuffer(q);
11011         destroyPQExpBuffer(delq);
11012         destroyPQExpBuffer(labelq);
11013         destroyPQExpBuffer(details);
11014 }
11015
11016 /*
11017  * dumpTSParser
11018  *        write out a single text search parser
11019  */
11020 static void
11021 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11022 {
11023         PQExpBuffer q;
11024         PQExpBuffer delq;
11025         PQExpBuffer labelq;
11026
11027         /* Skip if not to be dumped */
11028         if (!prsinfo->dobj.dump || dataOnly)
11029                 return;
11030
11031         q = createPQExpBuffer();
11032         delq = createPQExpBuffer();
11033         labelq = createPQExpBuffer();
11034
11035         /* Make sure we are in proper schema */
11036         selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11037
11038         appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11039                                           fmtId(prsinfo->dobj.name));
11040
11041         appendPQExpBuffer(q, "    START = %s,\n",
11042                                           convertTSFunction(fout, prsinfo->prsstart));
11043         appendPQExpBuffer(q, "    GETTOKEN = %s,\n",
11044                                           convertTSFunction(fout, prsinfo->prstoken));
11045         appendPQExpBuffer(q, "    END = %s,\n",
11046                                           convertTSFunction(fout, prsinfo->prsend));
11047         if (prsinfo->prsheadline != InvalidOid)
11048                 appendPQExpBuffer(q, "    HEADLINE = %s,\n",
11049                                                   convertTSFunction(fout, prsinfo->prsheadline));
11050         appendPQExpBuffer(q, "    LEXTYPES = %s );\n",
11051                                           convertTSFunction(fout, prsinfo->prslextype));
11052
11053         /*
11054          * DROP must be fully qualified in case same name appears in pg_catalog
11055          */
11056         appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11057                                           fmtId(prsinfo->dobj.namespace->dobj.name));
11058         appendPQExpBuffer(delq, ".%s;\n",
11059                                           fmtId(prsinfo->dobj.name));
11060
11061         appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11062                                           fmtId(prsinfo->dobj.name));
11063
11064         if (binary_upgrade)
11065                 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11066
11067         ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11068                                  prsinfo->dobj.name,
11069                                  prsinfo->dobj.namespace->dobj.name,
11070                                  NULL,
11071                                  "",
11072                                  false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11073                                  q->data, delq->data, NULL,
11074                                  prsinfo->dobj.dependencies, prsinfo->dobj.nDeps,
11075                                  NULL, NULL);
11076
11077         /* Dump Parser Comments */
11078         dumpComment(fout, labelq->data,
11079                                 NULL, "",
11080                                 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11081
11082         destroyPQExpBuffer(q);
11083         destroyPQExpBuffer(delq);
11084         destroyPQExpBuffer(labelq);
11085 }
11086
11087 /*
11088  * dumpTSDictionary
11089  *        write out a single text search dictionary
11090  */
11091 static void
11092 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11093 {
11094         PQExpBuffer q;
11095         PQExpBuffer delq;
11096         PQExpBuffer labelq;
11097         PQExpBuffer query;
11098         PGresult   *res;
11099         char       *nspname;
11100         char       *tmplname;
11101
11102         /* Skip if not to be dumped */
11103         if (!dictinfo->dobj.dump || dataOnly)
11104                 return;
11105
11106         q = createPQExpBuffer();
11107         delq = createPQExpBuffer();
11108         labelq = createPQExpBuffer();
11109         query = createPQExpBuffer();
11110
11111         /* Fetch name and namespace of the dictionary's template */
11112         selectSourceSchema(fout, "pg_catalog");
11113         appendPQExpBuffer(query, "SELECT nspname, tmplname "
11114                                           "FROM pg_ts_template p, pg_namespace n "
11115                                           "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11116                                           dictinfo->dicttemplate);
11117         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11118         nspname = PQgetvalue(res, 0, 0);
11119         tmplname = PQgetvalue(res, 0, 1);
11120
11121         /* Make sure we are in proper schema */
11122         selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11123
11124         appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11125                                           fmtId(dictinfo->dobj.name));
11126
11127         appendPQExpBuffer(q, "    TEMPLATE = ");
11128         if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11129                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11130         appendPQExpBuffer(q, "%s", fmtId(tmplname));
11131
11132         PQclear(res);
11133
11134         /* the dictinitoption can be dumped straight into the command */
11135         if (dictinfo->dictinitoption)
11136                 appendPQExpBuffer(q, ",\n    %s", dictinfo->dictinitoption);
11137
11138         appendPQExpBuffer(q, " );\n");
11139
11140         /*
11141          * DROP must be fully qualified in case same name appears in pg_catalog
11142          */
11143         appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11144                                           fmtId(dictinfo->dobj.namespace->dobj.name));
11145         appendPQExpBuffer(delq, ".%s;\n",
11146                                           fmtId(dictinfo->dobj.name));
11147
11148         appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11149                                           fmtId(dictinfo->dobj.name));
11150
11151         if (binary_upgrade)
11152                 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11153
11154         ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11155                                  dictinfo->dobj.name,
11156                                  dictinfo->dobj.namespace->dobj.name,
11157                                  NULL,
11158                                  dictinfo->rolname,
11159                                  false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11160                                  q->data, delq->data, NULL,
11161                                  dictinfo->dobj.dependencies, dictinfo->dobj.nDeps,
11162                                  NULL, NULL);
11163
11164         /* Dump Dictionary Comments */
11165         dumpComment(fout, labelq->data,
11166                                 NULL, dictinfo->rolname,
11167                                 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11168
11169         destroyPQExpBuffer(q);
11170         destroyPQExpBuffer(delq);
11171         destroyPQExpBuffer(labelq);
11172         destroyPQExpBuffer(query);
11173 }
11174
11175 /*
11176  * dumpTSTemplate
11177  *        write out a single text search template
11178  */
11179 static void
11180 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11181 {
11182         PQExpBuffer q;
11183         PQExpBuffer delq;
11184         PQExpBuffer labelq;
11185
11186         /* Skip if not to be dumped */
11187         if (!tmplinfo->dobj.dump || dataOnly)
11188                 return;
11189
11190         q = createPQExpBuffer();
11191         delq = createPQExpBuffer();
11192         labelq = createPQExpBuffer();
11193
11194         /* Make sure we are in proper schema */
11195         selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11196
11197         appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11198                                           fmtId(tmplinfo->dobj.name));
11199
11200         if (tmplinfo->tmplinit != InvalidOid)
11201                 appendPQExpBuffer(q, "    INIT = %s,\n",
11202                                                   convertTSFunction(fout, tmplinfo->tmplinit));
11203         appendPQExpBuffer(q, "    LEXIZE = %s );\n",
11204                                           convertTSFunction(fout, tmplinfo->tmpllexize));
11205
11206         /*
11207          * DROP must be fully qualified in case same name appears in pg_catalog
11208          */
11209         appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11210                                           fmtId(tmplinfo->dobj.namespace->dobj.name));
11211         appendPQExpBuffer(delq, ".%s;\n",
11212                                           fmtId(tmplinfo->dobj.name));
11213
11214         appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11215                                           fmtId(tmplinfo->dobj.name));
11216
11217         if (binary_upgrade)
11218                 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11219
11220         ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11221                                  tmplinfo->dobj.name,
11222                                  tmplinfo->dobj.namespace->dobj.name,
11223                                  NULL,
11224                                  "",
11225                                  false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11226                                  q->data, delq->data, NULL,
11227                                  tmplinfo->dobj.dependencies, tmplinfo->dobj.nDeps,
11228                                  NULL, NULL);
11229
11230         /* Dump Template Comments */
11231         dumpComment(fout, labelq->data,
11232                                 NULL, "",
11233                                 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11234
11235         destroyPQExpBuffer(q);
11236         destroyPQExpBuffer(delq);
11237         destroyPQExpBuffer(labelq);
11238 }
11239
11240 /*
11241  * dumpTSConfig
11242  *        write out a single text search configuration
11243  */
11244 static void
11245 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11246 {
11247         PQExpBuffer q;
11248         PQExpBuffer delq;
11249         PQExpBuffer labelq;
11250         PQExpBuffer query;
11251         PGresult   *res;
11252         char       *nspname;
11253         char       *prsname;
11254         int                     ntups,
11255                                 i;
11256         int                     i_tokenname;
11257         int                     i_dictname;
11258
11259         /* Skip if not to be dumped */
11260         if (!cfginfo->dobj.dump || dataOnly)
11261                 return;
11262
11263         q = createPQExpBuffer();
11264         delq = createPQExpBuffer();
11265         labelq = createPQExpBuffer();
11266         query = createPQExpBuffer();
11267
11268         /* Fetch name and namespace of the config's parser */
11269         selectSourceSchema(fout, "pg_catalog");
11270         appendPQExpBuffer(query, "SELECT nspname, prsname "
11271                                           "FROM pg_ts_parser p, pg_namespace n "
11272                                           "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11273                                           cfginfo->cfgparser);
11274         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11275         nspname = PQgetvalue(res, 0, 0);
11276         prsname = PQgetvalue(res, 0, 1);
11277
11278         /* Make sure we are in proper schema */
11279         selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11280
11281         appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11282                                           fmtId(cfginfo->dobj.name));
11283
11284         appendPQExpBuffer(q, "    PARSER = ");
11285         if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11286                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11287         appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11288
11289         PQclear(res);
11290
11291         resetPQExpBuffer(query);
11292         appendPQExpBuffer(query,
11293                                           "SELECT \n"
11294                                           "  ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11295                                           "    WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11296                                           "  m.mapdict::pg_catalog.regdictionary AS dictname \n"
11297                                           "FROM pg_catalog.pg_ts_config_map AS m \n"
11298                                           "WHERE m.mapcfg = '%u' \n"
11299                                           "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11300                                           cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11301
11302         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11303         ntups = PQntuples(res);
11304
11305         i_tokenname = PQfnumber(res, "tokenname");
11306         i_dictname = PQfnumber(res, "dictname");
11307
11308         for (i = 0; i < ntups; i++)
11309         {
11310                 char       *tokenname = PQgetvalue(res, i, i_tokenname);
11311                 char       *dictname = PQgetvalue(res, i, i_dictname);
11312
11313                 if (i == 0 ||
11314                         strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11315                 {
11316                         /* starting a new token type, so start a new command */
11317                         if (i > 0)
11318                                 appendPQExpBuffer(q, ";\n");
11319                         appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11320                                                           fmtId(cfginfo->dobj.name));
11321                         /* tokenname needs quoting, dictname does NOT */
11322                         appendPQExpBuffer(q, "    ADD MAPPING FOR %s WITH %s",
11323                                                           fmtId(tokenname), dictname);
11324                 }
11325                 else
11326                         appendPQExpBuffer(q, ", %s", dictname);
11327         }
11328
11329         if (ntups > 0)
11330                 appendPQExpBuffer(q, ";\n");
11331
11332         PQclear(res);
11333
11334         /*
11335          * DROP must be fully qualified in case same name appears in pg_catalog
11336          */
11337         appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11338                                           fmtId(cfginfo->dobj.namespace->dobj.name));
11339         appendPQExpBuffer(delq, ".%s;\n",
11340                                           fmtId(cfginfo->dobj.name));
11341
11342         appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11343                                           fmtId(cfginfo->dobj.name));
11344
11345         if (binary_upgrade)
11346                 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11347
11348         ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11349                                  cfginfo->dobj.name,
11350                                  cfginfo->dobj.namespace->dobj.name,
11351                                  NULL,
11352                                  cfginfo->rolname,
11353                                  false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11354                                  q->data, delq->data, NULL,
11355                                  cfginfo->dobj.dependencies, cfginfo->dobj.nDeps,
11356                                  NULL, NULL);
11357
11358         /* Dump Configuration Comments */
11359         dumpComment(fout, labelq->data,
11360                                 NULL, cfginfo->rolname,
11361                                 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11362
11363         destroyPQExpBuffer(q);
11364         destroyPQExpBuffer(delq);
11365         destroyPQExpBuffer(labelq);
11366         destroyPQExpBuffer(query);
11367 }
11368
11369 /*
11370  * dumpForeignDataWrapper
11371  *        write out a single foreign-data wrapper definition
11372  */
11373 static void
11374 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11375 {
11376         PQExpBuffer q;
11377         PQExpBuffer delq;
11378         PQExpBuffer labelq;
11379         char       *qfdwname;
11380
11381         /* Skip if not to be dumped */
11382         if (!fdwinfo->dobj.dump || dataOnly)
11383                 return;
11384
11385         /*
11386          * FDWs that belong to an extension are dumped based on their "dump"
11387          * field. Otherwise omit them if we are only dumping some specific object.
11388          */
11389         if (!fdwinfo->dobj.ext_member)
11390                 if (!include_everything)
11391                         return;
11392
11393         q = createPQExpBuffer();
11394         delq = createPQExpBuffer();
11395         labelq = createPQExpBuffer();
11396
11397         qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11398
11399         appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11400                                           qfdwname);
11401
11402         if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11403                 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11404
11405         if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11406                 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11407
11408         if (strlen(fdwinfo->fdwoptions) > 0)
11409                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", fdwinfo->fdwoptions);
11410
11411         appendPQExpBuffer(q, ";\n");
11412
11413         appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11414                                           qfdwname);
11415
11416         appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11417                                           qfdwname);
11418
11419         if (binary_upgrade)
11420                 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11421
11422         ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11423                                  fdwinfo->dobj.name,
11424                                  NULL,
11425                                  NULL,
11426                                  fdwinfo->rolname,
11427                                  false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11428                                  q->data, delq->data, NULL,
11429                                  fdwinfo->dobj.dependencies, fdwinfo->dobj.nDeps,
11430                                  NULL, NULL);
11431
11432         /* Handle the ACL */
11433         dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11434                         "FOREIGN DATA WRAPPER",
11435                         qfdwname, NULL, fdwinfo->dobj.name,
11436                         NULL, fdwinfo->rolname,
11437                         fdwinfo->fdwacl);
11438
11439         /* Dump Foreign Data Wrapper Comments */
11440         dumpComment(fout, labelq->data,
11441                                 NULL, fdwinfo->rolname,
11442                                 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11443
11444         free(qfdwname);
11445
11446         destroyPQExpBuffer(q);
11447         destroyPQExpBuffer(delq);
11448         destroyPQExpBuffer(labelq);
11449 }
11450
11451 /*
11452  * dumpForeignServer
11453  *        write out a foreign server definition
11454  */
11455 static void
11456 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11457 {
11458         PQExpBuffer q;
11459         PQExpBuffer delq;
11460         PQExpBuffer labelq;
11461         PQExpBuffer query;
11462         PGresult   *res;
11463         char       *qsrvname;
11464         char       *fdwname;
11465
11466         /* Skip if not to be dumped */
11467         if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11468                 return;
11469
11470         q = createPQExpBuffer();
11471         delq = createPQExpBuffer();
11472         labelq = createPQExpBuffer();
11473         query = createPQExpBuffer();
11474
11475         qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11476
11477         /* look up the foreign-data wrapper */
11478         selectSourceSchema(fout, "pg_catalog");
11479         appendPQExpBuffer(query, "SELECT fdwname "
11480                                           "FROM pg_foreign_data_wrapper w "
11481                                           "WHERE w.oid = '%u'",
11482                                           srvinfo->srvfdw);
11483         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11484         fdwname = PQgetvalue(res, 0, 0);
11485
11486         appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11487         if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11488         {
11489                 appendPQExpBuffer(q, " TYPE ");
11490                 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11491         }
11492         if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11493         {
11494                 appendPQExpBuffer(q, " VERSION ");
11495                 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11496         }
11497
11498         appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11499         appendPQExpBuffer(q, "%s", fmtId(fdwname));
11500
11501         if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11502                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", srvinfo->srvoptions);
11503
11504         appendPQExpBuffer(q, ";\n");
11505
11506         appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11507                                           qsrvname);
11508
11509         appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11510
11511         if (binary_upgrade)
11512                 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11513
11514         ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11515                                  srvinfo->dobj.name,
11516                                  NULL,
11517                                  NULL,
11518                                  srvinfo->rolname,
11519                                  false, "SERVER", SECTION_PRE_DATA,
11520                                  q->data, delq->data, NULL,
11521                                  srvinfo->dobj.dependencies, srvinfo->dobj.nDeps,
11522                                  NULL, NULL);
11523
11524         /* Handle the ACL */
11525         dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11526                         "FOREIGN SERVER",
11527                         qsrvname, NULL, srvinfo->dobj.name,
11528                         NULL, srvinfo->rolname,
11529                         srvinfo->srvacl);
11530
11531         /* Dump user mappings */
11532         dumpUserMappings(fout,
11533                                          srvinfo->dobj.name, NULL,
11534                                          srvinfo->rolname,
11535                                          srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11536
11537         /* Dump Foreign Server Comments */
11538         dumpComment(fout, labelq->data,
11539                                 NULL, srvinfo->rolname,
11540                                 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11541
11542         free(qsrvname);
11543
11544         destroyPQExpBuffer(q);
11545         destroyPQExpBuffer(delq);
11546         destroyPQExpBuffer(labelq);
11547 }
11548
11549 /*
11550  * dumpUserMappings
11551  *
11552  * This routine is used to dump any user mappings associated with the
11553  * server handed to this routine. Should be called after ArchiveEntry()
11554  * for the server.
11555  */
11556 static void
11557 dumpUserMappings(Archive *fout,
11558                                  const char *servername, const char *namespace,
11559                                  const char *owner,
11560                                  CatalogId catalogId, DumpId dumpId)
11561 {
11562         PQExpBuffer q;
11563         PQExpBuffer delq;
11564         PQExpBuffer query;
11565         PQExpBuffer tag;
11566         PGresult   *res;
11567         int                     ntups;
11568         int                     i_usename;
11569         int                     i_umoptions;
11570         int                     i;
11571
11572         q = createPQExpBuffer();
11573         tag = createPQExpBuffer();
11574         delq = createPQExpBuffer();
11575         query = createPQExpBuffer();
11576
11577         /*
11578          * We read from the publicly accessible view pg_user_mappings, so as not
11579          * to fail if run by a non-superuser.  Note that the view will show
11580          * umoptions as null if the user hasn't got privileges for the associated
11581          * server; this means that pg_dump will dump such a mapping, but with no
11582          * OPTIONS clause.      A possible alternative is to skip such mappings
11583          * altogether, but it's not clear that that's an improvement.
11584          */
11585         selectSourceSchema(fout, "pg_catalog");
11586
11587         appendPQExpBuffer(query,
11588                                           "SELECT usename, "
11589                                           "array_to_string(ARRAY("
11590                                           "SELECT quote_ident(option_name) || ' ' || "
11591                                           "quote_literal(option_value) "
11592                                           "FROM pg_options_to_table(umoptions) "
11593                                           "ORDER BY option_name"
11594                                           "), E',\n    ') AS umoptions "
11595                                           "FROM pg_user_mappings "
11596                                           "WHERE srvid = '%u' "
11597                                           "ORDER BY usename",
11598                                           catalogId.oid);
11599
11600         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11601
11602         ntups = PQntuples(res);
11603         i_usename = PQfnumber(res, "usename");
11604         i_umoptions = PQfnumber(res, "umoptions");
11605
11606         for (i = 0; i < ntups; i++)
11607         {
11608                 char       *usename;
11609                 char       *umoptions;
11610
11611                 usename = PQgetvalue(res, i, i_usename);
11612                 umoptions = PQgetvalue(res, i, i_umoptions);
11613
11614                 resetPQExpBuffer(q);
11615                 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
11616                 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
11617
11618                 if (umoptions && strlen(umoptions) > 0)
11619                         appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", umoptions);
11620
11621                 appendPQExpBuffer(q, ";\n");
11622
11623                 resetPQExpBuffer(delq);
11624                 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
11625                 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
11626
11627                 resetPQExpBuffer(tag);
11628                 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
11629                                                   usename, servername);
11630
11631                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11632                                          tag->data,
11633                                          namespace,
11634                                          NULL,
11635                                          owner, false,
11636                                          "USER MAPPING", SECTION_PRE_DATA,
11637                                          q->data, delq->data, NULL,
11638                                          &dumpId, 1,
11639                                          NULL, NULL);
11640         }
11641
11642         PQclear(res);
11643
11644         destroyPQExpBuffer(query);
11645         destroyPQExpBuffer(delq);
11646         destroyPQExpBuffer(q);
11647 }
11648
11649 /*
11650  * Write out default privileges information
11651  */
11652 static void
11653 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
11654 {
11655         PQExpBuffer q;
11656         PQExpBuffer tag;
11657         const char *type;
11658
11659         /* Skip if not to be dumped */
11660         if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
11661                 return;
11662
11663         q = createPQExpBuffer();
11664         tag = createPQExpBuffer();
11665
11666         switch (daclinfo->defaclobjtype)
11667         {
11668                 case DEFACLOBJ_RELATION:
11669                         type = "TABLES";
11670                         break;
11671                 case DEFACLOBJ_SEQUENCE:
11672                         type = "SEQUENCES";
11673                         break;
11674                 case DEFACLOBJ_FUNCTION:
11675                         type = "FUNCTIONS";
11676                         break;
11677                 default:
11678                         /* shouldn't get here */
11679                         exit_horribly(NULL,
11680                                                   "unknown object type (%d) in default privileges\n",
11681                                                   (int) daclinfo->defaclobjtype);
11682                         type = "";                      /* keep compiler quiet */
11683         }
11684
11685         appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
11686
11687         /* build the actual command(s) for this tuple */
11688         if (!buildDefaultACLCommands(type,
11689                                                                  daclinfo->dobj.namespace != NULL ?
11690                                                                  daclinfo->dobj.namespace->dobj.name : NULL,
11691                                                                  daclinfo->defaclacl,
11692                                                                  daclinfo->defaclrole,
11693                                                                  fout->remoteVersion,
11694                                                                  q))
11695                 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
11696                                           daclinfo->defaclacl);
11697
11698         ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
11699                                  tag->data,
11700            daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
11701                                  NULL,
11702                                  daclinfo->defaclrole,
11703                                  false, "DEFAULT ACL", SECTION_NONE,
11704                                  q->data, "", NULL,
11705                                  daclinfo->dobj.dependencies, daclinfo->dobj.nDeps,
11706                                  NULL, NULL);
11707
11708         destroyPQExpBuffer(tag);
11709         destroyPQExpBuffer(q);
11710 }
11711
11712 /*----------
11713  * Write out grant/revoke information
11714  *
11715  * 'objCatId' is the catalog ID of the underlying object.
11716  * 'objDumpId' is the dump ID of the underlying object.
11717  * 'type' must be one of
11718  *              TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
11719  *              FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
11720  * 'name' is the formatted name of the object.  Must be quoted etc. already.
11721  * 'subname' is the formatted name of the sub-object, if any.  Must be quoted.
11722  * 'tag' is the tag for the archive entry (typ. unquoted name of object).
11723  * 'nspname' is the namespace the object is in (NULL if none).
11724  * 'owner' is the owner, NULL if there is no owner (for languages).
11725  * 'acls' is the string read out of the fooacl system catalog field;
11726  *              it will be parsed here.
11727  *----------
11728  */
11729 static void
11730 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
11731                 const char *type, const char *name, const char *subname,
11732                 const char *tag, const char *nspname, const char *owner,
11733                 const char *acls)
11734 {
11735         PQExpBuffer sql;
11736
11737         /* Do nothing if ACL dump is not enabled */
11738         if (aclsSkip)
11739                 return;
11740
11741         /* --data-only skips ACLs *except* BLOB ACLs */
11742         if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
11743                 return;
11744
11745         sql = createPQExpBuffer();
11746
11747         if (!buildACLCommands(name, subname, type, acls, owner,
11748                                                   "", fout->remoteVersion, sql))
11749                 exit_horribly(NULL,
11750                                           "could not parse ACL list (%s) for object \"%s\" (%s)\n",
11751                                           acls, name, type);
11752
11753         if (sql->len > 0)
11754                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11755                                          tag, nspname,
11756                                          NULL,
11757                                          owner ? owner : "",
11758                                          false, "ACL", SECTION_NONE,
11759                                          sql->data, "", NULL,
11760                                          &(objDumpId), 1,
11761                                          NULL, NULL);
11762
11763         destroyPQExpBuffer(sql);
11764 }
11765
11766 /*
11767  * dumpSecLabel
11768  *
11769  * This routine is used to dump any security labels associated with the
11770  * object handed to this routine. The routine takes a constant character
11771  * string for the target part of the security-label command, plus
11772  * the namespace and owner of the object (for labeling the ArchiveEntry),
11773  * plus catalog ID and subid which are the lookup key for pg_seclabel,
11774  * plus the dump ID for the object (for setting a dependency).
11775  * If a matching pg_seclabel entry is found, it is dumped.
11776  *
11777  * Note: although this routine takes a dumpId for dependency purposes,
11778  * that purpose is just to mark the dependency in the emitted dump file
11779  * for possible future use by pg_restore.  We do NOT use it for determining
11780  * ordering of the label in the dump file, because this routine is called
11781  * after dependency sorting occurs.  This routine should be called just after
11782  * calling ArchiveEntry() for the specified object.
11783  */
11784 static void
11785 dumpSecLabel(Archive *fout, const char *target,
11786                          const char *namespace, const char *owner,
11787                          CatalogId catalogId, int subid, DumpId dumpId)
11788 {
11789         SecLabelItem *labels;
11790         int                     nlabels;
11791         int                     i;
11792         PQExpBuffer query;
11793
11794         /* do nothing, if --no-security-labels is supplied */
11795         if (no_security_labels)
11796                 return;
11797
11798         /* Comments are schema not data ... except blob comments are data */
11799         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
11800         {
11801                 if (dataOnly)
11802                         return;
11803         }
11804         else
11805         {
11806                 if (schemaOnly)
11807                         return;
11808         }
11809
11810         /* Search for security labels associated with catalogId, using table */
11811         nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
11812
11813         query = createPQExpBuffer();
11814
11815         for (i = 0; i < nlabels; i++)
11816         {
11817                 /*
11818                  * Ignore label entries for which the subid doesn't match.
11819                  */
11820                 if (labels[i].objsubid != subid)
11821                         continue;
11822
11823                 appendPQExpBuffer(query,
11824                                                   "SECURITY LABEL FOR %s ON %s IS ",
11825                                                   fmtId(labels[i].provider), target);
11826                 appendStringLiteralAH(query, labels[i].label, fout);
11827                 appendPQExpBuffer(query, ";\n");
11828         }
11829
11830         if (query->len > 0)
11831         {
11832                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11833                                          target, namespace, NULL, owner,
11834                                          false, "SECURITY LABEL", SECTION_NONE,
11835                                          query->data, "", NULL,
11836                                          &(dumpId), 1,
11837                                          NULL, NULL);
11838         }
11839         destroyPQExpBuffer(query);
11840 }
11841
11842 /*
11843  * dumpTableSecLabel
11844  *
11845  * As above, but dump security label for both the specified table (or view)
11846  * and its columns.
11847  */
11848 static void
11849 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
11850 {
11851         SecLabelItem *labels;
11852         int                     nlabels;
11853         int                     i;
11854         PQExpBuffer query;
11855         PQExpBuffer target;
11856
11857         /* do nothing, if --no-security-labels is supplied */
11858         if (no_security_labels)
11859                 return;
11860
11861         /* SecLabel are SCHEMA not data */
11862         if (dataOnly)
11863                 return;
11864
11865         /* Search for comments associated with relation, using table */
11866         nlabels = findSecLabels(fout,
11867                                                         tbinfo->dobj.catId.tableoid,
11868                                                         tbinfo->dobj.catId.oid,
11869                                                         &labels);
11870
11871         /* If security labels exist, build SECURITY LABEL statements */
11872         if (nlabels <= 0)
11873                 return;
11874
11875         query = createPQExpBuffer();
11876         target = createPQExpBuffer();
11877
11878         for (i = 0; i < nlabels; i++)
11879         {
11880                 const char *colname;
11881                 const char *provider = labels[i].provider;
11882                 const char *label = labels[i].label;
11883                 int                     objsubid = labels[i].objsubid;
11884
11885                 resetPQExpBuffer(target);
11886                 if (objsubid == 0)
11887                 {
11888                         appendPQExpBuffer(target, "%s %s", reltypename,
11889                                                           fmtId(tbinfo->dobj.name));
11890                 }
11891                 else
11892                 {
11893                         colname = getAttrName(objsubid, tbinfo);
11894                         /* first fmtId result must be consumed before calling it again */
11895                         appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
11896                         appendPQExpBuffer(target, ".%s", fmtId(colname));
11897                 }
11898                 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
11899                                                   fmtId(provider), target->data);
11900                 appendStringLiteralAH(query, label, fout);
11901                 appendPQExpBuffer(query, ";\n");
11902         }
11903         if (query->len > 0)
11904         {
11905                 resetPQExpBuffer(target);
11906                 appendPQExpBuffer(target, "%s %s", reltypename,
11907                                                   fmtId(tbinfo->dobj.name));
11908                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11909                                          target->data,
11910                                          tbinfo->dobj.namespace->dobj.name,
11911                                          NULL, tbinfo->rolname,
11912                                          false, "SECURITY LABEL", SECTION_NONE,
11913                                          query->data, "", NULL,
11914                                          &(tbinfo->dobj.dumpId), 1,
11915                                          NULL, NULL);
11916         }
11917         destroyPQExpBuffer(query);
11918         destroyPQExpBuffer(target);
11919 }
11920
11921 /*
11922  * findSecLabels
11923  *
11924  * Find the security label(s), if any, associated with the given object.
11925  * All the objsubid values associated with the given classoid/objoid are
11926  * found with one search.
11927  */
11928 static int
11929 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
11930 {
11931         /* static storage for table of security labels */
11932         static SecLabelItem *labels = NULL;
11933         static int      nlabels = -1;
11934
11935         SecLabelItem *middle = NULL;
11936         SecLabelItem *low;
11937         SecLabelItem *high;
11938         int                     nmatch;
11939
11940         /* Get security labels if we didn't already */
11941         if (nlabels < 0)
11942                 nlabels = collectSecLabels(fout, &labels);
11943
11944         if (nlabels <= 0)                       /* no labels, so no match is possible */
11945         {
11946                 *items = NULL;
11947                 return 0;
11948         }
11949
11950         /*
11951          * Do binary search to find some item matching the object.
11952          */
11953         low = &labels[0];
11954         high = &labels[nlabels - 1];
11955         while (low <= high)
11956         {
11957                 middle = low + (high - low) / 2;
11958
11959                 if (classoid < middle->classoid)
11960                         high = middle - 1;
11961                 else if (classoid > middle->classoid)
11962                         low = middle + 1;
11963                 else if (objoid < middle->objoid)
11964                         high = middle - 1;
11965                 else if (objoid > middle->objoid)
11966                         low = middle + 1;
11967                 else
11968                         break;                          /* found a match */
11969         }
11970
11971         if (low > high)                         /* no matches */
11972         {
11973                 *items = NULL;
11974                 return 0;
11975         }
11976
11977         /*
11978          * Now determine how many items match the object.  The search loop
11979          * invariant still holds: only items between low and high inclusive could
11980          * match.
11981          */
11982         nmatch = 1;
11983         while (middle > low)
11984         {
11985                 if (classoid != middle[-1].classoid ||
11986                         objoid != middle[-1].objoid)
11987                         break;
11988                 middle--;
11989                 nmatch++;
11990         }
11991
11992         *items = middle;
11993
11994         middle += nmatch;
11995         while (middle <= high)
11996         {
11997                 if (classoid != middle->classoid ||
11998                         objoid != middle->objoid)
11999                         break;
12000                 middle++;
12001                 nmatch++;
12002         }
12003
12004         return nmatch;
12005 }
12006
12007 /*
12008  * collectSecLabels
12009  *
12010  * Construct a table of all security labels available for database objects.
12011  * It's much faster to pull them all at once.
12012  *
12013  * The table is sorted by classoid/objid/objsubid for speed in lookup.
12014  */
12015 static int
12016 collectSecLabels(Archive *fout, SecLabelItem **items)
12017 {
12018         PGresult   *res;
12019         PQExpBuffer query;
12020         int                     i_label;
12021         int                     i_provider;
12022         int                     i_classoid;
12023         int                     i_objoid;
12024         int                     i_objsubid;
12025         int                     ntups;
12026         int                     i;
12027         SecLabelItem *labels;
12028
12029         query = createPQExpBuffer();
12030
12031         appendPQExpBuffer(query,
12032                                           "SELECT label, provider, classoid, objoid, objsubid "
12033                                           "FROM pg_catalog.pg_seclabel "
12034                                           "ORDER BY classoid, objoid, objsubid");
12035
12036         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12037
12038         /* Construct lookup table containing OIDs in numeric form */
12039         i_label = PQfnumber(res, "label");
12040         i_provider = PQfnumber(res, "provider");
12041         i_classoid = PQfnumber(res, "classoid");
12042         i_objoid = PQfnumber(res, "objoid");
12043         i_objsubid = PQfnumber(res, "objsubid");
12044
12045         ntups = PQntuples(res);
12046
12047         labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12048
12049         for (i = 0; i < ntups; i++)
12050         {
12051                 labels[i].label = PQgetvalue(res, i, i_label);
12052                 labels[i].provider = PQgetvalue(res, i, i_provider);
12053                 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12054                 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12055                 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12056         }
12057
12058         /* Do NOT free the PGresult since we are keeping pointers into it */
12059         destroyPQExpBuffer(query);
12060
12061         *items = labels;
12062         return ntups;
12063 }
12064
12065 /*
12066  * dumpTable
12067  *        write out to fout the declarations (not data) of a user-defined table
12068  */
12069 static void
12070 dumpTable(Archive *fout, TableInfo *tbinfo)
12071 {
12072         if (tbinfo->dobj.dump)
12073         {
12074                 char       *namecopy;
12075
12076                 if (tbinfo->relkind == RELKIND_SEQUENCE)
12077                         dumpSequence(fout, tbinfo);
12078                 else if (!dataOnly)
12079                         dumpTableSchema(fout, tbinfo);
12080
12081                 /* Handle the ACL here */
12082                 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12083                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12084                                 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12085                                 "TABLE",
12086                                 namecopy, NULL, tbinfo->dobj.name,
12087                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12088                                 tbinfo->relacl);
12089
12090                 /*
12091                  * Handle column ACLs, if any.  Note: we pull these with a separate
12092                  * query rather than trying to fetch them during getTableAttrs, so
12093                  * that we won't miss ACLs on system columns.
12094                  */
12095                 if (fout->remoteVersion >= 80400)
12096                 {
12097                         PQExpBuffer query = createPQExpBuffer();
12098                         PGresult   *res;
12099                         int                     i;
12100
12101                         appendPQExpBuffer(query,
12102                                            "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12103                                                           "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12104                                                           "ORDER BY attnum",
12105                                                           tbinfo->dobj.catId.oid);
12106                         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12107
12108                         for (i = 0; i < PQntuples(res); i++)
12109                         {
12110                                 char       *attname = PQgetvalue(res, i, 0);
12111                                 char       *attacl = PQgetvalue(res, i, 1);
12112                                 char       *attnamecopy;
12113                                 char       *acltag;
12114
12115                                 attnamecopy = pg_strdup(fmtId(attname));
12116                                 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12117                                 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12118                                 /* Column's GRANT type is always TABLE */
12119                                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12120                                                 namecopy, attnamecopy, acltag,
12121                                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12122                                                 attacl);
12123                                 free(attnamecopy);
12124                                 free(acltag);
12125                         }
12126                         PQclear(res);
12127                         destroyPQExpBuffer(query);
12128                 }
12129
12130                 free(namecopy);
12131         }
12132 }
12133
12134 /*
12135  * dumpTableSchema
12136  *        write the declaration (not data) of one user-defined table or view
12137  */
12138 static void
12139 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12140 {
12141         PQExpBuffer query = createPQExpBuffer();
12142         PQExpBuffer q = createPQExpBuffer();
12143         PQExpBuffer delq = createPQExpBuffer();
12144         PQExpBuffer labelq = createPQExpBuffer();
12145         PGresult   *res;
12146         int                     numParents;
12147         TableInfo **parents;
12148         int                     actual_atts;    /* number of attrs in this CREATE statement */
12149         const char *reltypename;
12150         char       *storage;
12151         char       *srvname;
12152         char       *ftoptions;
12153         int                     j,
12154                                 k;
12155
12156         /* Make sure we are in proper schema */
12157         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12158
12159         if (binary_upgrade)
12160                 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12161                                                                                                 tbinfo->dobj.catId.oid);
12162
12163         /* Is it a table or a view? */
12164         if (tbinfo->relkind == RELKIND_VIEW)
12165         {
12166                 char       *viewdef;
12167
12168                 reltypename = "VIEW";
12169
12170                 /* Fetch the view definition */
12171                 if (fout->remoteVersion >= 70300)
12172                 {
12173                         /* Beginning in 7.3, viewname is not unique; rely on OID */
12174                         appendPQExpBuffer(query,
12175                                                           "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12176                                                           tbinfo->dobj.catId.oid);
12177                 }
12178                 else
12179                 {
12180                         appendPQExpBuffer(query, "SELECT definition AS viewdef "
12181                                                           "FROM pg_views WHERE viewname = ");
12182                         appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12183                         appendPQExpBuffer(query, ";");
12184                 }
12185
12186                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12187
12188                 if (PQntuples(res) != 1)
12189                 {
12190                         if (PQntuples(res) < 1)
12191                                 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12192                                                   tbinfo->dobj.name);
12193                         else
12194                                 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12195                                                   tbinfo->dobj.name);
12196                 }
12197
12198                 viewdef = PQgetvalue(res, 0, 0);
12199
12200                 if (strlen(viewdef) == 0)
12201                         exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12202                                                   tbinfo->dobj.name);
12203
12204                 /*
12205                  * DROP must be fully qualified in case same name appears in
12206                  * pg_catalog
12207                  */
12208                 appendPQExpBuffer(delq, "DROP VIEW %s.",
12209                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12210                 appendPQExpBuffer(delq, "%s;\n",
12211                                                   fmtId(tbinfo->dobj.name));
12212
12213                 if (binary_upgrade)
12214                         binary_upgrade_set_pg_class_oids(fout, q,
12215                                                                                          tbinfo->dobj.catId.oid, false);
12216
12217                 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12218                 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12219                         appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12220                 appendPQExpBuffer(q, " AS\n    %s\n", viewdef);
12221
12222                 appendPQExpBuffer(labelq, "VIEW %s",
12223                                                   fmtId(tbinfo->dobj.name));
12224
12225                 PQclear(res);
12226         }
12227         else
12228         {
12229                 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12230                 {
12231                         int                     i_srvname;
12232                         int                     i_ftoptions;
12233
12234                         reltypename = "FOREIGN TABLE";
12235
12236                         /* retrieve name of foreign server and generic options */
12237                         appendPQExpBuffer(query,
12238                                                           "SELECT fs.srvname, "
12239                                                           "pg_catalog.array_to_string(ARRAY("
12240                                                           "SELECT pg_catalog.quote_ident(option_name) || "
12241                                                           "' ' || pg_catalog.quote_literal(option_value) "
12242                                                           "FROM pg_catalog.pg_options_to_table(ftoptions) "
12243                                                           "ORDER BY option_name"
12244                                                           "), E',\n    ') AS ftoptions "
12245                                                           "FROM pg_catalog.pg_foreign_table ft "
12246                                                           "JOIN pg_catalog.pg_foreign_server fs "
12247                                                           "ON (fs.oid = ft.ftserver) "
12248                                                           "WHERE ft.ftrelid = '%u'",
12249                                                           tbinfo->dobj.catId.oid);
12250                         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12251                         i_srvname = PQfnumber(res, "srvname");
12252                         i_ftoptions = PQfnumber(res, "ftoptions");
12253                         srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12254                         ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12255                         PQclear(res);
12256                 }
12257                 else
12258                 {
12259                         reltypename = "TABLE";
12260                         srvname = NULL;
12261                         ftoptions = NULL;
12262                 }
12263                 numParents = tbinfo->numParents;
12264                 parents = tbinfo->parents;
12265
12266                 /*
12267                  * DROP must be fully qualified in case same name appears in
12268                  * pg_catalog
12269                  */
12270                 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12271                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12272                 appendPQExpBuffer(delq, "%s;\n",
12273                                                   fmtId(tbinfo->dobj.name));
12274
12275                 appendPQExpBuffer(labelq, "%s %s", reltypename,
12276                                                   fmtId(tbinfo->dobj.name));
12277
12278                 if (binary_upgrade)
12279                         binary_upgrade_set_pg_class_oids(fout, q,
12280                                                                                          tbinfo->dobj.catId.oid, false);
12281
12282                 appendPQExpBuffer(q, "CREATE %s%s %s",
12283                                                   tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12284                                                   "UNLOGGED " : "",
12285                                                   reltypename,
12286                                                   fmtId(tbinfo->dobj.name));
12287
12288                 /*
12289                  * Attach to type, if reloftype; except in case of a binary upgrade,
12290                  * we dump the table normally and attach it to the type afterward.
12291                  */
12292                 if (tbinfo->reloftype && !binary_upgrade)
12293                         appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12294
12295                 /* Dump the attributes */
12296                 actual_atts = 0;
12297                 for (j = 0; j < tbinfo->numatts; j++)
12298                 {
12299                         /*
12300                          * Normally, dump if it's locally defined in this table, and not
12301                          * dropped.  But for binary upgrade, we'll dump all the columns,
12302                          * and then fix up the dropped and nonlocal cases below.
12303                          */
12304                         if (shouldPrintColumn(tbinfo, j))
12305                         {
12306                                 /*
12307                                  * Default value --- suppress if to be printed separately.
12308                                  */
12309                                 bool            has_default = (tbinfo->attrdefs[j] != NULL &&
12310                                                                                    !tbinfo->attrdefs[j]->separate);
12311
12312                                 /*
12313                                  * Not Null constraint --- suppress if inherited, except in
12314                                  * binary-upgrade case where that won't work.
12315                                  */
12316                                 bool            has_notnull = (tbinfo->notnull[j] &&
12317                                                                                    (!tbinfo->inhNotNull[j] ||
12318                                                                                         binary_upgrade));
12319
12320                                 /* Skip column if fully defined by reloftype */
12321                                 if (tbinfo->reloftype &&
12322                                         !has_default && !has_notnull && !binary_upgrade)
12323                                         continue;
12324
12325                                 /* Format properly if not first attr */
12326                                 if (actual_atts == 0)
12327                                         appendPQExpBuffer(q, " (");
12328                                 else
12329                                         appendPQExpBuffer(q, ",");
12330                                 appendPQExpBuffer(q, "\n    ");
12331                                 actual_atts++;
12332
12333                                 /* Attribute name */
12334                                 appendPQExpBuffer(q, "%s ",
12335                                                                   fmtId(tbinfo->attnames[j]));
12336
12337                                 if (tbinfo->attisdropped[j])
12338                                 {
12339                                         /*
12340                                          * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12341                                          * so we will not have gotten a valid type name; insert
12342                                          * INTEGER as a stopgap.  We'll clean things up later.
12343                                          */
12344                                         appendPQExpBuffer(q, "INTEGER /* dummy */");
12345                                         /* Skip all the rest, too */
12346                                         continue;
12347                                 }
12348
12349                                 /* Attribute type */
12350                                 if (tbinfo->reloftype && !binary_upgrade)
12351                                 {
12352                                         appendPQExpBuffer(q, "WITH OPTIONS");
12353                                 }
12354                                 else if (fout->remoteVersion >= 70100)
12355                                 {
12356                                         appendPQExpBuffer(q, "%s",
12357                                                                           tbinfo->atttypnames[j]);
12358                                 }
12359                                 else
12360                                 {
12361                                         /* If no format_type, fake it */
12362                                         appendPQExpBuffer(q, "%s",
12363                                                                           myFormatType(tbinfo->atttypnames[j],
12364                                                                                                    tbinfo->atttypmod[j]));
12365                                 }
12366
12367                                 /* Add collation if not default for the type */
12368                                 if (OidIsValid(tbinfo->attcollation[j]))
12369                                 {
12370                                         CollInfo   *coll;
12371
12372                                         coll = findCollationByOid(tbinfo->attcollation[j]);
12373                                         if (coll)
12374                                         {
12375                                                 /* always schema-qualify, don't try to be smart */
12376                                                 appendPQExpBuffer(q, " COLLATE %s.",
12377                                                                          fmtId(coll->dobj.namespace->dobj.name));
12378                                                 appendPQExpBuffer(q, "%s",
12379                                                                                   fmtId(coll->dobj.name));
12380                                         }
12381                                 }
12382
12383                                 if (has_default)
12384                                         appendPQExpBuffer(q, " DEFAULT %s",
12385                                                                           tbinfo->attrdefs[j]->adef_expr);
12386
12387                                 if (has_notnull)
12388                                         appendPQExpBuffer(q, " NOT NULL");
12389                         }
12390                 }
12391
12392                 /*
12393                  * Add non-inherited CHECK constraints, if any.
12394                  */
12395                 for (j = 0; j < tbinfo->ncheck; j++)
12396                 {
12397                         ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12398
12399                         if (constr->separate || !constr->conislocal)
12400                                 continue;
12401
12402                         if (actual_atts == 0)
12403                                 appendPQExpBuffer(q, " (\n    ");
12404                         else
12405                                 appendPQExpBuffer(q, ",\n    ");
12406
12407                         appendPQExpBuffer(q, "CONSTRAINT %s ",
12408                                                           fmtId(constr->dobj.name));
12409                         appendPQExpBuffer(q, "%s", constr->condef);
12410
12411                         actual_atts++;
12412                 }
12413
12414                 if (actual_atts)
12415                         appendPQExpBuffer(q, "\n)");
12416                 else if (!(tbinfo->reloftype && !binary_upgrade))
12417                 {
12418                         /*
12419                          * We must have a parenthesized attribute list, even though empty,
12420                          * when not using the OF TYPE syntax.
12421                          */
12422                         appendPQExpBuffer(q, " (\n)");
12423                 }
12424
12425                 if (numParents > 0 && !binary_upgrade)
12426                 {
12427                         appendPQExpBuffer(q, "\nINHERITS (");
12428                         for (k = 0; k < numParents; k++)
12429                         {
12430                                 TableInfo  *parentRel = parents[k];
12431
12432                                 if (k > 0)
12433                                         appendPQExpBuffer(q, ", ");
12434                                 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12435                                         appendPQExpBuffer(q, "%s.",
12436                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
12437                                 appendPQExpBuffer(q, "%s",
12438                                                                   fmtId(parentRel->dobj.name));
12439                         }
12440                         appendPQExpBuffer(q, ")");
12441                 }
12442
12443                 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12444                         appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12445
12446                 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12447                   (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12448                 {
12449                         bool            addcomma = false;
12450
12451                         appendPQExpBuffer(q, "\nWITH (");
12452                         if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12453                         {
12454                                 addcomma = true;
12455                                 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12456                         }
12457                         if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12458                         {
12459                                 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12460                                                                   tbinfo->toast_reloptions);
12461                         }
12462                         appendPQExpBuffer(q, ")");
12463                 }
12464
12465                 /* Dump generic options if any */
12466                 if (ftoptions && ftoptions[0])
12467                         appendPQExpBuffer(q, "\nOPTIONS (\n    %s\n)", ftoptions);
12468
12469                 appendPQExpBuffer(q, ";\n");
12470
12471                 /*
12472                  * To create binary-compatible heap files, we have to ensure the same
12473                  * physical column order, including dropped columns, as in the
12474                  * original.  Therefore, we create dropped columns above and drop them
12475                  * here, also updating their attlen/attalign values so that the
12476                  * dropped column can be skipped properly.      (We do not bother with
12477                  * restoring the original attbyval setting.)  Also, inheritance
12478                  * relationships are set up by doing ALTER INHERIT rather than using
12479                  * an INHERITS clause --- the latter would possibly mess up the column
12480                  * order.  That also means we have to take care about setting
12481                  * attislocal correctly, plus fix up any inherited CHECK constraints.
12482                  * Analogously, we set up typed tables using ALTER TABLE / OF here.
12483                  */
12484                 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12485                 {
12486                         for (j = 0; j < tbinfo->numatts; j++)
12487                         {
12488                                 if (tbinfo->attisdropped[j])
12489                                 {
12490                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12491                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12492                                                                           "SET attlen = %d, "
12493                                                                           "attalign = '%c', attbyval = false\n"
12494                                                                           "WHERE attname = ",
12495                                                                           tbinfo->attlen[j],
12496                                                                           tbinfo->attalign[j]);
12497                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12498                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
12499                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12500                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12501
12502                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12503                                                                           fmtId(tbinfo->dobj.name));
12504                                         appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12505                                                                           fmtId(tbinfo->attnames[j]));
12506                                 }
12507                                 else if (!tbinfo->attislocal[j])
12508                                 {
12509                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12510                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12511                                                                           "SET attislocal = false\n"
12512                                                                           "WHERE attname = ");
12513                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12514                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
12515                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12516                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12517                                 }
12518                         }
12519
12520                         for (k = 0; k < tbinfo->ncheck; k++)
12521                         {
12522                                 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12523
12524                                 if (constr->separate || constr->conislocal)
12525                                         continue;
12526
12527                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12528                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12529                                                                   fmtId(tbinfo->dobj.name));
12530                                 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12531                                                                   fmtId(constr->dobj.name));
12532                                 appendPQExpBuffer(q, "%s;\n", constr->condef);
12533                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
12534                                                                   "SET conislocal = false\n"
12535                                                                   "WHERE contype = 'c' AND conname = ");
12536                                 appendStringLiteralAH(q, constr->dobj.name, fout);
12537                                 appendPQExpBuffer(q, "\n  AND conrelid = ");
12538                                 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12539                                 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12540                         }
12541
12542                         if (numParents > 0)
12543                         {
12544                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
12545                                 for (k = 0; k < numParents; k++)
12546                                 {
12547                                         TableInfo  *parentRel = parents[k];
12548
12549                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
12550                                                                           fmtId(tbinfo->dobj.name));
12551                                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12552                                                 appendPQExpBuffer(q, "%s.",
12553                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
12554                                         appendPQExpBuffer(q, "%s;\n",
12555                                                                           fmtId(parentRel->dobj.name));
12556                                 }
12557                         }
12558
12559                         if (tbinfo->reloftype)
12560                         {
12561                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
12562                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
12563                                                                   fmtId(tbinfo->dobj.name),
12564                                                                   tbinfo->reloftype);
12565                         }
12566
12567                         appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
12568                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12569                                                           "SET relfrozenxid = '%u'\n"
12570                                                           "WHERE oid = ",
12571                                                           tbinfo->frozenxid);
12572                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12573                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12574
12575                         if (tbinfo->toast_oid)
12576                         {
12577                                 /* We preserve the toast oids, so we can use it during restore */
12578                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
12579                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12580                                                                   "SET relfrozenxid = '%u'\n"
12581                                                                   "WHERE oid = '%u';\n",
12582                                                                   tbinfo->toast_frozenxid, tbinfo->toast_oid);
12583                         }
12584                 }
12585
12586                 /*
12587                  * Dump additional per-column properties that we can't handle in the
12588                  * main CREATE TABLE command.
12589                  */
12590                 for (j = 0; j < tbinfo->numatts; j++)
12591                 {
12592                         /* None of this applies to dropped columns */
12593                         if (tbinfo->attisdropped[j])
12594                                 continue;
12595
12596                         /*
12597                          * If we didn't dump the column definition explicitly above, and
12598                          * it is NOT NULL and did not inherit that property from a parent,
12599                          * we have to mark it separately.
12600                          */
12601                         if (!shouldPrintColumn(tbinfo, j) &&
12602                                 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
12603                         {
12604                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12605                                                                   fmtId(tbinfo->dobj.name));
12606                                 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
12607                                                                   fmtId(tbinfo->attnames[j]));
12608                         }
12609
12610                         /*
12611                          * Dump per-column statistics information. We only issue an ALTER
12612                          * TABLE statement if the attstattarget entry for this column is
12613                          * non-negative (i.e. it's not the default value)
12614                          */
12615                         if (tbinfo->attstattarget[j] >= 0)
12616                         {
12617                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12618                                                                   fmtId(tbinfo->dobj.name));
12619                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12620                                                                   fmtId(tbinfo->attnames[j]));
12621                                 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
12622                                                                   tbinfo->attstattarget[j]);
12623                         }
12624
12625                         /*
12626                          * Dump per-column storage information.  The statement is only
12627                          * dumped if the storage has been changed from the type's default.
12628                          */
12629                         if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
12630                         {
12631                                 switch (tbinfo->attstorage[j])
12632                                 {
12633                                         case 'p':
12634                                                 storage = "PLAIN";
12635                                                 break;
12636                                         case 'e':
12637                                                 storage = "EXTERNAL";
12638                                                 break;
12639                                         case 'm':
12640                                                 storage = "MAIN";
12641                                                 break;
12642                                         case 'x':
12643                                                 storage = "EXTENDED";
12644                                                 break;
12645                                         default:
12646                                                 storage = NULL;
12647                                 }
12648
12649                                 /*
12650                                  * Only dump the statement if it's a storage type we recognize
12651                                  */
12652                                 if (storage != NULL)
12653                                 {
12654                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12655                                                                           fmtId(tbinfo->dobj.name));
12656                                         appendPQExpBuffer(q, "ALTER COLUMN %s ",
12657                                                                           fmtId(tbinfo->attnames[j]));
12658                                         appendPQExpBuffer(q, "SET STORAGE %s;\n",
12659                                                                           storage);
12660                                 }
12661                         }
12662
12663                         /*
12664                          * Dump per-column attributes.
12665                          */
12666                         if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
12667                         {
12668                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12669                                                                   fmtId(tbinfo->dobj.name));
12670                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12671                                                                   fmtId(tbinfo->attnames[j]));
12672                                 appendPQExpBuffer(q, "SET (%s);\n",
12673                                                                   tbinfo->attoptions[j]);
12674                         }
12675
12676                         /*
12677                          * Dump per-column fdw options.
12678                          */
12679                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
12680                                 tbinfo->attfdwoptions[j] &&
12681                                 tbinfo->attfdwoptions[j][0] != '\0')
12682                         {
12683                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
12684                                                                   fmtId(tbinfo->dobj.name));
12685                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12686                                                                   fmtId(tbinfo->attnames[j]));
12687                                 appendPQExpBuffer(q, "OPTIONS (\n    %s\n);\n",
12688                                                                   tbinfo->attfdwoptions[j]);
12689                         }
12690                 }
12691         }
12692
12693         if (binary_upgrade)
12694                 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
12695
12696         ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12697                                  tbinfo->dobj.name,
12698                                  tbinfo->dobj.namespace->dobj.name,
12699                         (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
12700                                  tbinfo->rolname,
12701                            (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
12702                                  reltypename, SECTION_PRE_DATA,
12703                                  q->data, delq->data, NULL,
12704                                  tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
12705                                  NULL, NULL);
12706
12707
12708         /* Dump Table Comments */
12709         dumpTableComment(fout, tbinfo, reltypename);
12710
12711         /* Dump Table Security Labels */
12712         dumpTableSecLabel(fout, tbinfo, reltypename);
12713
12714         /* Dump comments on inlined table constraints */
12715         for (j = 0; j < tbinfo->ncheck; j++)
12716         {
12717                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12718
12719                 if (constr->separate || !constr->conislocal)
12720                         continue;
12721
12722                 dumpTableConstraintComment(fout, constr);
12723         }
12724
12725         destroyPQExpBuffer(query);
12726         destroyPQExpBuffer(q);
12727         destroyPQExpBuffer(delq);
12728         destroyPQExpBuffer(labelq);
12729 }
12730
12731 /*
12732  * dumpAttrDef --- dump an attribute's default-value declaration
12733  */
12734 static void
12735 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
12736 {
12737         TableInfo  *tbinfo = adinfo->adtable;
12738         int                     adnum = adinfo->adnum;
12739         PQExpBuffer q;
12740         PQExpBuffer delq;
12741
12742         /* Skip if table definition not to be dumped */
12743         if (!tbinfo->dobj.dump || dataOnly)
12744                 return;
12745
12746         /* Skip if not "separate"; it was dumped in the table's definition */
12747         if (!adinfo->separate)
12748                 return;
12749
12750         q = createPQExpBuffer();
12751         delq = createPQExpBuffer();
12752
12753         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12754                                           fmtId(tbinfo->dobj.name));
12755         appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
12756                                           fmtId(tbinfo->attnames[adnum - 1]),
12757                                           adinfo->adef_expr);
12758
12759         /*
12760          * DROP must be fully qualified in case same name appears in pg_catalog
12761          */
12762         appendPQExpBuffer(delq, "ALTER TABLE %s.",
12763                                           fmtId(tbinfo->dobj.namespace->dobj.name));
12764         appendPQExpBuffer(delq, "%s ",
12765                                           fmtId(tbinfo->dobj.name));
12766         appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
12767                                           fmtId(tbinfo->attnames[adnum - 1]));
12768
12769         ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
12770                                  tbinfo->attnames[adnum - 1],
12771                                  tbinfo->dobj.namespace->dobj.name,
12772                                  NULL,
12773                                  tbinfo->rolname,
12774                                  false, "DEFAULT", SECTION_PRE_DATA,
12775                                  q->data, delq->data, NULL,
12776                                  adinfo->dobj.dependencies, adinfo->dobj.nDeps,
12777                                  NULL, NULL);
12778
12779         destroyPQExpBuffer(q);
12780         destroyPQExpBuffer(delq);
12781 }
12782
12783 /*
12784  * getAttrName: extract the correct name for an attribute
12785  *
12786  * The array tblInfo->attnames[] only provides names of user attributes;
12787  * if a system attribute number is supplied, we have to fake it.
12788  * We also do a little bit of bounds checking for safety's sake.
12789  */
12790 static const char *
12791 getAttrName(int attrnum, TableInfo *tblInfo)
12792 {
12793         if (attrnum > 0 && attrnum <= tblInfo->numatts)
12794                 return tblInfo->attnames[attrnum - 1];
12795         switch (attrnum)
12796         {
12797                 case SelfItemPointerAttributeNumber:
12798                         return "ctid";
12799                 case ObjectIdAttributeNumber:
12800                         return "oid";
12801                 case MinTransactionIdAttributeNumber:
12802                         return "xmin";
12803                 case MinCommandIdAttributeNumber:
12804                         return "cmin";
12805                 case MaxTransactionIdAttributeNumber:
12806                         return "xmax";
12807                 case MaxCommandIdAttributeNumber:
12808                         return "cmax";
12809                 case TableOidAttributeNumber:
12810                         return "tableoid";
12811         }
12812         exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
12813                                   attrnum, tblInfo->dobj.name);
12814         return NULL;                            /* keep compiler quiet */
12815 }
12816
12817 /*
12818  * dumpIndex
12819  *        write out to fout a user-defined index
12820  */
12821 static void
12822 dumpIndex(Archive *fout, IndxInfo *indxinfo)
12823 {
12824         TableInfo  *tbinfo = indxinfo->indextable;
12825         PQExpBuffer q;
12826         PQExpBuffer delq;
12827         PQExpBuffer labelq;
12828
12829         if (dataOnly)
12830                 return;
12831
12832         q = createPQExpBuffer();
12833         delq = createPQExpBuffer();
12834         labelq = createPQExpBuffer();
12835
12836         appendPQExpBuffer(labelq, "INDEX %s",
12837                                           fmtId(indxinfo->dobj.name));
12838
12839         /*
12840          * If there's an associated constraint, don't dump the index per se, but
12841          * do dump any comment for it.  (This is safe because dependency ordering
12842          * will have ensured the constraint is emitted first.)
12843          */
12844         if (indxinfo->indexconstraint == 0)
12845         {
12846                 if (binary_upgrade)
12847                         binary_upgrade_set_pg_class_oids(fout, q,
12848                                                                                          indxinfo->dobj.catId.oid, true);
12849
12850                 /* Plain secondary index */
12851                 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
12852
12853                 /* If the index is clustered, we need to record that. */
12854                 if (indxinfo->indisclustered)
12855                 {
12856                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12857                                                           fmtId(tbinfo->dobj.name));
12858                         appendPQExpBuffer(q, " ON %s;\n",
12859                                                           fmtId(indxinfo->dobj.name));
12860                 }
12861
12862                 /*
12863                  * DROP must be fully qualified in case same name appears in
12864                  * pg_catalog
12865                  */
12866                 appendPQExpBuffer(delq, "DROP INDEX %s.",
12867                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12868                 appendPQExpBuffer(delq, "%s;\n",
12869                                                   fmtId(indxinfo->dobj.name));
12870
12871                 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
12872                                          indxinfo->dobj.name,
12873                                          tbinfo->dobj.namespace->dobj.name,
12874                                          indxinfo->tablespace,
12875                                          tbinfo->rolname, false,
12876                                          "INDEX", SECTION_POST_DATA,
12877                                          q->data, delq->data, NULL,
12878                                          indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
12879                                          NULL, NULL);
12880         }
12881
12882         /* Dump Index Comments */
12883         dumpComment(fout, labelq->data,
12884                                 tbinfo->dobj.namespace->dobj.name,
12885                                 tbinfo->rolname,
12886                                 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
12887
12888         destroyPQExpBuffer(q);
12889         destroyPQExpBuffer(delq);
12890         destroyPQExpBuffer(labelq);
12891 }
12892
12893 /*
12894  * dumpConstraint
12895  *        write out to fout a user-defined constraint
12896  */
12897 static void
12898 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
12899 {
12900         TableInfo  *tbinfo = coninfo->contable;
12901         PQExpBuffer q;
12902         PQExpBuffer delq;
12903
12904         /* Skip if not to be dumped */
12905         if (!coninfo->dobj.dump || dataOnly)
12906                 return;
12907
12908         q = createPQExpBuffer();
12909         delq = createPQExpBuffer();
12910
12911         if (coninfo->contype == 'p' ||
12912                 coninfo->contype == 'u' ||
12913                 coninfo->contype == 'x')
12914         {
12915                 /* Index-related constraint */
12916                 IndxInfo   *indxinfo;
12917                 int                     k;
12918
12919                 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
12920
12921                 if (indxinfo == NULL)
12922                         exit_horribly(NULL, "missing index for constraint \"%s\"\n",
12923                                                   coninfo->dobj.name);
12924
12925                 if (binary_upgrade)
12926                         binary_upgrade_set_pg_class_oids(fout, q,
12927                                                                                          indxinfo->dobj.catId.oid, true);
12928
12929                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
12930                                                   fmtId(tbinfo->dobj.name));
12931                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s ",
12932                                                   fmtId(coninfo->dobj.name));
12933
12934                 if (coninfo->condef)
12935                 {
12936                         /* pg_get_constraintdef should have provided everything */
12937                         appendPQExpBuffer(q, "%s;\n", coninfo->condef);
12938                 }
12939                 else
12940                 {
12941                         appendPQExpBuffer(q, "%s (",
12942                                                  coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
12943                         for (k = 0; k < indxinfo->indnkeys; k++)
12944                         {
12945                                 int                     indkey = (int) indxinfo->indkeys[k];
12946                                 const char *attname;
12947
12948                                 if (indkey == InvalidAttrNumber)
12949                                         break;
12950                                 attname = getAttrName(indkey, tbinfo);
12951
12952                                 appendPQExpBuffer(q, "%s%s",
12953                                                                   (k == 0) ? "" : ", ",
12954                                                                   fmtId(attname));
12955                         }
12956
12957                         appendPQExpBuffer(q, ")");
12958
12959                         if (indxinfo->options && strlen(indxinfo->options) > 0)
12960                                 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
12961
12962                         if (coninfo->condeferrable)
12963                         {
12964                                 appendPQExpBuffer(q, " DEFERRABLE");
12965                                 if (coninfo->condeferred)
12966                                         appendPQExpBuffer(q, " INITIALLY DEFERRED");
12967                         }
12968
12969                         appendPQExpBuffer(q, ";\n");
12970                 }
12971
12972                 /* If the index is clustered, we need to record that. */
12973                 if (indxinfo->indisclustered)
12974                 {
12975                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12976                                                           fmtId(tbinfo->dobj.name));
12977                         appendPQExpBuffer(q, " ON %s;\n",
12978                                                           fmtId(indxinfo->dobj.name));
12979                 }
12980
12981                 /*
12982                  * DROP must be fully qualified in case same name appears in
12983                  * pg_catalog
12984                  */
12985                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
12986                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12987                 appendPQExpBuffer(delq, "%s ",
12988                                                   fmtId(tbinfo->dobj.name));
12989                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
12990                                                   fmtId(coninfo->dobj.name));
12991
12992                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
12993                                          coninfo->dobj.name,
12994                                          tbinfo->dobj.namespace->dobj.name,
12995                                          indxinfo->tablespace,
12996                                          tbinfo->rolname, false,
12997                                          "CONSTRAINT", SECTION_POST_DATA,
12998                                          q->data, delq->data, NULL,
12999                                          coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13000                                          NULL, NULL);
13001         }
13002         else if (coninfo->contype == 'f')
13003         {
13004                 /*
13005                  * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13006                  * current table data is not processed
13007                  */
13008                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13009                                                   fmtId(tbinfo->dobj.name));
13010                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13011                                                   fmtId(coninfo->dobj.name),
13012                                                   coninfo->condef);
13013
13014                 /*
13015                  * DROP must be fully qualified in case same name appears in
13016                  * pg_catalog
13017                  */
13018                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13019                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13020                 appendPQExpBuffer(delq, "%s ",
13021                                                   fmtId(tbinfo->dobj.name));
13022                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13023                                                   fmtId(coninfo->dobj.name));
13024
13025                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13026                                          coninfo->dobj.name,
13027                                          tbinfo->dobj.namespace->dobj.name,
13028                                          NULL,
13029                                          tbinfo->rolname, false,
13030                                          "FK CONSTRAINT", SECTION_POST_DATA,
13031                                          q->data, delq->data, NULL,
13032                                          coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13033                                          NULL, NULL);
13034         }
13035         else if (coninfo->contype == 'c' && tbinfo)
13036         {
13037                 /* CHECK constraint on a table */
13038
13039                 /* Ignore if not to be dumped separately */
13040                 if (coninfo->separate)
13041                 {
13042                         /* not ONLY since we want it to propagate to children */
13043                         appendPQExpBuffer(q, "ALTER TABLE %s\n",
13044                                                           fmtId(tbinfo->dobj.name));
13045                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13046                                                           fmtId(coninfo->dobj.name),
13047                                                           coninfo->condef);
13048
13049                         /*
13050                          * DROP must be fully qualified in case same name appears in
13051                          * pg_catalog
13052                          */
13053                         appendPQExpBuffer(delq, "ALTER TABLE %s.",
13054                                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13055                         appendPQExpBuffer(delq, "%s ",
13056                                                           fmtId(tbinfo->dobj.name));
13057                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13058                                                           fmtId(coninfo->dobj.name));
13059
13060                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13061                                                  coninfo->dobj.name,
13062                                                  tbinfo->dobj.namespace->dobj.name,
13063                                                  NULL,
13064                                                  tbinfo->rolname, false,
13065                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13066                                                  q->data, delq->data, NULL,
13067                                                  coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13068                                                  NULL, NULL);
13069                 }
13070         }
13071         else if (coninfo->contype == 'c' && tbinfo == NULL)
13072         {
13073                 /* CHECK constraint on a domain */
13074                 TypeInfo   *tyinfo = coninfo->condomain;
13075
13076                 /* Ignore if not to be dumped separately */
13077                 if (coninfo->separate)
13078                 {
13079                         appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13080                                                           fmtId(tyinfo->dobj.name));
13081                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13082                                                           fmtId(coninfo->dobj.name),
13083                                                           coninfo->condef);
13084
13085                         /*
13086                          * DROP must be fully qualified in case same name appears in
13087                          * pg_catalog
13088                          */
13089                         appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13090                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
13091                         appendPQExpBuffer(delq, "%s ",
13092                                                           fmtId(tyinfo->dobj.name));
13093                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13094                                                           fmtId(coninfo->dobj.name));
13095
13096                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13097                                                  coninfo->dobj.name,
13098                                                  tyinfo->dobj.namespace->dobj.name,
13099                                                  NULL,
13100                                                  tyinfo->rolname, false,
13101                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13102                                                  q->data, delq->data, NULL,
13103                                                  coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13104                                                  NULL, NULL);
13105                 }
13106         }
13107         else
13108         {
13109                 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13110                                           coninfo->contype);
13111         }
13112
13113         /* Dump Constraint Comments --- only works for table constraints */
13114         if (tbinfo && coninfo->separate)
13115                 dumpTableConstraintComment(fout, coninfo);
13116
13117         destroyPQExpBuffer(q);
13118         destroyPQExpBuffer(delq);
13119 }
13120
13121 /*
13122  * dumpTableConstraintComment --- dump a constraint's comment if any
13123  *
13124  * This is split out because we need the function in two different places
13125  * depending on whether the constraint is dumped as part of CREATE TABLE
13126  * or as a separate ALTER command.
13127  */
13128 static void
13129 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13130 {
13131         TableInfo  *tbinfo = coninfo->contable;
13132         PQExpBuffer labelq = createPQExpBuffer();
13133
13134         appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13135                                           fmtId(coninfo->dobj.name));
13136         appendPQExpBuffer(labelq, "ON %s",
13137                                           fmtId(tbinfo->dobj.name));
13138         dumpComment(fout, labelq->data,
13139                                 tbinfo->dobj.namespace->dobj.name,
13140                                 tbinfo->rolname,
13141                                 coninfo->dobj.catId, 0,
13142                          coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13143
13144         destroyPQExpBuffer(labelq);
13145 }
13146
13147 /*
13148  * findLastBuiltInOid -
13149  * find the last built in oid
13150  *
13151  * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13152  * pg_database entry for the current database
13153  */
13154 static Oid
13155 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13156 {
13157         PGresult   *res;
13158         Oid                     last_oid;
13159         PQExpBuffer query = createPQExpBuffer();
13160
13161         resetPQExpBuffer(query);
13162         appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13163         appendStringLiteralAH(query, dbname, fout);
13164
13165         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13166         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13167         PQclear(res);
13168         destroyPQExpBuffer(query);
13169         return last_oid;
13170 }
13171
13172 /*
13173  * findLastBuiltInOid -
13174  * find the last built in oid
13175  *
13176  * For 7.0, we do this by assuming that the last thing that initdb does is to
13177  * create the pg_indexes view.  This sucks in general, but seeing that 7.0.x
13178  * initdb won't be changing anymore, it'll do.
13179  */
13180 static Oid
13181 findLastBuiltinOid_V70(Archive *fout)
13182 {
13183         PGresult   *res;
13184         int                     last_oid;
13185
13186         res = ExecuteSqlQueryForSingleRow(fout,
13187                                         "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13188         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13189         PQclear(res);
13190         return last_oid;
13191 }
13192
13193 static void
13194 dumpSequence(Archive *fout, TableInfo *tbinfo)
13195 {
13196         PGresult   *res;
13197         char       *startv,
13198                            *last,
13199                            *incby,
13200                            *maxv = NULL,
13201                            *minv = NULL,
13202                            *cache;
13203         char            bufm[100],
13204                                 bufx[100];
13205         bool            cycled,
13206                                 called;
13207         PQExpBuffer query = createPQExpBuffer();
13208         PQExpBuffer delqry = createPQExpBuffer();
13209         PQExpBuffer labelq = createPQExpBuffer();
13210
13211         /* Make sure we are in proper schema */
13212         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13213
13214         snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13215         snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13216
13217         if (fout->remoteVersion >= 80400)
13218         {
13219                 appendPQExpBuffer(query,
13220                                                   "SELECT sequence_name, "
13221                                                   "start_value, last_value, increment_by, "
13222                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13223                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13224                                                   "     ELSE max_value "
13225                                                   "END AS max_value, "
13226                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13227                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13228                                                   "     ELSE min_value "
13229                                                   "END AS min_value, "
13230                                                   "cache_value, is_cycled, is_called from %s",
13231                                                   bufx, bufm,
13232                                                   fmtId(tbinfo->dobj.name));
13233         }
13234         else
13235         {
13236                 appendPQExpBuffer(query,
13237                                                   "SELECT sequence_name, "
13238                                                   "0 AS start_value, last_value, increment_by, "
13239                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13240                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13241                                                   "     ELSE max_value "
13242                                                   "END AS max_value, "
13243                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13244                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13245                                                   "     ELSE min_value "
13246                                                   "END AS min_value, "
13247                                                   "cache_value, is_cycled, is_called from %s",
13248                                                   bufx, bufm,
13249                                                   fmtId(tbinfo->dobj.name));
13250         }
13251
13252         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13253
13254         if (PQntuples(res) != 1)
13255         {
13256                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13257                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13258                                                                  PQntuples(res)),
13259                                   tbinfo->dobj.name, PQntuples(res));
13260                 exit_nicely(1);
13261         }
13262
13263         /* Disable this check: it fails if sequence has been renamed */
13264 #ifdef NOT_USED
13265         if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13266         {
13267                 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13268                                   tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13269                 exit_nicely(1);
13270         }
13271 #endif
13272
13273         startv = PQgetvalue(res, 0, 1);
13274         last = PQgetvalue(res, 0, 2);
13275         incby = PQgetvalue(res, 0, 3);
13276         if (!PQgetisnull(res, 0, 4))
13277                 maxv = PQgetvalue(res, 0, 4);
13278         if (!PQgetisnull(res, 0, 5))
13279                 minv = PQgetvalue(res, 0, 5);
13280         cache = PQgetvalue(res, 0, 6);
13281         cycled = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
13282         called = (strcmp(PQgetvalue(res, 0, 8), "t") == 0);
13283
13284         /*
13285          * The logic we use for restoring sequences is as follows:
13286          *
13287          * Add a CREATE SEQUENCE statement as part of a "schema" dump (use
13288          * last_val for start if called is false, else use min_val for start_val).
13289          * Also, if the sequence is owned by a column, add an ALTER SEQUENCE OWNED
13290          * BY command for it.
13291          *
13292          * Add a 'SETVAL(seq, last_val, iscalled)' as part of a "data" dump.
13293          */
13294         if (!dataOnly)
13295         {
13296                 /*
13297                  * DROP must be fully qualified in case same name appears in
13298                  * pg_catalog
13299                  */
13300                 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13301                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13302                 appendPQExpBuffer(delqry, "%s;\n",
13303                                                   fmtId(tbinfo->dobj.name));
13304
13305                 resetPQExpBuffer(query);
13306
13307                 if (binary_upgrade)
13308                 {
13309                         binary_upgrade_set_pg_class_oids(fout, query,
13310                                                                                          tbinfo->dobj.catId.oid, false);
13311                         binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13312                                                                                                         tbinfo->dobj.catId.oid);
13313                 }
13314
13315                 appendPQExpBuffer(query,
13316                                                   "CREATE SEQUENCE %s\n",
13317                                                   fmtId(tbinfo->dobj.name));
13318
13319                 if (fout->remoteVersion >= 80400)
13320                         appendPQExpBuffer(query, "    START WITH %s\n", startv);
13321                 else
13322                 {
13323                         /*
13324                          * Versions before 8.4 did not remember the true start value.  If
13325                          * is_called is false then the sequence has never been incremented
13326                          * so we can use last_val.      Otherwise punt and let it default.
13327                          */
13328                         if (!called)
13329                                 appendPQExpBuffer(query, "    START WITH %s\n", last);
13330                 }
13331
13332                 appendPQExpBuffer(query, "    INCREMENT BY %s\n", incby);
13333
13334                 if (minv)
13335                         appendPQExpBuffer(query, "    MINVALUE %s\n", minv);
13336                 else
13337                         appendPQExpBuffer(query, "    NO MINVALUE\n");
13338
13339                 if (maxv)
13340                         appendPQExpBuffer(query, "    MAXVALUE %s\n", maxv);
13341                 else
13342                         appendPQExpBuffer(query, "    NO MAXVALUE\n");
13343
13344                 appendPQExpBuffer(query,
13345                                                   "    CACHE %s%s",
13346                                                   cache, (cycled ? "\n    CYCLE" : ""));
13347
13348                 appendPQExpBuffer(query, ";\n");
13349
13350                 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13351
13352                 /* binary_upgrade:      no need to clear TOAST table oid */
13353
13354                 if (binary_upgrade)
13355                         binary_upgrade_extension_member(query, &tbinfo->dobj,
13356                                                                                         labelq->data);
13357
13358                 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13359                                          tbinfo->dobj.name,
13360                                          tbinfo->dobj.namespace->dobj.name,
13361                                          NULL,
13362                                          tbinfo->rolname,
13363                                          false, "SEQUENCE", SECTION_PRE_DATA,
13364                                          query->data, delqry->data, NULL,
13365                                          tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
13366                                          NULL, NULL);
13367
13368                 /*
13369                  * If the sequence is owned by a table column, emit the ALTER for it
13370                  * as a separate TOC entry immediately following the sequence's own
13371                  * entry.  It's OK to do this rather than using full sorting logic,
13372                  * because the dependency that tells us it's owned will have forced
13373                  * the table to be created first.  We can't just include the ALTER in
13374                  * the TOC entry because it will fail if we haven't reassigned the
13375                  * sequence owner to match the table's owner.
13376                  *
13377                  * We need not schema-qualify the table reference because both
13378                  * sequence and table must be in the same schema.
13379                  */
13380                 if (OidIsValid(tbinfo->owning_tab))
13381                 {
13382                         TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
13383
13384                         if (owning_tab && owning_tab->dobj.dump)
13385                         {
13386                                 resetPQExpBuffer(query);
13387                                 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13388                                                                   fmtId(tbinfo->dobj.name));
13389                                 appendPQExpBuffer(query, " OWNED BY %s",
13390                                                                   fmtId(owning_tab->dobj.name));
13391                                 appendPQExpBuffer(query, ".%s;\n",
13392                                                 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13393
13394                                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13395                                                          tbinfo->dobj.name,
13396                                                          tbinfo->dobj.namespace->dobj.name,
13397                                                          NULL,
13398                                                          tbinfo->rolname,
13399                                                          false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13400                                                          query->data, "", NULL,
13401                                                          &(tbinfo->dobj.dumpId), 1,
13402                                                          NULL, NULL);
13403                         }
13404                 }
13405
13406                 /* Dump Sequence Comments and Security Labels */
13407                 dumpComment(fout, labelq->data,
13408                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13409                                         tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13410                 dumpSecLabel(fout, labelq->data,
13411                                          tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13412                                          tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13413         }
13414
13415         if (!schemaOnly)
13416         {
13417                 resetPQExpBuffer(query);
13418                 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13419                 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13420                 appendPQExpBuffer(query, ", %s, %s);\n",
13421                                                   last, (called ? "true" : "false"));
13422
13423                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13424                                          tbinfo->dobj.name,
13425                                          tbinfo->dobj.namespace->dobj.name,
13426                                          NULL,
13427                                          tbinfo->rolname,
13428                                          false, "SEQUENCE SET", SECTION_PRE_DATA,
13429                                          query->data, "", NULL,
13430                                          &(tbinfo->dobj.dumpId), 1,
13431                                          NULL, NULL);
13432         }
13433
13434         PQclear(res);
13435
13436         destroyPQExpBuffer(query);
13437         destroyPQExpBuffer(delqry);
13438         destroyPQExpBuffer(labelq);
13439 }
13440
13441 static void
13442 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13443 {
13444         TableInfo  *tbinfo = tginfo->tgtable;
13445         PQExpBuffer query;
13446         PQExpBuffer delqry;
13447         PQExpBuffer labelq;
13448         char       *tgargs;
13449         size_t          lentgargs;
13450         const char *p;
13451         int                     findx;
13452
13453         if (dataOnly)
13454                 return;
13455
13456         query = createPQExpBuffer();
13457         delqry = createPQExpBuffer();
13458         labelq = createPQExpBuffer();
13459
13460         /*
13461          * DROP must be fully qualified in case same name appears in pg_catalog
13462          */
13463         appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13464                                           fmtId(tginfo->dobj.name));
13465         appendPQExpBuffer(delqry, "ON %s.",
13466                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13467         appendPQExpBuffer(delqry, "%s;\n",
13468                                           fmtId(tbinfo->dobj.name));
13469
13470         if (tginfo->tgdef)
13471         {
13472                 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13473         }
13474         else
13475         {
13476                 if (tginfo->tgisconstraint)
13477                 {
13478                         appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13479                         appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13480                 }
13481                 else
13482                 {
13483                         appendPQExpBuffer(query, "CREATE TRIGGER ");
13484                         appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13485                 }
13486                 appendPQExpBuffer(query, "\n    ");
13487
13488                 /* Trigger type */
13489                 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13490                         appendPQExpBuffer(query, "BEFORE");
13491                 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13492                         appendPQExpBuffer(query, "AFTER");
13493                 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13494                         appendPQExpBuffer(query, "INSTEAD OF");
13495                 else
13496                 {
13497                         write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13498                         exit_nicely(1);
13499                 }
13500
13501                 findx = 0;
13502                 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13503                 {
13504                         appendPQExpBuffer(query, " INSERT");
13505                         findx++;
13506                 }
13507                 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13508                 {
13509                         if (findx > 0)
13510                                 appendPQExpBuffer(query, " OR DELETE");
13511                         else
13512                                 appendPQExpBuffer(query, " DELETE");
13513                         findx++;
13514                 }
13515                 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13516                 {
13517                         if (findx > 0)
13518                                 appendPQExpBuffer(query, " OR UPDATE");
13519                         else
13520                                 appendPQExpBuffer(query, " UPDATE");
13521                         findx++;
13522                 }
13523                 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
13524                 {
13525                         if (findx > 0)
13526                                 appendPQExpBuffer(query, " OR TRUNCATE");
13527                         else
13528                                 appendPQExpBuffer(query, " TRUNCATE");
13529                         findx++;
13530                 }
13531                 appendPQExpBuffer(query, " ON %s\n",
13532                                                   fmtId(tbinfo->dobj.name));
13533
13534                 if (tginfo->tgisconstraint)
13535                 {
13536                         if (OidIsValid(tginfo->tgconstrrelid))
13537                         {
13538                                 /* If we are using regclass, name is already quoted */
13539                                 if (fout->remoteVersion >= 70300)
13540                                         appendPQExpBuffer(query, "    FROM %s\n    ",
13541                                                                           tginfo->tgconstrrelname);
13542                                 else
13543                                         appendPQExpBuffer(query, "    FROM %s\n    ",
13544                                                                           fmtId(tginfo->tgconstrrelname));
13545                         }
13546                         if (!tginfo->tgdeferrable)
13547                                 appendPQExpBuffer(query, "NOT ");
13548                         appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
13549                         if (tginfo->tginitdeferred)
13550                                 appendPQExpBuffer(query, "DEFERRED\n");
13551                         else
13552                                 appendPQExpBuffer(query, "IMMEDIATE\n");
13553                 }
13554
13555                 if (TRIGGER_FOR_ROW(tginfo->tgtype))
13556                         appendPQExpBuffer(query, "    FOR EACH ROW\n    ");
13557                 else
13558                         appendPQExpBuffer(query, "    FOR EACH STATEMENT\n    ");
13559
13560                 /* In 7.3, result of regproc is already quoted */
13561                 if (fout->remoteVersion >= 70300)
13562                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13563                                                           tginfo->tgfname);
13564                 else
13565                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13566                                                           fmtId(tginfo->tgfname));
13567
13568                 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
13569                                                                                   &lentgargs);
13570                 p = tgargs;
13571                 for (findx = 0; findx < tginfo->tgnargs; findx++)
13572                 {
13573                         /* find the embedded null that terminates this trigger argument */
13574                         size_t          tlen = strlen(p);
13575
13576                         if (p + tlen >= tgargs + lentgargs)
13577                         {
13578                                 /* hm, not found before end of bytea value... */
13579                                 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
13580                                                   tginfo->tgargs,
13581                                                   tginfo->dobj.name,
13582                                                   tbinfo->dobj.name);
13583                                 exit_nicely(1);
13584                         }
13585
13586                         if (findx > 0)
13587                                 appendPQExpBuffer(query, ", ");
13588                         appendStringLiteralAH(query, p, fout);
13589                         p += tlen + 1;
13590                 }
13591                 free(tgargs);
13592                 appendPQExpBuffer(query, ");\n");
13593         }
13594
13595         if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
13596         {
13597                 appendPQExpBuffer(query, "\nALTER TABLE %s ",
13598                                                   fmtId(tbinfo->dobj.name));
13599                 switch (tginfo->tgenabled)
13600                 {
13601                         case 'D':
13602                         case 'f':
13603                                 appendPQExpBuffer(query, "DISABLE");
13604                                 break;
13605                         case 'A':
13606                                 appendPQExpBuffer(query, "ENABLE ALWAYS");
13607                                 break;
13608                         case 'R':
13609                                 appendPQExpBuffer(query, "ENABLE REPLICA");
13610                                 break;
13611                         default:
13612                                 appendPQExpBuffer(query, "ENABLE");
13613                                 break;
13614                 }
13615                 appendPQExpBuffer(query, " TRIGGER %s;\n",
13616                                                   fmtId(tginfo->dobj.name));
13617         }
13618
13619         appendPQExpBuffer(labelq, "TRIGGER %s ",
13620                                           fmtId(tginfo->dobj.name));
13621         appendPQExpBuffer(labelq, "ON %s",
13622                                           fmtId(tbinfo->dobj.name));
13623
13624         ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
13625                                  tginfo->dobj.name,
13626                                  tbinfo->dobj.namespace->dobj.name,
13627                                  NULL,
13628                                  tbinfo->rolname, false,
13629                                  "TRIGGER", SECTION_POST_DATA,
13630                                  query->data, delqry->data, NULL,
13631                                  tginfo->dobj.dependencies, tginfo->dobj.nDeps,
13632                                  NULL, NULL);
13633
13634         dumpComment(fout, labelq->data,
13635                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13636                                 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
13637
13638         destroyPQExpBuffer(query);
13639         destroyPQExpBuffer(delqry);
13640         destroyPQExpBuffer(labelq);
13641 }
13642
13643 /*
13644  * dumpRule
13645  *              Dump a rule
13646  */
13647 static void
13648 dumpRule(Archive *fout, RuleInfo *rinfo)
13649 {
13650         TableInfo  *tbinfo = rinfo->ruletable;
13651         PQExpBuffer query;
13652         PQExpBuffer cmd;
13653         PQExpBuffer delcmd;
13654         PQExpBuffer labelq;
13655         PGresult   *res;
13656
13657         /* Skip if not to be dumped */
13658         if (!rinfo->dobj.dump || dataOnly)
13659                 return;
13660
13661         /*
13662          * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
13663          * we do not want to dump it as a separate object.
13664          */
13665         if (!rinfo->separate)
13666                 return;
13667
13668         /*
13669          * Make sure we are in proper schema.
13670          */
13671         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13672
13673         query = createPQExpBuffer();
13674         cmd = createPQExpBuffer();
13675         delcmd = createPQExpBuffer();
13676         labelq = createPQExpBuffer();
13677
13678         if (fout->remoteVersion >= 70300)
13679         {
13680                 appendPQExpBuffer(query,
13681                                                   "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
13682                                                   rinfo->dobj.catId.oid);
13683         }
13684         else
13685         {
13686                 /* Rule name was unique before 7.3 ... */
13687                 appendPQExpBuffer(query,
13688                                                   "SELECT pg_get_ruledef('%s') AS definition",
13689                                                   rinfo->dobj.name);
13690         }
13691
13692         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13693
13694         if (PQntuples(res) != 1)
13695         {
13696                 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
13697                                   rinfo->dobj.name, tbinfo->dobj.name);
13698                 exit_nicely(1);
13699         }
13700
13701         printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
13702
13703         /*
13704          * Add the command to alter the rules replication firing semantics if it
13705          * differs from the default.
13706          */
13707         if (rinfo->ev_enabled != 'O')
13708         {
13709                 appendPQExpBuffer(cmd, "ALTER TABLE %s.",
13710                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13711                 appendPQExpBuffer(cmd, "%s ",
13712                                                   fmtId(tbinfo->dobj.name));
13713                 switch (rinfo->ev_enabled)
13714                 {
13715                         case 'A':
13716                                 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
13717                                                                   fmtId(rinfo->dobj.name));
13718                                 break;
13719                         case 'R':
13720                                 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
13721                                                                   fmtId(rinfo->dobj.name));
13722                                 break;
13723                         case 'D':
13724                                 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
13725                                                                   fmtId(rinfo->dobj.name));
13726                                 break;
13727                 }
13728         }
13729
13730         /*
13731          * DROP must be fully qualified in case same name appears in pg_catalog
13732          */
13733         appendPQExpBuffer(delcmd, "DROP RULE %s ",
13734                                           fmtId(rinfo->dobj.name));
13735         appendPQExpBuffer(delcmd, "ON %s.",
13736                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13737         appendPQExpBuffer(delcmd, "%s;\n",
13738                                           fmtId(tbinfo->dobj.name));
13739
13740         appendPQExpBuffer(labelq, "RULE %s",
13741                                           fmtId(rinfo->dobj.name));
13742         appendPQExpBuffer(labelq, " ON %s",
13743                                           fmtId(tbinfo->dobj.name));
13744
13745         ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
13746                                  rinfo->dobj.name,
13747                                  tbinfo->dobj.namespace->dobj.name,
13748                                  NULL,
13749                                  tbinfo->rolname, false,
13750                                  "RULE", SECTION_POST_DATA,
13751                                  cmd->data, delcmd->data, NULL,
13752                                  rinfo->dobj.dependencies, rinfo->dobj.nDeps,
13753                                  NULL, NULL);
13754
13755         /* Dump rule comments */
13756         dumpComment(fout, labelq->data,
13757                                 tbinfo->dobj.namespace->dobj.name,
13758                                 tbinfo->rolname,
13759                                 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
13760
13761         PQclear(res);
13762
13763         destroyPQExpBuffer(query);
13764         destroyPQExpBuffer(cmd);
13765         destroyPQExpBuffer(delcmd);
13766         destroyPQExpBuffer(labelq);
13767 }
13768
13769 /*
13770  * getExtensionMembership --- obtain extension membership data
13771  */
13772 void
13773 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
13774                                            int numExtensions)
13775 {
13776         PQExpBuffer query;
13777         PGresult   *res;
13778         int                     ntups,
13779                                 i;
13780         int                     i_classid,
13781                                 i_objid,
13782                                 i_refclassid,
13783                                 i_refobjid;
13784         DumpableObject *dobj,
13785                            *refdobj;
13786
13787         /* Nothing to do if no extensions */
13788         if (numExtensions == 0)
13789                 return;
13790
13791         /* Make sure we are in proper schema */
13792         selectSourceSchema(fout, "pg_catalog");
13793
13794         query = createPQExpBuffer();
13795
13796         /* refclassid constraint is redundant but may speed the search */
13797         appendPQExpBuffer(query, "SELECT "
13798                                           "classid, objid, refclassid, refobjid "
13799                                           "FROM pg_depend "
13800                                           "WHERE refclassid = 'pg_extension'::regclass "
13801                                           "AND deptype = 'e' "
13802                                           "ORDER BY 3,4");
13803
13804         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13805
13806         ntups = PQntuples(res);
13807
13808         i_classid = PQfnumber(res, "classid");
13809         i_objid = PQfnumber(res, "objid");
13810         i_refclassid = PQfnumber(res, "refclassid");
13811         i_refobjid = PQfnumber(res, "refobjid");
13812
13813         /*
13814          * Since we ordered the SELECT by referenced ID, we can expect that
13815          * multiple entries for the same extension will appear together; this
13816          * saves on searches.
13817          */
13818         refdobj = NULL;
13819
13820         for (i = 0; i < ntups; i++)
13821         {
13822                 CatalogId       objId;
13823                 CatalogId       refobjId;
13824
13825                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
13826                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
13827                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
13828                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
13829
13830                 if (refdobj == NULL ||
13831                         refdobj->catId.tableoid != refobjId.tableoid ||
13832                         refdobj->catId.oid != refobjId.oid)
13833                         refdobj = findObjectByCatalogId(refobjId);
13834
13835                 /*
13836                  * Failure to find objects mentioned in pg_depend is not unexpected,
13837                  * since for example we don't collect info about TOAST tables.
13838                  */
13839                 if (refdobj == NULL)
13840                 {
13841 #ifdef NOT_USED
13842                         fprintf(stderr, "no referenced object %u %u\n",
13843                                         refobjId.tableoid, refobjId.oid);
13844 #endif
13845                         continue;
13846                 }
13847
13848                 dobj = findObjectByCatalogId(objId);
13849
13850                 if (dobj == NULL)
13851                 {
13852 #ifdef NOT_USED
13853                         fprintf(stderr, "no referencing object %u %u\n",
13854                                         objId.tableoid, objId.oid);
13855 #endif
13856                         continue;
13857                 }
13858
13859                 /* Record dependency so that getDependencies needn't repeat this */
13860                 addObjectDependency(dobj, refdobj->dumpId);
13861
13862                 dobj->ext_member = true;
13863
13864                 /*
13865                  * Normally, mark the member object as not to be dumped.  But in
13866                  * binary upgrades, we still dump the members individually, since the
13867                  * idea is to exactly reproduce the database contents rather than
13868                  * replace the extension contents with something different.
13869                  */
13870                 if (!binary_upgrade)
13871                         dobj->dump = false;
13872                 else
13873                         dobj->dump = refdobj->dump;
13874         }
13875
13876         PQclear(res);
13877
13878         /*
13879          * Now identify extension configuration tables and create TableDataInfo
13880          * objects for them, ensuring their data will be dumped even though the
13881          * tables themselves won't be.
13882          *
13883          * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
13884          * user data in a configuration table is treated like schema data. This
13885          * seems appropriate since system data in a config table would get
13886          * reloaded by CREATE EXTENSION.
13887          */
13888         for (i = 0; i < numExtensions; i++)
13889         {
13890                 ExtensionInfo *curext = &(extinfo[i]);
13891                 char       *extconfig = curext->extconfig;
13892                 char       *extcondition = curext->extcondition;
13893                 char      **extconfigarray = NULL;
13894                 char      **extconditionarray = NULL;
13895                 int                     nconfigitems;
13896                 int                     nconditionitems;
13897
13898                 /* Tables of not-to-be-dumped extensions shouldn't be dumped */
13899                 if (!curext->dobj.dump)
13900                         continue;
13901
13902                 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
13903                   parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
13904                         nconfigitems == nconditionitems)
13905                 {
13906                         int                     j;
13907
13908                         for (j = 0; j < nconfigitems; j++)
13909                         {
13910                                 TableInfo  *configtbl;
13911
13912                                 configtbl = findTableByOid(atooid(extconfigarray[j]));
13913                                 if (configtbl == NULL)
13914                                         continue;
13915
13916                                 /*
13917                                  * Note: config tables are dumped without OIDs regardless
13918                                  * of the --oids setting.  This is because row filtering
13919                                  * conditions aren't compatible with dumping OIDs.
13920                                  */
13921                                 makeTableDataInfo(configtbl, false);
13922                                 if (configtbl->dataObj != NULL)
13923                                 {
13924                                         if (strlen(extconditionarray[j]) > 0)
13925                                                 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
13926                                 }
13927                         }
13928                 }
13929                 if (extconfigarray)
13930                         free(extconfigarray);
13931                 if (extconditionarray)
13932                         free(extconditionarray);
13933         }
13934
13935         destroyPQExpBuffer(query);
13936 }
13937
13938 /*
13939  * getDependencies --- obtain available dependency data
13940  */
13941 static void
13942 getDependencies(Archive *fout)
13943 {
13944         PQExpBuffer query;
13945         PGresult   *res;
13946         int                     ntups,
13947                                 i;
13948         int                     i_classid,
13949                                 i_objid,
13950                                 i_refclassid,
13951                                 i_refobjid,
13952                                 i_deptype;
13953         DumpableObject *dobj,
13954                            *refdobj;
13955
13956         /* No dependency info available before 7.3 */
13957         if (fout->remoteVersion < 70300)
13958                 return;
13959
13960         if (g_verbose)
13961                 write_msg(NULL, "reading dependency data\n");
13962
13963         /* Make sure we are in proper schema */
13964         selectSourceSchema(fout, "pg_catalog");
13965
13966         query = createPQExpBuffer();
13967
13968         /*
13969          * PIN dependencies aren't interesting, and EXTENSION dependencies were
13970          * already processed by getExtensionMembership.
13971          */
13972         appendPQExpBuffer(query, "SELECT "
13973                                           "classid, objid, refclassid, refobjid, deptype "
13974                                           "FROM pg_depend "
13975                                           "WHERE deptype != 'p' AND deptype != 'e' "
13976                                           "ORDER BY 1,2");
13977
13978         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13979
13980         ntups = PQntuples(res);
13981
13982         i_classid = PQfnumber(res, "classid");
13983         i_objid = PQfnumber(res, "objid");
13984         i_refclassid = PQfnumber(res, "refclassid");
13985         i_refobjid = PQfnumber(res, "refobjid");
13986         i_deptype = PQfnumber(res, "deptype");
13987
13988         /*
13989          * Since we ordered the SELECT by referencing ID, we can expect that
13990          * multiple entries for the same object will appear together; this saves
13991          * on searches.
13992          */
13993         dobj = NULL;
13994
13995         for (i = 0; i < ntups; i++)
13996         {
13997                 CatalogId       objId;
13998                 CatalogId       refobjId;
13999                 char            deptype;
14000
14001                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14002                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14003                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14004                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14005                 deptype = *(PQgetvalue(res, i, i_deptype));
14006
14007                 if (dobj == NULL ||
14008                         dobj->catId.tableoid != objId.tableoid ||
14009                         dobj->catId.oid != objId.oid)
14010                         dobj = findObjectByCatalogId(objId);
14011
14012                 /*
14013                  * Failure to find objects mentioned in pg_depend is not unexpected,
14014                  * since for example we don't collect info about TOAST tables.
14015                  */
14016                 if (dobj == NULL)
14017                 {
14018 #ifdef NOT_USED
14019                         fprintf(stderr, "no referencing object %u %u\n",
14020                                         objId.tableoid, objId.oid);
14021 #endif
14022                         continue;
14023                 }
14024
14025                 refdobj = findObjectByCatalogId(refobjId);
14026
14027                 if (refdobj == NULL)
14028                 {
14029 #ifdef NOT_USED
14030                         fprintf(stderr, "no referenced object %u %u\n",
14031                                         refobjId.tableoid, refobjId.oid);
14032 #endif
14033                         continue;
14034                 }
14035
14036                 /*
14037                  * Ordinarily, table rowtypes have implicit dependencies on their
14038                  * tables.      However, for a composite type the implicit dependency goes
14039                  * the other way in pg_depend; which is the right thing for DROP but
14040                  * it doesn't produce the dependency ordering we need. So in that one
14041                  * case, we reverse the direction of the dependency.
14042                  */
14043                 if (deptype == 'i' &&
14044                         dobj->objType == DO_TABLE &&
14045                         refdobj->objType == DO_TYPE)
14046                         addObjectDependency(refdobj, dobj->dumpId);
14047                 else
14048                         /* normal case */
14049                         addObjectDependency(dobj, refdobj->dumpId);
14050         }
14051
14052         PQclear(res);
14053
14054         destroyPQExpBuffer(query);
14055 }
14056
14057
14058 /*
14059  * selectSourceSchema - make the specified schema the active search path
14060  * in the source database.
14061  *
14062  * NB: pg_catalog is explicitly searched after the specified schema;
14063  * so user names are only qualified if they are cross-schema references,
14064  * and system names are only qualified if they conflict with a user name
14065  * in the current schema.
14066  *
14067  * Whenever the selected schema is not pg_catalog, be careful to qualify
14068  * references to system catalogs and types in our emitted commands!
14069  */
14070 static void
14071 selectSourceSchema(Archive *fout, const char *schemaName)
14072 {
14073         static char *curSchemaName = NULL;
14074         PQExpBuffer query;
14075
14076         /* Not relevant if fetching from pre-7.3 DB */
14077         if (fout->remoteVersion < 70300)
14078                 return;
14079         /* Ignore null schema names */
14080         if (schemaName == NULL || *schemaName == '\0')
14081                 return;
14082         /* Optimize away repeated selection of same schema */
14083         if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14084                 return;
14085
14086         query = createPQExpBuffer();
14087         appendPQExpBuffer(query, "SET search_path = %s",
14088                                           fmtId(schemaName));
14089         if (strcmp(schemaName, "pg_catalog") != 0)
14090                 appendPQExpBuffer(query, ", pg_catalog");
14091
14092         ExecuteSqlStatement(fout, query->data);
14093
14094         destroyPQExpBuffer(query);
14095         if (curSchemaName)
14096                 free(curSchemaName);
14097         curSchemaName = pg_strdup(schemaName);
14098 }
14099
14100 /*
14101  * getFormattedTypeName - retrieve a nicely-formatted type name for the
14102  * given type name.
14103  *
14104  * NB: in 7.3 and up the result may depend on the currently-selected
14105  * schema; this is why we don't try to cache the names.
14106  */
14107 static char *
14108 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
14109 {
14110         char       *result;
14111         PQExpBuffer query;
14112         PGresult   *res;
14113
14114         if (oid == 0)
14115         {
14116                 if ((opts & zeroAsOpaque) != 0)
14117                         return pg_strdup(g_opaque_type);
14118                 else if ((opts & zeroAsAny) != 0)
14119                         return pg_strdup("'any'");
14120                 else if ((opts & zeroAsStar) != 0)
14121                         return pg_strdup("*");
14122                 else if ((opts & zeroAsNone) != 0)
14123                         return pg_strdup("NONE");
14124         }
14125
14126         query = createPQExpBuffer();
14127         if (fout->remoteVersion >= 70300)
14128         {
14129                 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14130                                                   oid);
14131         }
14132         else if (fout->remoteVersion >= 70100)
14133         {
14134                 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14135                                                   oid);
14136         }
14137         else
14138         {
14139                 appendPQExpBuffer(query, "SELECT typname "
14140                                                   "FROM pg_type "
14141                                                   "WHERE oid = '%u'::oid",
14142                                                   oid);
14143         }
14144
14145         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14146
14147         if (fout->remoteVersion >= 70100)
14148         {
14149                 /* already quoted */
14150                 result = pg_strdup(PQgetvalue(res, 0, 0));
14151         }
14152         else
14153         {
14154                 /* may need to quote it */
14155                 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14156         }
14157
14158         PQclear(res);
14159         destroyPQExpBuffer(query);
14160
14161         return result;
14162 }
14163
14164 /*
14165  * myFormatType --- local implementation of format_type for use with 7.0.
14166  */
14167 static char *
14168 myFormatType(const char *typname, int32 typmod)
14169 {
14170         char       *result;
14171         bool            isarray = false;
14172         PQExpBuffer buf = createPQExpBuffer();
14173
14174         /* Handle array types */
14175         if (typname[0] == '_')
14176         {
14177                 isarray = true;
14178                 typname++;
14179         }
14180
14181         /* Show lengths on bpchar and varchar */
14182         if (strcmp(typname, "bpchar") == 0)
14183         {
14184                 int                     len = (typmod - VARHDRSZ);
14185
14186                 appendPQExpBuffer(buf, "character");
14187                 if (len > 1)
14188                         appendPQExpBuffer(buf, "(%d)",
14189                                                           typmod - VARHDRSZ);
14190         }
14191         else if (strcmp(typname, "varchar") == 0)
14192         {
14193                 appendPQExpBuffer(buf, "character varying");
14194                 if (typmod != -1)
14195                         appendPQExpBuffer(buf, "(%d)",
14196                                                           typmod - VARHDRSZ);
14197         }
14198         else if (strcmp(typname, "numeric") == 0)
14199         {
14200                 appendPQExpBuffer(buf, "numeric");
14201                 if (typmod != -1)
14202                 {
14203                         int32           tmp_typmod;
14204                         int                     precision;
14205                         int                     scale;
14206
14207                         tmp_typmod = typmod - VARHDRSZ;
14208                         precision = (tmp_typmod >> 16) & 0xffff;
14209                         scale = tmp_typmod & 0xffff;
14210                         appendPQExpBuffer(buf, "(%d,%d)",
14211                                                           precision, scale);
14212                 }
14213         }
14214
14215         /*
14216          * char is an internal single-byte data type; Let's make sure we force it
14217          * through with quotes. - thomas 1998-12-13
14218          */
14219         else if (strcmp(typname, "char") == 0)
14220                 appendPQExpBuffer(buf, "\"char\"");
14221         else
14222                 appendPQExpBuffer(buf, "%s", fmtId(typname));
14223
14224         /* Append array qualifier for array types */
14225         if (isarray)
14226                 appendPQExpBuffer(buf, "[]");
14227
14228         result = pg_strdup(buf->data);
14229         destroyPQExpBuffer(buf);
14230
14231         return result;
14232 }
14233
14234 /*
14235  * fmtQualifiedId - convert a qualified name to the proper format for
14236  * the source database.
14237  *
14238  * Like fmtId, use the result before calling again.
14239  */
14240 static const char *
14241 fmtQualifiedId(Archive *fout, const char *schema, const char *id)
14242 {
14243         static PQExpBuffer id_return = NULL;
14244
14245         if (id_return)                          /* first time through? */
14246                 resetPQExpBuffer(id_return);
14247         else
14248                 id_return = createPQExpBuffer();
14249
14250         /* Suppress schema name if fetching from pre-7.3 DB */
14251         if (fout->remoteVersion >= 70300 && schema && *schema)
14252         {
14253                 appendPQExpBuffer(id_return, "%s.",
14254                                                   fmtId(schema));
14255         }
14256         appendPQExpBuffer(id_return, "%s",
14257                                           fmtId(id));
14258
14259         return id_return->data;
14260 }
14261
14262 /*
14263  * Return a column list clause for the given relation.
14264  *
14265  * Special case: if there are no undropped columns in the relation, return
14266  * "", not an invalid "()" column list.
14267  */
14268 static const char *
14269 fmtCopyColumnList(const TableInfo *ti)
14270 {
14271         static PQExpBuffer q = NULL;
14272         int                     numatts = ti->numatts;
14273         char      **attnames = ti->attnames;
14274         bool       *attisdropped = ti->attisdropped;
14275         bool            needComma;
14276         int                     i;
14277
14278         if (q)                                          /* first time through? */
14279                 resetPQExpBuffer(q);
14280         else
14281                 q = createPQExpBuffer();
14282
14283         appendPQExpBuffer(q, "(");
14284         needComma = false;
14285         for (i = 0; i < numatts; i++)
14286         {
14287                 if (attisdropped[i])
14288                         continue;
14289                 if (needComma)
14290                         appendPQExpBuffer(q, ", ");
14291                 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
14292                 needComma = true;
14293         }
14294
14295         if (!needComma)
14296                 return "";                              /* no undropped columns */
14297
14298         appendPQExpBuffer(q, ")");
14299         return q->data;
14300 }
14301
14302 /*
14303  * Execute an SQL query and verify that we got exactly one row back.
14304  */
14305 static PGresult *
14306 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
14307 {
14308         PGresult   *res;
14309         int                     ntups;
14310
14311         res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
14312
14313         /* Expecting a single result only */
14314         ntups = PQntuples(res);
14315         if (ntups != 1)
14316                 exit_horribly(NULL,
14317                                           ngettext("query returned %d row instead of one: %s\n",
14318                                                            "query returned %d rows instead of one: %s\n",
14319                                                                  ntups),
14320                                           ntups, query);
14321
14322         return res;
14323 }