]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_dump.c
pg_dump: fix double free of query results
[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 pgdump_cleanup_at_exit(int code, void *arg);
148 static void setup_connection(Archive *AH, const char *dumpencoding,
149                                  char *use_role);
150 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
151 static void expand_schema_name_patterns(Archive *fout,
152                                                         SimpleStringList *patterns,
153                                                         SimpleOidList *oids);
154 static void expand_table_name_patterns(Archive *fout,
155                                                    SimpleStringList *patterns,
156                                                    SimpleOidList *oids);
157 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid, Oid objoid);
158 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
159 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
160 static void dumpComment(Archive *fout, const char *target,
161                         const char *namespace, const char *owner,
162                         CatalogId catalogId, int subid, DumpId dumpId);
163 static int findComments(Archive *fout, Oid classoid, Oid objoid,
164                          CommentItem **items);
165 static int      collectComments(Archive *fout, CommentItem **items);
166 static void dumpSecLabel(Archive *fout, const char *target,
167                          const char *namespace, const char *owner,
168                          CatalogId catalogId, int subid, DumpId dumpId);
169 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
170                           SecLabelItem **items);
171 static int      collectSecLabels(Archive *fout, SecLabelItem **items);
172 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
173 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
174 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
175 static void dumpType(Archive *fout, TypeInfo *tyinfo);
176 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
177 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
178 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
179 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
180 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
181 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
182 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
183 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
184 static void dumpFunc(Archive *fout, FuncInfo *finfo);
185 static void dumpCast(Archive *fout, CastInfo *cast);
186 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
187 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
188 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
189 static void dumpCollation(Archive *fout, CollInfo *convinfo);
190 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
191 static void dumpRule(Archive *fout, RuleInfo *rinfo);
192 static void dumpAgg(Archive *fout, AggInfo *agginfo);
193 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
194 static void dumpTable(Archive *fout, TableInfo *tbinfo);
195 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
196 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
197 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
198 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
199 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
200 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
201 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
202 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
203 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
204 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
205 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
206 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
207 static void dumpUserMappings(Archive *fout,
208                                  const char *servername, const char *namespace,
209                                  const char *owner, CatalogId catalogId, DumpId dumpId);
210 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
211
212 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
213                 const char *type, const char *name, const char *subname,
214                 const char *tag, const char *nspname, const char *owner,
215                 const char *acls);
216
217 static void getDependencies(Archive *fout);
218 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
219 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
220 static void makeTableDataInfo(TableInfo *tbinfo, bool oids);
221 static void getTableDataFKConstraints(void);
222 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
223 static char *format_function_arguments_old(Archive *fout,
224                                                           FuncInfo *finfo, int nallargs,
225                                                           char **allargtypes,
226                                                           char **argmodes,
227                                                           char **argnames);
228 static char *format_function_signature(Archive *fout,
229                                                                            FuncInfo *finfo, bool honor_quotes);
230 static const char *convertRegProcReference(Archive *fout,
231                                                                                    const char *proc);
232 static const char *convertOperatorReference(Archive *fout, const char *opr);
233 static const char *convertTSFunction(Archive *fout, Oid funcOid);
234 static Oid      findLastBuiltinOid_V71(Archive *fout, const char *);
235 static Oid      findLastBuiltinOid_V70(Archive *fout);
236 static void selectSourceSchema(Archive *fout, const char *schemaName);
237 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
238 static char *myFormatType(const char *typname, int32 typmod);
239 static const char *fmtQualifiedId(Archive *fout,
240                                                                   const char *schema, const char *id);
241 static void getBlobs(Archive *fout);
242 static void dumpBlob(Archive *fout, BlobInfo *binfo);
243 static int      dumpBlobs(Archive *fout, void *arg);
244 static void dumpDatabase(Archive *AH);
245 static void dumpEncoding(Archive *AH);
246 static void dumpStdStrings(Archive *AH);
247 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
248                                                                 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
249 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
250                                                                  PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
251 static void binary_upgrade_set_pg_class_oids(Archive *fout,
252                                                                  PQExpBuffer upgrade_buffer,
253                                                                  Oid pg_class_oid, bool is_index);
254 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
255                                                                 DumpableObject *dobj,
256                                                                 const char *objlabel);
257 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
258 static const char *fmtCopyColumnList(const TableInfo *ti);
259 static PGresult *ExecuteSqlQueryForSingleRow(Archive *fout, char *query);
260
261 int
262 main(int argc, char **argv)
263 {
264         int                     c;
265         const char *filename = NULL;
266         const char *format = "p";
267         const char *dbname = NULL;
268         const char *pghost = NULL;
269         const char *pgport = NULL;
270         const char *username = NULL;
271         const char *dumpencoding = NULL;
272         bool            oids = false;
273         TableInfo  *tblinfo;
274         int                     numTables;
275         DumpableObject **dobjs;
276         int                     numObjs;
277         int                     i;
278         enum trivalue prompt_password = TRI_DEFAULT;
279         int                     compressLevel = -1;
280         int                     plainText = 0;
281         int                     outputClean = 0;
282         int                     outputCreateDB = 0;
283         bool            outputBlobs = false;
284         int                     outputNoOwner = 0;
285         char       *outputSuperuser = NULL;
286         char       *use_role = NULL;
287         int                     my_version;
288         int                     optindex;
289         RestoreOptions *ropt;
290         ArchiveFormat archiveFormat = archUnknown;
291         ArchiveMode archiveMode;
292         Archive    *fout;                               /* the script file */
293
294         static int      disable_triggers = 0;
295         static int      outputNoTablespaces = 0;
296         static int      use_setsessauth = 0;
297
298         static struct option long_options[] = {
299                 {"data-only", no_argument, NULL, 'a'},
300                 {"blobs", no_argument, NULL, 'b'},
301                 {"clean", no_argument, NULL, 'c'},
302                 {"create", no_argument, NULL, 'C'},
303                 {"file", required_argument, NULL, 'f'},
304                 {"format", required_argument, NULL, 'F'},
305                 {"host", required_argument, NULL, 'h'},
306                 {"ignore-version", no_argument, NULL, 'i'},
307                 {"no-reconnect", no_argument, NULL, 'R'},
308                 {"oids", no_argument, NULL, 'o'},
309                 {"no-owner", no_argument, NULL, 'O'},
310                 {"port", required_argument, NULL, 'p'},
311                 {"schema", required_argument, NULL, 'n'},
312                 {"exclude-schema", required_argument, NULL, 'N'},
313                 {"schema-only", no_argument, NULL, 's'},
314                 {"superuser", required_argument, NULL, 'S'},
315                 {"table", required_argument, NULL, 't'},
316                 {"exclude-table", required_argument, NULL, 'T'},
317                 {"no-password", no_argument, NULL, 'w'},
318                 {"password", no_argument, NULL, 'W'},
319                 {"username", required_argument, NULL, 'U'},
320                 {"verbose", no_argument, NULL, 'v'},
321                 {"no-privileges", no_argument, NULL, 'x'},
322                 {"no-acl", no_argument, NULL, 'x'},
323                 {"compress", required_argument, NULL, 'Z'},
324                 {"encoding", required_argument, NULL, 'E'},
325                 {"help", no_argument, NULL, '?'},
326                 {"version", no_argument, NULL, 'V'},
327
328                 /*
329                  * the following options don't have an equivalent short option letter
330                  */
331                 {"attribute-inserts", no_argument, &column_inserts, 1},
332                 {"binary-upgrade", no_argument, &binary_upgrade, 1},
333                 {"column-inserts", no_argument, &column_inserts, 1},
334                 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
335                 {"disable-triggers", no_argument, &disable_triggers, 1},
336                 {"exclude-table-data", required_argument, NULL, 4},
337                 {"inserts", no_argument, &dump_inserts, 1},
338                 {"lock-wait-timeout", required_argument, NULL, 2},
339                 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
340                 {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
341                 {"role", required_argument, NULL, 3},
342                 {"section", required_argument, NULL, 5},
343                 {"serializable-deferrable", no_argument, &serializable_deferrable, 1},
344                 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
345                 {"no-security-labels", no_argument, &no_security_labels, 1},
346                 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
347
348                 {NULL, 0, NULL, 0}
349         };
350
351         set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
352
353         g_verbose = false;
354
355         strcpy(g_comment_start, "-- ");
356         g_comment_end[0] = '\0';
357         strcpy(g_opaque_type, "opaque");
358
359         dataOnly = schemaOnly = false;
360         dumpSections = DUMP_UNSECTIONED;
361         lockWaitTimeout = NULL;
362
363         progname = get_progname(argv[0]);
364
365         /* Set default options based on progname */
366         if (strcmp(progname, "pg_backup") == 0)
367                 format = "c";
368
369         if (argc > 1)
370         {
371                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
372                 {
373                         help(progname);
374                         exit_nicely(0);
375                 }
376                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
377                 {
378                         puts("pg_dump (PostgreSQL) " PG_VERSION);
379                         exit_nicely(0);
380                 }
381         }
382
383         while ((c = getopt_long(argc, argv, "abcCE:f:F:h:in:N:oOp:RsS:t:T:U:vwWxZ:",
384                                                         long_options, &optindex)) != -1)
385         {
386                 switch (c)
387                 {
388                         case 'a':                       /* Dump data only */
389                                 dataOnly = true;
390                                 break;
391
392                         case 'b':                       /* Dump blobs */
393                                 outputBlobs = true;
394                                 break;
395
396                         case 'c':                       /* clean (i.e., drop) schema prior to create */
397                                 outputClean = 1;
398                                 break;
399
400                         case 'C':                       /* Create DB */
401                                 outputCreateDB = 1;
402                                 break;
403
404                         case 'E':                       /* Dump encoding */
405                                 dumpencoding = optarg;
406                                 break;
407
408                         case 'f':
409                                 filename = optarg;
410                                 break;
411
412                         case 'F':
413                                 format = optarg;
414                                 break;
415
416                         case 'h':                       /* server host */
417                                 pghost = optarg;
418                                 break;
419
420                         case 'i':
421                                 /* ignored, deprecated option */
422                                 break;
423
424                         case 'n':                       /* include schema(s) */
425                                 simple_string_list_append(&schema_include_patterns, optarg);
426                                 include_everything = false;
427                                 break;
428
429                         case 'N':                       /* exclude schema(s) */
430                                 simple_string_list_append(&schema_exclude_patterns, optarg);
431                                 break;
432
433                         case 'o':                       /* Dump oids */
434                                 oids = true;
435                                 break;
436
437                         case 'O':                       /* Don't reconnect to match owner */
438                                 outputNoOwner = 1;
439                                 break;
440
441                         case 'p':                       /* server port */
442                                 pgport = optarg;
443                                 break;
444
445                         case 'R':
446                                 /* no-op, still accepted for backwards compatibility */
447                                 break;
448
449                         case 's':                       /* dump schema only */
450                                 schemaOnly = true;
451                                 break;
452
453                         case 'S':                       /* Username for superuser in plain text output */
454                                 outputSuperuser = pg_strdup(optarg);
455                                 break;
456
457                         case 't':                       /* include table(s) */
458                                 simple_string_list_append(&table_include_patterns, optarg);
459                                 include_everything = false;
460                                 break;
461
462                         case 'T':                       /* exclude table(s) */
463                                 simple_string_list_append(&table_exclude_patterns, optarg);
464                                 break;
465
466                         case 'U':
467                                 username = optarg;
468                                 break;
469
470                         case 'v':                       /* verbose */
471                                 g_verbose = true;
472                                 break;
473
474                         case 'w':
475                                 prompt_password = TRI_NO;
476                                 break;
477
478                         case 'W':
479                                 prompt_password = TRI_YES;
480                                 break;
481
482                         case 'x':                       /* skip ACL dump */
483                                 aclsSkip = true;
484                                 break;
485
486                         case 'Z':                       /* Compression Level */
487                                 compressLevel = atoi(optarg);
488                                 break;
489
490                         case 0:
491                                 /* This covers the long options. */
492                                 break;
493
494                         case 2:                         /* lock-wait-timeout */
495                                 lockWaitTimeout = optarg;
496                                 break;
497
498                         case 3:                         /* SET ROLE */
499                                 use_role = optarg;
500                                 break;
501
502                         case 4:                 /* exclude table(s) data */
503                                 simple_string_list_append(&tabledata_exclude_patterns, optarg);
504                                 break;
505
506                         case 5:                         /* section */
507                                 set_section(optarg, &dumpSections);
508                                 break;
509
510                         default:
511                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
512                                 exit_nicely(1);
513                 }
514         }
515
516         /* Get database name from command line */
517         if (optind < argc)
518                 dbname = argv[optind++];
519
520         /* Complain if any arguments remain */
521         if (optind < argc)
522         {
523                 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
524                                 progname, argv[optind]);
525                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
526                                 progname);
527                 exit_nicely(1);
528         }
529
530         /* --column-inserts implies --inserts */
531         if (column_inserts)
532                 dump_inserts = 1;
533
534         if (dataOnly && schemaOnly)
535                 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
536
537         if ((dataOnly || schemaOnly) && dumpSections != DUMP_UNSECTIONED)
538                 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used with --section\n");
539
540         if (dataOnly)
541                 dumpSections = DUMP_DATA;
542         else if (schemaOnly)
543                 dumpSections = DUMP_PRE_DATA | DUMP_POST_DATA;
544         else if ( dumpSections != DUMP_UNSECTIONED)
545         {
546                 dataOnly = dumpSections == DUMP_DATA;
547                 schemaOnly = !(dumpSections & DUMP_DATA);
548         }
549
550         if (dataOnly && outputClean)
551                 exit_horribly(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
552
553         if (dump_inserts && oids)
554         {
555                 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
556                 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
557                 exit_nicely(1);
558         }
559
560         /* Identify archive format to emit */
561         archiveFormat = parseArchiveFormat(format, &archiveMode);
562
563         /* archiveFormat specific setup */
564         if (archiveFormat == archNull)
565                 plainText = 1;
566
567         /* Custom and directory formats are compressed by default, others not */
568         if (compressLevel == -1)
569         {
570                 if (archiveFormat == archCustom || archiveFormat == archDirectory)
571                         compressLevel = Z_DEFAULT_COMPRESSION;
572                 else
573                         compressLevel = 0;
574         }
575
576         /* Open the output file */
577         fout = CreateArchive(filename, archiveFormat, compressLevel, archiveMode);
578         on_exit_nicely(pgdump_cleanup_at_exit, fout);
579
580         if (fout == NULL)
581                 exit_horribly(NULL, "could not open output file \"%s\" for writing\n", filename);
582
583         /* Let the archiver know how noisy to be */
584         fout->verbose = g_verbose;
585
586         my_version = parse_version(PG_VERSION);
587         if (my_version < 0)
588                 exit_horribly(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
589
590         /*
591          * We allow the server to be back to 7.0, and up to any minor release of
592          * our own major version.  (See also version check in pg_dumpall.c.)
593          */
594         fout->minRemoteVersion = 70000;
595         fout->maxRemoteVersion = (my_version / 100) * 100 + 99;
596
597         /*
598          * Open the database using the Archiver, so it knows about it. Errors mean
599          * death.
600          */
601         ConnectDatabase(fout, dbname, pghost, pgport, username, prompt_password);
602         setup_connection(fout, dumpencoding, use_role);
603
604         /*
605          * Disable security label support if server version < v9.1.x (prevents
606          * access to nonexistent pg_seclabel catalog)
607          */
608         if (fout->remoteVersion < 90100)
609                 no_security_labels = 1;
610
611         /*
612          * Start transaction-snapshot mode transaction to dump consistent data.
613          */
614         ExecuteSqlStatement(fout, "BEGIN");
615         if (fout->remoteVersion >= 90100)
616         {
617                 if (serializable_deferrable)
618                         ExecuteSqlStatement(fout,
619                                                                 "SET TRANSACTION ISOLATION LEVEL "
620                                                                 "SERIALIZABLE, READ ONLY, DEFERRABLE");
621                 else
622                         ExecuteSqlStatement(fout,
623                                                                 "SET TRANSACTION ISOLATION LEVEL "
624                                                                 "REPEATABLE READ");
625         }
626         else
627                 ExecuteSqlStatement(fout,
628                                                         "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
629
630         /* Select the appropriate subquery to convert user IDs to names */
631         if (fout->remoteVersion >= 80100)
632                 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
633         else if (fout->remoteVersion >= 70300)
634                 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
635         else
636                 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
637
638         /* Find the last built-in OID, if needed */
639         if (fout->remoteVersion < 70300)
640         {
641                 if (fout->remoteVersion >= 70100)
642                         g_last_builtin_oid = findLastBuiltinOid_V71(fout,
643                                 PQdb(GetConnection(fout)));
644                 else
645                         g_last_builtin_oid = findLastBuiltinOid_V70(fout);
646                 if (g_verbose)
647                         write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
648         }
649
650         /* Expand schema selection patterns into OID lists */
651         if (schema_include_patterns.head != NULL)
652         {
653                 expand_schema_name_patterns(fout, &schema_include_patterns,
654                                                                         &schema_include_oids);
655                 if (schema_include_oids.head == NULL)
656                         exit_horribly(NULL, "No matching schemas were found\n");
657         }
658         expand_schema_name_patterns(fout, &schema_exclude_patterns,
659                                                                 &schema_exclude_oids);
660         /* non-matching exclusion patterns aren't an error */
661
662         /* Expand table selection patterns into OID lists */
663         if (table_include_patterns.head != NULL)
664         {
665                 expand_table_name_patterns(fout, &table_include_patterns,
666                                                                    &table_include_oids);
667                 if (table_include_oids.head == NULL)
668                         exit_horribly(NULL, "No matching tables were found\n");
669         }
670         expand_table_name_patterns(fout, &table_exclude_patterns,
671                                                            &table_exclude_oids);
672
673         expand_table_name_patterns(fout, &tabledata_exclude_patterns,
674                                                            &tabledata_exclude_oids);
675
676         /* non-matching exclusion patterns aren't an error */
677
678         /*
679          * Dumping blobs is now default unless we saw an inclusion switch or -s
680          * ... but even if we did see one of these, -b turns it back on.
681          */
682         if (include_everything && !schemaOnly)
683                 outputBlobs = true;
684
685         /*
686          * Now scan the database and create DumpableObject structs for all the
687          * objects we intend to dump.
688          */
689         tblinfo = getSchemaData(fout, &numTables);
690
691         if (fout->remoteVersion < 80400)
692                 guessConstraintInheritance(tblinfo, numTables);
693
694         if (!schemaOnly)
695         {
696                 getTableData(tblinfo, numTables, oids);
697                 if (dataOnly)
698                         getTableDataFKConstraints();
699         }
700
701         if (outputBlobs)
702                 getBlobs(fout);
703
704         /*
705          * Collect dependency data to assist in ordering the objects.
706          */
707         getDependencies(fout);
708
709         /*
710          * Sort the objects into a safe dump order (no forward references).
711          *
712          * In 7.3 or later, we can rely on dependency information to help us
713          * determine a safe order, so the initial sort is mostly for cosmetic
714          * purposes: we sort by name to ensure that logically identical schemas
715          * will dump identically.  Before 7.3 we don't have dependencies and we
716          * use OID ordering as an (unreliable) guide to creation order.
717          */
718         getDumpableObjects(&dobjs, &numObjs);
719
720         if (fout->remoteVersion >= 70300)
721                 sortDumpableObjectsByTypeName(dobjs, numObjs);
722         else
723                 sortDumpableObjectsByTypeOid(dobjs, numObjs);
724
725         sortDumpableObjects(dobjs, numObjs);
726
727         /*
728          * Create archive TOC entries for all the objects to be dumped, in a safe
729          * order.
730          */
731
732         /* First the special ENCODING and STDSTRINGS entries. */
733         dumpEncoding(fout);
734         dumpStdStrings(fout);
735
736         /* The database item is always next, unless we don't want it at all */
737         if (include_everything && !dataOnly)
738                 dumpDatabase(fout);
739
740         /* Now the rearrangeable objects. */
741         for (i = 0; i < numObjs; i++)
742                 dumpDumpableObject(fout, dobjs[i]);
743
744         /*
745          * And finally we can do the actual output.
746          */
747         if (plainText)
748         {
749                 ropt = NewRestoreOptions();
750                 ropt->filename = filename;
751                 ropt->dropSchema = outputClean;
752                 ropt->aclsSkip = aclsSkip;
753                 ropt->superuser = outputSuperuser;
754                 ropt->createDB = outputCreateDB;
755                 ropt->noOwner = outputNoOwner;
756                 ropt->noTablespace = outputNoTablespaces;
757                 ropt->disable_triggers = disable_triggers;
758                 ropt->use_setsessauth = use_setsessauth;
759                 ropt->dataOnly = dataOnly;
760
761                 if (compressLevel == -1)
762                         ropt->compression = 0;
763                 else
764                         ropt->compression = compressLevel;
765
766                 ropt->suppressDumpWarnings = true;              /* We've already shown them */
767
768                 RestoreArchive(fout, ropt);
769         }
770
771         CloseArchive(fout);
772
773         exit_nicely(0);
774 }
775
776
777 static void
778 help(const char *progname)
779 {
780         printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
781         printf(_("Usage:\n"));
782         printf(_("  %s [OPTION]... [DBNAME]\n"), progname);
783
784         printf(_("\nGeneral options:\n"));
785         printf(_("  -f, --file=FILENAME         output file or directory name\n"));
786         printf(_("  -F, --format=c|d|t|p        output file format (custom, directory, tar,\n"
787                          "                              plain text (default))\n"));
788         printf(_("  -v, --verbose               verbose mode\n"));
789         printf(_("  -Z, --compress=0-9          compression level for compressed formats\n"));
790         printf(_("  --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
791         printf(_("  --help                      show this help, then exit\n"));
792         printf(_("  --version                   output version information, then exit\n"));
793
794         printf(_("\nOptions controlling the output content:\n"));
795         printf(_("  -a, --data-only             dump only the data, not the schema\n"));
796         printf(_("  -b, --blobs                 include large objects in dump\n"));
797         printf(_("  -c, --clean                 clean (drop) database objects before recreating\n"));
798         printf(_("  -C, --create                include commands to create database in dump\n"));
799         printf(_("  -E, --encoding=ENCODING     dump the data in encoding ENCODING\n"));
800         printf(_("  -n, --schema=SCHEMA         dump the named schema(s) only\n"));
801         printf(_("  -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
802         printf(_("  -o, --oids                  include OIDs in dump\n"));
803         printf(_("  -O, --no-owner              skip restoration of object ownership in\n"
804                          "                              plain-text format\n"));
805         printf(_("  -s, --schema-only           dump only the schema, no data\n"));
806         printf(_("  -S, --superuser=NAME        superuser user name to use in plain-text format\n"));
807         printf(_("  -t, --table=TABLE           dump the named table(s) only\n"));
808         printf(_("  -T, --exclude-table=TABLE   do NOT dump the named table(s)\n"));
809         printf(_("  -x, --no-privileges         do not dump privileges (grant/revoke)\n"));
810         printf(_("  --binary-upgrade            for use by upgrade utilities only\n"));
811         printf(_("  --column-inserts            dump data as INSERT commands with column names\n"));
812         printf(_("  --disable-dollar-quoting    disable dollar quoting, use SQL standard quoting\n"));
813         printf(_("  --disable-triggers          disable triggers during data-only restore\n"));
814         printf(_("  --exclude-table-data=TABLE  do NOT dump data for the named table(s)\n"));
815         printf(_("  --inserts                   dump data as INSERT commands, rather than COPY\n"));
816         printf(_("  --no-security-labels        do not dump security label assignments\n"));
817         printf(_("  --no-tablespaces            do not dump tablespace assignments\n"));
818         printf(_("  --no-unlogged-table-data    do not dump unlogged table data\n"));
819         printf(_("  --quote-all-identifiers     quote all identifiers, even if not key words\n"));
820         printf(_("  --section=SECTION           dump named section (pre-data, data, or post-data)\n"));
821         printf(_("  --serializable-deferrable   wait until the dump can run without anomalies\n"));
822         printf(_("  --use-set-session-authorization\n"
823                          "                              use SET SESSION AUTHORIZATION commands instead of\n"
824         "                              ALTER OWNER commands to set ownership\n"));
825
826         printf(_("\nConnection options:\n"));
827         printf(_("  -h, --host=HOSTNAME      database server host or socket directory\n"));
828         printf(_("  -p, --port=PORT          database server port number\n"));
829         printf(_("  -U, --username=NAME      connect as specified database user\n"));
830         printf(_("  -w, --no-password        never prompt for password\n"));
831         printf(_("  -W, --password           force password prompt (should happen automatically)\n"));
832         printf(_("  --role=ROLENAME          do SET ROLE before dump\n"));
833
834         printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
835                          "variable value is used.\n\n"));
836         printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
837 }
838
839 static void
840 pgdump_cleanup_at_exit(int code, void *arg)
841 {
842         Archive    *AH = (Archive *) arg;
843
844         DisconnectDatabase(AH);
845 }
846
847 static void
848 setup_connection(Archive *AH, const char *dumpencoding, char *use_role)
849 {
850         PGconn     *conn = GetConnection(AH);
851         const char *std_strings;
852
853         /* Set the client encoding if requested */
854         if (dumpencoding)
855         {
856                 if (PQsetClientEncoding(conn, dumpencoding) < 0)
857                         exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
858                                                   dumpencoding);
859         }
860
861         /*
862          * Get the active encoding and the standard_conforming_strings setting, so
863          * we know how to escape strings.
864          */
865         AH->encoding = PQclientEncoding(conn);
866
867         std_strings = PQparameterStatus(conn, "standard_conforming_strings");
868         AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
869
870         /* Set the role if requested */
871         if (use_role && AH->remoteVersion >= 80100)
872         {
873                 PQExpBuffer query = createPQExpBuffer();
874
875                 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
876                 ExecuteSqlStatement(AH, query->data);
877                 destroyPQExpBuffer(query);
878         }
879
880         /* Set the datestyle to ISO to ensure the dump's portability */
881         ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
882
883         /* Likewise, avoid using sql_standard intervalstyle */
884         if (AH->remoteVersion >= 80400)
885                 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
886
887         /*
888          * If supported, set extra_float_digits so that we can dump float data
889          * exactly (given correctly implemented float I/O code, anyway)
890          */
891         if (AH->remoteVersion >= 90000)
892                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
893         else if (AH->remoteVersion >= 70400)
894                 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
895
896         /*
897          * If synchronized scanning is supported, disable it, to prevent
898          * unpredictable changes in row ordering across a dump and reload.
899          */
900         if (AH->remoteVersion >= 80300)
901                 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
902
903         /*
904          * Disable timeouts if supported.
905          */
906         if (AH->remoteVersion >= 70300)
907                 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
908
909         /*
910          * Quote all identifiers, if requested.
911          */
912         if (quote_all_identifiers && AH->remoteVersion >= 90100)
913                 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
914 }
915
916 static ArchiveFormat
917 parseArchiveFormat(const char *format, ArchiveMode *mode)
918 {
919         ArchiveFormat archiveFormat;
920
921         *mode = archModeWrite;
922
923         if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
924         {
925                 /* This is used by pg_dumpall, and is not documented */
926                 archiveFormat = archNull;
927                 *mode = archModeAppend;
928         }
929         else if (pg_strcasecmp(format, "c") == 0)
930                 archiveFormat = archCustom;
931         else if (pg_strcasecmp(format, "custom") == 0)
932                 archiveFormat = archCustom;
933         else if (pg_strcasecmp(format, "d") == 0)
934                 archiveFormat = archDirectory;
935         else if (pg_strcasecmp(format, "directory") == 0)
936                 archiveFormat = archDirectory;
937         else if (pg_strcasecmp(format, "f") == 0 || pg_strcasecmp(format, "file") == 0)
938
939                 /*
940                  * Dump files into the current directory; for demonstration only, not
941                  * documented.
942                  */
943                 archiveFormat = archFiles;
944         else if (pg_strcasecmp(format, "p") == 0)
945                 archiveFormat = archNull;
946         else if (pg_strcasecmp(format, "plain") == 0)
947                 archiveFormat = archNull;
948         else if (pg_strcasecmp(format, "t") == 0)
949                 archiveFormat = archTar;
950         else if (pg_strcasecmp(format, "tar") == 0)
951                 archiveFormat = archTar;
952         else
953                 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
954         return archiveFormat;
955 }
956
957 /*
958  * Find the OIDs of all schemas matching the given list of patterns,
959  * and append them to the given OID list.
960  */
961 static void
962 expand_schema_name_patterns(Archive *fout,
963                                                         SimpleStringList *patterns,
964                                                         SimpleOidList *oids)
965 {
966         PQExpBuffer query;
967         PGresult   *res;
968         SimpleStringListCell *cell;
969         int                     i;
970
971         if (patterns->head == NULL)
972                 return;                                 /* nothing to do */
973
974         if (fout->remoteVersion < 70300)
975                 exit_horribly(NULL, "server version must be at least 7.3 to use schema selection switches\n");
976
977         query = createPQExpBuffer();
978
979         /*
980          * We use UNION ALL rather than UNION; this might sometimes result in
981          * duplicate entries in the OID list, but we don't care.
982          */
983
984         for (cell = patterns->head; cell; cell = cell->next)
985         {
986                 if (cell != patterns->head)
987                         appendPQExpBuffer(query, "UNION ALL\n");
988                 appendPQExpBuffer(query,
989                                                   "SELECT oid FROM pg_catalog.pg_namespace n\n");
990                 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
991                                                           false, NULL, "n.nspname", NULL, NULL);
992         }
993
994         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
995
996         for (i = 0; i < PQntuples(res); i++)
997         {
998                 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
999         }
1000
1001         PQclear(res);
1002         destroyPQExpBuffer(query);
1003 }
1004
1005 /*
1006  * Find the OIDs of all tables matching the given list of patterns,
1007  * and append them to the given OID list.
1008  */
1009 static void
1010 expand_table_name_patterns(Archive *fout,
1011                                                    SimpleStringList *patterns, SimpleOidList *oids)
1012 {
1013         PQExpBuffer query;
1014         PGresult   *res;
1015         SimpleStringListCell *cell;
1016         int                     i;
1017
1018         if (patterns->head == NULL)
1019                 return;                                 /* nothing to do */
1020
1021         query = createPQExpBuffer();
1022
1023         /*
1024          * We use UNION ALL rather than UNION; this might sometimes result in
1025          * duplicate entries in the OID list, but we don't care.
1026          */
1027
1028         for (cell = patterns->head; cell; cell = cell->next)
1029         {
1030                 if (cell != patterns->head)
1031                         appendPQExpBuffer(query, "UNION ALL\n");
1032                 appendPQExpBuffer(query,
1033                                                   "SELECT c.oid"
1034                                                   "\nFROM pg_catalog.pg_class c"
1035                 "\n     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1036                                                   "\nWHERE c.relkind in ('%c', '%c', '%c', '%c')\n",
1037                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1038                                                   RELKIND_FOREIGN_TABLE);
1039                 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1040                                                           false, "n.nspname", "c.relname", NULL,
1041                                                           "pg_catalog.pg_table_is_visible(c.oid)");
1042         }
1043
1044         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1045
1046         for (i = 0; i < PQntuples(res); i++)
1047         {
1048                 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1049         }
1050
1051         PQclear(res);
1052         destroyPQExpBuffer(query);
1053 }
1054
1055 /*
1056  * selectDumpableNamespace: policy-setting subroutine
1057  *              Mark a namespace as to be dumped or not
1058  */
1059 static void
1060 selectDumpableNamespace(NamespaceInfo *nsinfo)
1061 {
1062         /*
1063          * If specific tables are being dumped, do not dump any complete
1064          * namespaces. If specific namespaces are being dumped, dump just those
1065          * namespaces. Otherwise, dump all non-system namespaces.
1066          */
1067         if (table_include_oids.head != NULL)
1068                 nsinfo->dobj.dump = false;
1069         else if (schema_include_oids.head != NULL)
1070                 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
1071                                                                                                    nsinfo->dobj.catId.oid);
1072         else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1073                          strcmp(nsinfo->dobj.name, "information_schema") == 0)
1074                 nsinfo->dobj.dump = false;
1075         else
1076                 nsinfo->dobj.dump = true;
1077
1078         /*
1079          * In any case, a namespace can be excluded by an exclusion switch
1080          */
1081         if (nsinfo->dobj.dump &&
1082                 simple_oid_list_member(&schema_exclude_oids,
1083                                                            nsinfo->dobj.catId.oid))
1084                 nsinfo->dobj.dump = false;
1085 }
1086
1087 /*
1088  * selectDumpableTable: policy-setting subroutine
1089  *              Mark a table as to be dumped or not
1090  */
1091 static void
1092 selectDumpableTable(TableInfo *tbinfo)
1093 {
1094         /*
1095          * If specific tables are being dumped, dump just those tables; else, dump
1096          * according to the parent namespace's dump flag.
1097          */
1098         if (table_include_oids.head != NULL)
1099                 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1100                                                                                                    tbinfo->dobj.catId.oid);
1101         else
1102                 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1103
1104         /*
1105          * In any case, a table can be excluded by an exclusion switch
1106          */
1107         if (tbinfo->dobj.dump &&
1108                 simple_oid_list_member(&table_exclude_oids,
1109                                                            tbinfo->dobj.catId.oid))
1110                 tbinfo->dobj.dump = false;
1111 }
1112
1113 /*
1114  * selectDumpableType: policy-setting subroutine
1115  *              Mark a type as to be dumped or not
1116  *
1117  * If it's a table's rowtype or an autogenerated array type, we also apply a
1118  * special type code to facilitate sorting into the desired order.      (We don't
1119  * want to consider those to be ordinary types because that would bring tables
1120  * up into the datatype part of the dump order.)  We still set the object's
1121  * dump flag; that's not going to cause the dummy type to be dumped, but we
1122  * need it so that casts involving such types will be dumped correctly -- see
1123  * dumpCast.  This means the flag should be set the same as for the underlying
1124  * object (the table or base type).
1125  */
1126 static void
1127 selectDumpableType(TypeInfo *tyinfo)
1128 {
1129         /* skip complex types, except for standalone composite types */
1130         if (OidIsValid(tyinfo->typrelid) &&
1131                 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1132         {
1133                 TableInfo  *tytable = findTableByOid(tyinfo->typrelid);
1134
1135                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1136                 if (tytable != NULL)
1137                         tyinfo->dobj.dump = tytable->dobj.dump;
1138                 else
1139                         tyinfo->dobj.dump = false;
1140                 return;
1141         }
1142
1143         /* skip auto-generated array types */
1144         if (tyinfo->isArray)
1145         {
1146                 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1147                 /*
1148                  * Fall through to set the dump flag; we assume that the subsequent
1149                  * rules will do the same thing as they would for the array's base
1150                  * type.  (We cannot reliably look up the base type here, since
1151                  * getTypes may not have processed it yet.)
1152                  */
1153         }
1154
1155         /* dump only types in dumpable namespaces */
1156         if (!tyinfo->dobj.namespace->dobj.dump)
1157                 tyinfo->dobj.dump = false;
1158
1159         /* skip undefined placeholder types */
1160         else if (!tyinfo->isDefined)
1161                 tyinfo->dobj.dump = false;
1162
1163         else
1164                 tyinfo->dobj.dump = true;
1165 }
1166
1167 /*
1168  * selectDumpableDefaultACL: policy-setting subroutine
1169  *              Mark a default ACL as to be dumped or not
1170  *
1171  * For per-schema default ACLs, dump if the schema is to be dumped.
1172  * Otherwise dump if we are dumping "everything".  Note that dataOnly
1173  * and aclsSkip are checked separately.
1174  */
1175 static void
1176 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1177 {
1178         if (dinfo->dobj.namespace)
1179                 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1180         else
1181                 dinfo->dobj.dump = include_everything;
1182 }
1183
1184 /*
1185  * selectDumpableExtension: policy-setting subroutine
1186  *              Mark an extension as to be dumped or not
1187  *
1188  * Normally, we dump all extensions, or none of them if include_everything
1189  * is false (i.e., a --schema or --table switch was given).  However, in
1190  * binary-upgrade mode it's necessary to skip built-in extensions, since we
1191  * assume those will already be installed in the target database.  We identify
1192  * such extensions by their having OIDs in the range reserved for initdb.
1193  */
1194 static void
1195 selectDumpableExtension(ExtensionInfo *extinfo)
1196 {
1197         if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1198                 extinfo->dobj.dump = false;
1199         else
1200                 extinfo->dobj.dump = include_everything;
1201 }
1202
1203 /*
1204  * selectDumpableObject: policy-setting subroutine
1205  *              Mark a generic dumpable object as to be dumped or not
1206  *
1207  * Use this only for object types without a special-case routine above.
1208  */
1209 static void
1210 selectDumpableObject(DumpableObject *dobj)
1211 {
1212         /*
1213          * Default policy is to dump if parent namespace is dumpable, or always
1214          * for non-namespace-associated items.
1215          */
1216         if (dobj->namespace)
1217                 dobj->dump = dobj->namespace->dobj.dump;
1218         else
1219                 dobj->dump = true;
1220 }
1221
1222 /*
1223  *      Dump a table's contents for loading using the COPY command
1224  *      - this routine is called by the Archiver when it wants the table
1225  *        to be dumped.
1226  */
1227
1228 static int
1229 dumpTableData_copy(Archive *fout, void *dcontext)
1230 {
1231         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1232         TableInfo  *tbinfo = tdinfo->tdtable;
1233         const char *classname = tbinfo->dobj.name;
1234         const bool      hasoids = tbinfo->hasoids;
1235         const bool      oids = tdinfo->oids;
1236         PQExpBuffer q = createPQExpBuffer();
1237         PGconn     *conn = GetConnection(fout);
1238         PGresult   *res;
1239         int                     ret;
1240         char       *copybuf;
1241         const char *column_list;
1242
1243         if (g_verbose)
1244                 write_msg(NULL, "dumping contents of table %s\n", classname);
1245
1246         /*
1247          * Make sure we are in proper schema.  We will qualify the table name
1248          * below anyway (in case its name conflicts with a pg_catalog table); but
1249          * this ensures reproducible results in case the table contains regproc,
1250          * regclass, etc columns.
1251          */
1252         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1253
1254         /*
1255          * If possible, specify the column list explicitly so that we have no
1256          * possibility of retrieving data in the wrong column order.  (The default
1257          * column ordering of COPY will not be what we want in certain corner
1258          * cases involving ADD COLUMN and inheritance.)
1259          */
1260         if (fout->remoteVersion >= 70300)
1261                 column_list = fmtCopyColumnList(tbinfo);
1262         else
1263                 column_list = "";               /* can't select columns in COPY */
1264
1265         if (oids && hasoids)
1266         {
1267                 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1268                                                   fmtQualifiedId(fout,
1269                                                                                  tbinfo->dobj.namespace->dobj.name,
1270                                                                                  classname),
1271                                                   column_list);
1272         }
1273         else if (tdinfo->filtercond)
1274         {
1275                 /* Note: this syntax is only supported in 8.2 and up */
1276                 appendPQExpBufferStr(q, "COPY (SELECT ");
1277                 /* klugery to get rid of parens in column list */
1278                 if (strlen(column_list) > 2)
1279                 {
1280                         appendPQExpBufferStr(q, column_list + 1);
1281                         q->data[q->len - 1] = ' ';
1282                 }
1283                 else
1284                         appendPQExpBufferStr(q, "* ");
1285                 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1286                                                   fmtQualifiedId(fout,
1287                                                                                  tbinfo->dobj.namespace->dobj.name,
1288                                                                                  classname),
1289                                                   tdinfo->filtercond);
1290         }
1291         else
1292         {
1293                 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1294                                                   fmtQualifiedId(fout,
1295                                                                                  tbinfo->dobj.namespace->dobj.name,
1296                                                                                  classname),
1297                                                   column_list);
1298         }
1299         res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1300         PQclear(res);
1301
1302         for (;;)
1303         {
1304                 ret = PQgetCopyData(conn, &copybuf, 0);
1305
1306                 if (ret < 0)
1307                         break;                          /* done or error */
1308
1309                 if (copybuf)
1310                 {
1311                         WriteData(fout, copybuf, ret);
1312                         PQfreemem(copybuf);
1313                 }
1314
1315                 /* ----------
1316                  * THROTTLE:
1317                  *
1318                  * There was considerable discussion in late July, 2000 regarding
1319                  * slowing down pg_dump when backing up large tables. Users with both
1320                  * slow & fast (multi-processor) machines experienced performance
1321                  * degradation when doing a backup.
1322                  *
1323                  * Initial attempts based on sleeping for a number of ms for each ms
1324                  * of work were deemed too complex, then a simple 'sleep in each loop'
1325                  * implementation was suggested. The latter failed because the loop
1326                  * was too tight. Finally, the following was implemented:
1327                  *
1328                  * If throttle is non-zero, then
1329                  *              See how long since the last sleep.
1330                  *              Work out how long to sleep (based on ratio).
1331                  *              If sleep is more than 100ms, then
1332                  *                      sleep
1333                  *                      reset timer
1334                  *              EndIf
1335                  * EndIf
1336                  *
1337                  * where the throttle value was the number of ms to sleep per ms of
1338                  * work. The calculation was done in each loop.
1339                  *
1340                  * Most of the hard work is done in the backend, and this solution
1341                  * still did not work particularly well: on slow machines, the ratio
1342                  * was 50:1, and on medium paced machines, 1:1, and on fast
1343                  * multi-processor machines, it had little or no effect, for reasons
1344                  * that were unclear.
1345                  *
1346                  * Further discussion ensued, and the proposal was dropped.
1347                  *
1348                  * For those people who want this feature, it can be implemented using
1349                  * gettimeofday in each loop, calculating the time since last sleep,
1350                  * multiplying that by the sleep ratio, then if the result is more
1351                  * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1352                  * function to sleep for a subsecond period ie.
1353                  *
1354                  * select(0, NULL, NULL, NULL, &tvi);
1355                  *
1356                  * This will return after the interval specified in the structure tvi.
1357                  * Finally, call gettimeofday again to save the 'last sleep time'.
1358                  * ----------
1359                  */
1360         }
1361         archprintf(fout, "\\.\n\n\n");
1362
1363         if (ret == -2)
1364         {
1365                 /* copy data transfer failed */
1366                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1367                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1368                 write_msg(NULL, "The command was: %s\n", q->data);
1369                 exit_nicely(1);
1370         }
1371
1372         /* Check command status and return to normal libpq state */
1373         res = PQgetResult(conn);
1374         if (PQresultStatus(res) != PGRES_COMMAND_OK)
1375         {
1376                 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1377                 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1378                 write_msg(NULL, "The command was: %s\n", q->data);
1379                 exit_nicely(1);
1380         }
1381         PQclear(res);
1382
1383         destroyPQExpBuffer(q);
1384         return 1;
1385 }
1386
1387 /*
1388  * Dump table data using INSERT commands.
1389  *
1390  * Caution: when we restore from an archive file direct to database, the
1391  * INSERT commands emitted by this function have to be parsed by
1392  * pg_backup_db.c's ExecuteInsertCommands(), which will not handle comments,
1393  * E'' strings, or dollar-quoted strings.  So don't emit anything like that.
1394  */
1395 static int
1396 dumpTableData_insert(Archive *fout, void *dcontext)
1397 {
1398         TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1399         TableInfo  *tbinfo = tdinfo->tdtable;
1400         const char *classname = tbinfo->dobj.name;
1401         PQExpBuffer q = createPQExpBuffer();
1402         PGresult   *res;
1403         int                     tuple;
1404         int                     nfields;
1405         int                     field;
1406
1407         /*
1408          * Make sure we are in proper schema.  We will qualify the table name
1409          * below anyway (in case its name conflicts with a pg_catalog table); but
1410          * this ensures reproducible results in case the table contains regproc,
1411          * regclass, etc columns.
1412          */
1413         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1414
1415         if (fout->remoteVersion >= 70100)
1416         {
1417                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1418                                                   "SELECT * FROM ONLY %s",
1419                                                   fmtQualifiedId(fout,
1420                                                                                  tbinfo->dobj.namespace->dobj.name,
1421                                                                                  classname));
1422         }
1423         else
1424         {
1425                 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1426                                                   "SELECT * FROM %s",
1427                                                   fmtQualifiedId(fout,
1428                                                                                  tbinfo->dobj.namespace->dobj.name,
1429                                                                                  classname));
1430         }
1431         if (tdinfo->filtercond)
1432                 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1433
1434         ExecuteSqlStatement(fout, q->data);
1435
1436         while (1)
1437         {
1438                 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1439                                                           PGRES_TUPLES_OK);
1440                 nfields = PQnfields(res);
1441                 for (tuple = 0; tuple < PQntuples(res); tuple++)
1442                 {
1443                         archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1444                         if (nfields == 0)
1445                         {
1446                                 /* corner case for zero-column table */
1447                                 archprintf(fout, "DEFAULT VALUES;\n");
1448                                 continue;
1449                         }
1450                         if (column_inserts)
1451                         {
1452                                 resetPQExpBuffer(q);
1453                                 appendPQExpBuffer(q, "(");
1454                                 for (field = 0; field < nfields; field++)
1455                                 {
1456                                         if (field > 0)
1457                                                 appendPQExpBuffer(q, ", ");
1458                                         appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1459                                 }
1460                                 appendPQExpBuffer(q, ") ");
1461                                 archputs(q->data, fout);
1462                         }
1463                         archprintf(fout, "VALUES (");
1464                         for (field = 0; field < nfields; field++)
1465                         {
1466                                 if (field > 0)
1467                                         archprintf(fout, ", ");
1468                                 if (PQgetisnull(res, tuple, field))
1469                                 {
1470                                         archprintf(fout, "NULL");
1471                                         continue;
1472                                 }
1473
1474                                 /* XXX This code is partially duplicated in ruleutils.c */
1475                                 switch (PQftype(res, field))
1476                                 {
1477                                         case INT2OID:
1478                                         case INT4OID:
1479                                         case INT8OID:
1480                                         case OIDOID:
1481                                         case FLOAT4OID:
1482                                         case FLOAT8OID:
1483                                         case NUMERICOID:
1484                                                 {
1485                                                         /*
1486                                                          * These types are printed without quotes unless
1487                                                          * they contain values that aren't accepted by the
1488                                                          * scanner unquoted (e.g., 'NaN').      Note that
1489                                                          * strtod() and friends might accept NaN, so we
1490                                                          * can't use that to test.
1491                                                          *
1492                                                          * In reality we only need to defend against
1493                                                          * infinity and NaN, so we need not get too crazy
1494                                                          * about pattern matching here.
1495                                                          */
1496                                                         const char *s = PQgetvalue(res, tuple, field);
1497
1498                                                         if (strspn(s, "0123456789 +-eE.") == strlen(s))
1499                                                                 archprintf(fout, "%s", s);
1500                                                         else
1501                                                                 archprintf(fout, "'%s'", s);
1502                                                 }
1503                                                 break;
1504
1505                                         case BITOID:
1506                                         case VARBITOID:
1507                                                 archprintf(fout, "B'%s'",
1508                                                                    PQgetvalue(res, tuple, field));
1509                                                 break;
1510
1511                                         case BOOLOID:
1512                                                 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1513                                                         archprintf(fout, "true");
1514                                                 else
1515                                                         archprintf(fout, "false");
1516                                                 break;
1517
1518                                         default:
1519                                                 /* All other types are printed as string literals. */
1520                                                 resetPQExpBuffer(q);
1521                                                 appendStringLiteralAH(q,
1522                                                                                           PQgetvalue(res, tuple, field),
1523                                                                                           fout);
1524                                                 archputs(q->data, fout);
1525                                                 break;
1526                                 }
1527                         }
1528                         archprintf(fout, ");\n");
1529                 }
1530
1531                 if (PQntuples(res) <= 0)
1532                 {
1533                         PQclear(res);
1534                         break;
1535                 }
1536                 PQclear(res);
1537         }
1538
1539         archprintf(fout, "\n\n");
1540
1541         ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
1542
1543         destroyPQExpBuffer(q);
1544         return 1;
1545 }
1546
1547
1548 /*
1549  * dumpTableData -
1550  *        dump the contents of a single table
1551  *
1552  * Actually, this just makes an ArchiveEntry for the table contents.
1553  */
1554 static void
1555 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1556 {
1557         TableInfo  *tbinfo = tdinfo->tdtable;
1558         PQExpBuffer copyBuf = createPQExpBuffer();
1559         DataDumperPtr dumpFn;
1560         char       *copyStmt;
1561
1562         if (!dump_inserts)
1563         {
1564                 /* Dump/restore using COPY */
1565                 dumpFn = dumpTableData_copy;
1566                 /* must use 2 steps here 'cause fmtId is nonreentrant */
1567                 appendPQExpBuffer(copyBuf, "COPY %s ",
1568                                                   fmtId(tbinfo->dobj.name));
1569                 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1570                                                   fmtCopyColumnList(tbinfo),
1571                                           (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1572                 copyStmt = copyBuf->data;
1573         }
1574         else
1575         {
1576                 /* Restore using INSERT */
1577                 dumpFn = dumpTableData_insert;
1578                 copyStmt = NULL;
1579         }
1580
1581         ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1582                                  tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1583                                  NULL, tbinfo->rolname,
1584                                  false, "TABLE DATA", SECTION_DATA,
1585                                  "", "", copyStmt,
1586                                  tdinfo->dobj.dependencies, tdinfo->dobj.nDeps,
1587                                  dumpFn, tdinfo);
1588
1589         destroyPQExpBuffer(copyBuf);
1590 }
1591
1592 /*
1593  * getTableData -
1594  *        set up dumpable objects representing the contents of tables
1595  */
1596 static void
1597 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1598 {
1599         int                     i;
1600
1601         for (i = 0; i < numTables; i++)
1602         {
1603                 if (tblinfo[i].dobj.dump)
1604                         makeTableDataInfo(&(tblinfo[i]), oids);
1605         }
1606 }
1607
1608 /*
1609  * Make a dumpable object for the data of this specific table
1610  *
1611  * Note: we make a TableDataInfo if and only if we are going to dump the
1612  * table data; the "dump" flag in such objects isn't used.
1613  */
1614 static void
1615 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1616 {
1617         TableDataInfo *tdinfo;
1618
1619         /*
1620          * Nothing to do if we already decided to dump the table.  This will
1621          * happen for "config" tables.
1622          */
1623         if (tbinfo->dataObj != NULL)
1624                 return;
1625
1626         /* Skip VIEWs (no data to dump) */
1627         if (tbinfo->relkind == RELKIND_VIEW)
1628                 return;
1629         /* Skip SEQUENCEs (handled elsewhere) */
1630         if (tbinfo->relkind == RELKIND_SEQUENCE)
1631                 return;
1632         /* Skip FOREIGN TABLEs (no data to dump) */
1633         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
1634                 return;
1635
1636         /* Don't dump data in unlogged tables, if so requested */
1637         if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
1638                 no_unlogged_table_data)
1639                 return;
1640
1641         /* Check that the data is not explicitly excluded */
1642         if (simple_oid_list_member(&tabledata_exclude_oids,
1643                                                            tbinfo->dobj.catId.oid))
1644                 return;
1645
1646         /* OK, let's dump it */
1647         tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
1648
1649         tdinfo->dobj.objType = DO_TABLE_DATA;
1650
1651         /*
1652          * Note: use tableoid 0 so that this object won't be mistaken for
1653          * something that pg_depend entries apply to.
1654          */
1655         tdinfo->dobj.catId.tableoid = 0;
1656         tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
1657         AssignDumpId(&tdinfo->dobj);
1658         tdinfo->dobj.name = tbinfo->dobj.name;
1659         tdinfo->dobj.namespace = tbinfo->dobj.namespace;
1660         tdinfo->tdtable = tbinfo;
1661         tdinfo->oids = oids;
1662         tdinfo->filtercond = NULL;      /* might get set later */
1663         addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
1664
1665         tbinfo->dataObj = tdinfo;
1666 }
1667
1668 /*
1669  * getTableDataFKConstraints -
1670  *        add dump-order dependencies reflecting foreign key constraints
1671  *
1672  * This code is executed only in a data-only dump --- in schema+data dumps
1673  * we handle foreign key issues by not creating the FK constraints until
1674  * after the data is loaded.  In a data-only dump, however, we want to
1675  * order the table data objects in such a way that a table's referenced
1676  * tables are restored first.  (In the presence of circular references or
1677  * self-references this may be impossible; we'll detect and complain about
1678  * that during the dependency sorting step.)
1679  */
1680 static void
1681 getTableDataFKConstraints(void)
1682 {
1683         DumpableObject **dobjs;
1684         int                     numObjs;
1685         int                     i;
1686
1687         /* Search through all the dumpable objects for FK constraints */
1688         getDumpableObjects(&dobjs, &numObjs);
1689         for (i = 0; i < numObjs; i++)
1690         {
1691                 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
1692                 {
1693                         ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
1694                         TableInfo  *ftable;
1695
1696                         /* Not interesting unless both tables are to be dumped */
1697                         if (cinfo->contable == NULL ||
1698                                 cinfo->contable->dataObj == NULL)
1699                                 continue;
1700                         ftable = findTableByOid(cinfo->confrelid);
1701                         if (ftable == NULL ||
1702                                 ftable->dataObj == NULL)
1703                                 continue;
1704
1705                         /*
1706                          * Okay, make referencing table's TABLE_DATA object depend on the
1707                          * referenced table's TABLE_DATA object.
1708                          */
1709                         addObjectDependency(&cinfo->contable->dataObj->dobj,
1710                                                                 ftable->dataObj->dobj.dumpId);
1711                 }
1712         }
1713         free(dobjs);
1714 }
1715
1716
1717 /*
1718  * guessConstraintInheritance:
1719  *      In pre-8.4 databases, we can't tell for certain which constraints
1720  *      are inherited.  We assume a CHECK constraint is inherited if its name
1721  *      matches the name of any constraint in the parent.  Originally this code
1722  *      tried to compare the expression texts, but that can fail for various
1723  *      reasons --- for example, if the parent and child tables are in different
1724  *      schemas, reverse-listing of function calls may produce different text
1725  *      (schema-qualified or not) depending on search path.
1726  *
1727  *      In 8.4 and up we can rely on the conislocal field to decide which
1728  *      constraints must be dumped; much safer.
1729  *
1730  *      This function assumes all conislocal flags were initialized to TRUE.
1731  *      It clears the flag on anything that seems to be inherited.
1732  */
1733 static void
1734 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
1735 {
1736         int                     i,
1737                                 j,
1738                                 k;
1739
1740         for (i = 0; i < numTables; i++)
1741         {
1742                 TableInfo  *tbinfo = &(tblinfo[i]);
1743                 int                     numParents;
1744                 TableInfo **parents;
1745                 TableInfo  *parent;
1746
1747                 /* Sequences and views never have parents */
1748                 if (tbinfo->relkind == RELKIND_SEQUENCE ||
1749                         tbinfo->relkind == RELKIND_VIEW)
1750                         continue;
1751
1752                 /* Don't bother computing anything for non-target tables, either */
1753                 if (!tbinfo->dobj.dump)
1754                         continue;
1755
1756                 numParents = tbinfo->numParents;
1757                 parents = tbinfo->parents;
1758
1759                 if (numParents == 0)
1760                         continue;                       /* nothing to see here, move along */
1761
1762                 /* scan for inherited CHECK constraints */
1763                 for (j = 0; j < tbinfo->ncheck; j++)
1764                 {
1765                         ConstraintInfo *constr;
1766
1767                         constr = &(tbinfo->checkexprs[j]);
1768
1769                         for (k = 0; k < numParents; k++)
1770                         {
1771                                 int                     l;
1772
1773                                 parent = parents[k];
1774                                 for (l = 0; l < parent->ncheck; l++)
1775                                 {
1776                                         ConstraintInfo *pconstr = &(parent->checkexprs[l]);
1777
1778                                         if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
1779                                         {
1780                                                 constr->conislocal = false;
1781                                                 break;
1782                                         }
1783                                 }
1784                                 if (!constr->conislocal)
1785                                         break;
1786                         }
1787                 }
1788         }
1789 }
1790
1791
1792 /*
1793  * dumpDatabase:
1794  *      dump the database definition
1795  */
1796 static void
1797 dumpDatabase(Archive *fout)
1798 {
1799         PQExpBuffer dbQry = createPQExpBuffer();
1800         PQExpBuffer delQry = createPQExpBuffer();
1801         PQExpBuffer creaQry = createPQExpBuffer();
1802         PGconn     *conn = GetConnection(fout);
1803         PGresult   *res;
1804         int                     i_tableoid,
1805                                 i_oid,
1806                                 i_dba,
1807                                 i_encoding,
1808                                 i_collate,
1809                                 i_ctype,
1810                                 i_frozenxid,
1811                                 i_tablespace;
1812         CatalogId       dbCatId;
1813         DumpId          dbDumpId;
1814         const char *datname,
1815                            *dba,
1816                            *encoding,
1817                            *collate,
1818                            *ctype,
1819                            *tablespace;
1820         uint32          frozenxid;
1821
1822         datname = PQdb(conn);
1823
1824         if (g_verbose)
1825                 write_msg(NULL, "saving database definition\n");
1826
1827         /* Make sure we are in proper schema */
1828         selectSourceSchema(fout, "pg_catalog");
1829
1830         /* Get the database owner and parameters from pg_database */
1831         if (fout->remoteVersion >= 80400)
1832         {
1833                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1834                                                   "(%s datdba) AS dba, "
1835                                                   "pg_encoding_to_char(encoding) AS encoding, "
1836                                                   "datcollate, 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 >= 80200)
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                                           "shobj_description(oid, 'pg_database') AS description "
1853
1854                                                   "FROM pg_database "
1855                                                   "WHERE datname = ",
1856                                                   username_subquery);
1857                 appendStringLiteralAH(dbQry, datname, fout);
1858         }
1859         else if (fout->remoteVersion >= 80000)
1860         {
1861                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1862                                                   "(%s datdba) AS dba, "
1863                                                   "pg_encoding_to_char(encoding) AS encoding, "
1864                                            "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1865                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
1866                                                   "FROM pg_database "
1867                                                   "WHERE datname = ",
1868                                                   username_subquery);
1869                 appendStringLiteralAH(dbQry, datname, fout);
1870         }
1871         else if (fout->remoteVersion >= 70100)
1872         {
1873                 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1874                                                   "(%s datdba) AS dba, "
1875                                                   "pg_encoding_to_char(encoding) AS encoding, "
1876                                                   "NULL AS datcollate, NULL AS datctype, "
1877                                                   "0 AS datfrozenxid, "
1878                                                   "NULL AS tablespace "
1879                                                   "FROM pg_database "
1880                                                   "WHERE datname = ",
1881                                                   username_subquery);
1882                 appendStringLiteralAH(dbQry, datname, fout);
1883         }
1884         else
1885         {
1886                 appendPQExpBuffer(dbQry, "SELECT "
1887                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1888                                                   "oid, "
1889                                                   "(%s datdba) AS dba, "
1890                                                   "pg_encoding_to_char(encoding) AS encoding, "
1891                                                   "NULL AS datcollate, NULL AS datctype, "
1892                                                   "0 AS datfrozenxid, "
1893                                                   "NULL AS tablespace "
1894                                                   "FROM pg_database "
1895                                                   "WHERE datname = ",
1896                                                   username_subquery);
1897                 appendStringLiteralAH(dbQry, datname, fout);
1898         }
1899
1900         res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
1901
1902         i_tableoid = PQfnumber(res, "tableoid");
1903         i_oid = PQfnumber(res, "oid");
1904         i_dba = PQfnumber(res, "dba");
1905         i_encoding = PQfnumber(res, "encoding");
1906         i_collate = PQfnumber(res, "datcollate");
1907         i_ctype = PQfnumber(res, "datctype");
1908         i_frozenxid = PQfnumber(res, "datfrozenxid");
1909         i_tablespace = PQfnumber(res, "tablespace");
1910
1911         dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1912         dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1913         dba = PQgetvalue(res, 0, i_dba);
1914         encoding = PQgetvalue(res, 0, i_encoding);
1915         collate = PQgetvalue(res, 0, i_collate);
1916         ctype = PQgetvalue(res, 0, i_ctype);
1917         frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
1918         tablespace = PQgetvalue(res, 0, i_tablespace);
1919
1920         appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1921                                           fmtId(datname));
1922         if (strlen(encoding) > 0)
1923         {
1924                 appendPQExpBuffer(creaQry, " ENCODING = ");
1925                 appendStringLiteralAH(creaQry, encoding, fout);
1926         }
1927         if (strlen(collate) > 0)
1928         {
1929                 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
1930                 appendStringLiteralAH(creaQry, collate, fout);
1931         }
1932         if (strlen(ctype) > 0)
1933         {
1934                 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
1935                 appendStringLiteralAH(creaQry, ctype, fout);
1936         }
1937         if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1938                 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1939                                                   fmtId(tablespace));
1940         appendPQExpBuffer(creaQry, ";\n");
1941
1942         if (binary_upgrade)
1943         {
1944                 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
1945                 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
1946                                                   "SET datfrozenxid = '%u'\n"
1947                                                   "WHERE        datname = ",
1948                                                   frozenxid);
1949                 appendStringLiteralAH(creaQry, datname, fout);
1950                 appendPQExpBuffer(creaQry, ";\n");
1951
1952         }
1953
1954         appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1955                                           fmtId(datname));
1956
1957         dbDumpId = createDumpId();
1958
1959         ArchiveEntry(fout,
1960                                  dbCatId,               /* catalog ID */
1961                                  dbDumpId,              /* dump ID */
1962                                  datname,               /* Name */
1963                                  NULL,                  /* Namespace */
1964                                  NULL,                  /* Tablespace */
1965                                  dba,                   /* Owner */
1966                                  false,                 /* with oids */
1967                                  "DATABASE",    /* Desc */
1968                                  SECTION_PRE_DATA,              /* Section */
1969                                  creaQry->data, /* Create */
1970                                  delQry->data,  /* Del */
1971                                  NULL,                  /* Copy */
1972                                  NULL,                  /* Deps */
1973                                  0,                             /* # Deps */
1974                                  NULL,                  /* Dumper */
1975                                  NULL);                 /* Dumper Arg */
1976
1977         /*
1978          * pg_largeobject and pg_largeobject_metadata come from the old system
1979          * intact, so set their relfrozenxids.
1980          */
1981         if (binary_upgrade)
1982         {
1983                 PGresult   *lo_res;
1984                 PQExpBuffer loFrozenQry = createPQExpBuffer();
1985                 PQExpBuffer loOutQry = createPQExpBuffer();
1986                 int                     i_relfrozenxid;
1987
1988                 /*
1989                  * pg_largeobject
1990                  */
1991                 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
1992                                                   "FROM pg_catalog.pg_class\n"
1993                                                   "WHERE oid = %u;\n",
1994                                                   LargeObjectRelationId);
1995
1996                 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
1997
1998                 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
1999
2000                 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject.relfrozenxid\n");
2001                 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2002                                                   "SET relfrozenxid = '%u'\n"
2003                                                   "WHERE oid = %u;\n",
2004                                                   atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2005                                                   LargeObjectRelationId);
2006                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2007                                          "pg_largeobject", NULL, NULL, "",
2008                                          false, "pg_largeobject", SECTION_PRE_DATA,
2009                                          loOutQry->data, "", NULL,
2010                                          NULL, 0,
2011                                          NULL, NULL);
2012
2013                 PQclear(lo_res);
2014
2015                 /*
2016                  * pg_largeobject_metadata
2017                  */
2018                 if (fout->remoteVersion >= 90000)
2019                 {
2020                         resetPQExpBuffer(loFrozenQry);
2021                         resetPQExpBuffer(loOutQry);
2022
2023                         appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2024                                                           "FROM pg_catalog.pg_class\n"
2025                                                           "WHERE oid = %u;\n",
2026                                                           LargeObjectMetadataRelationId);
2027
2028                         lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2029
2030                         i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2031
2032                         appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata.relfrozenxid\n");
2033                         appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2034                                                           "SET relfrozenxid = '%u'\n"
2035                                                           "WHERE oid = %u;\n",
2036                                                           atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2037                                                           LargeObjectMetadataRelationId);
2038                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
2039                                                  "pg_largeobject_metadata", NULL, NULL, "",
2040                                                  false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2041                                                  loOutQry->data, "", NULL,
2042                                                  NULL, 0,
2043                                                  NULL, NULL);
2044
2045                         PQclear(lo_res);
2046                 }
2047
2048                 destroyPQExpBuffer(loFrozenQry);
2049                 destroyPQExpBuffer(loOutQry);
2050         }
2051
2052         /* Dump DB comment if any */
2053         if (fout->remoteVersion >= 80200)
2054         {
2055                 /*
2056                  * 8.2 keeps comments on shared objects in a shared table, so we
2057                  * cannot use the dumpComment used for other database objects.
2058                  */
2059                 char       *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2060
2061                 if (comment && strlen(comment))
2062                 {
2063                         resetPQExpBuffer(dbQry);
2064
2065                         /*
2066                          * Generates warning when loaded into a differently-named
2067                          * database.
2068                          */
2069                         appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2070                         appendStringLiteralAH(dbQry, comment, fout);
2071                         appendPQExpBuffer(dbQry, ";\n");
2072
2073                         ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2074                                                  dba, false, "COMMENT", SECTION_NONE,
2075                                                  dbQry->data, "", NULL,
2076                                                  &dbDumpId, 1, NULL, NULL);
2077                 }
2078         }
2079         else
2080         {
2081                 resetPQExpBuffer(dbQry);
2082                 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2083                 dumpComment(fout, dbQry->data, NULL, "",
2084                                         dbCatId, 0, dbDumpId);
2085         }
2086
2087         PQclear(res);
2088
2089         /* Dump shared security label. */
2090         if (!no_security_labels && fout->remoteVersion >= 90200)
2091         {
2092                 PQExpBuffer seclabelQry = createPQExpBuffer();
2093
2094                 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2095                 res = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2096                 resetPQExpBuffer(seclabelQry);
2097                 emitShSecLabels(conn, res, seclabelQry, "DATABASE", datname);
2098                 if (strlen(seclabelQry->data))
2099                         ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2100                                                  dba, false, "SECURITY LABEL", SECTION_NONE,
2101                                                  seclabelQry->data, "", NULL,
2102                                                  &dbDumpId, 1, NULL, NULL);
2103                 destroyPQExpBuffer(seclabelQry);
2104         }
2105
2106         destroyPQExpBuffer(dbQry);
2107         destroyPQExpBuffer(delQry);
2108         destroyPQExpBuffer(creaQry);
2109 }
2110
2111
2112 /*
2113  * dumpEncoding: put the correct encoding into the archive
2114  */
2115 static void
2116 dumpEncoding(Archive *AH)
2117 {
2118         const char *encname = pg_encoding_to_char(AH->encoding);
2119         PQExpBuffer qry = createPQExpBuffer();
2120
2121         if (g_verbose)
2122                 write_msg(NULL, "saving encoding = %s\n", encname);
2123
2124         appendPQExpBuffer(qry, "SET client_encoding = ");
2125         appendStringLiteralAH(qry, encname, AH);
2126         appendPQExpBuffer(qry, ";\n");
2127
2128         ArchiveEntry(AH, nilCatalogId, createDumpId(),
2129                                  "ENCODING", NULL, NULL, "",
2130                                  false, "ENCODING", SECTION_PRE_DATA,
2131                                  qry->data, "", NULL,
2132                                  NULL, 0,
2133                                  NULL, NULL);
2134
2135         destroyPQExpBuffer(qry);
2136 }
2137
2138
2139 /*
2140  * dumpStdStrings: put the correct escape string behavior into the archive
2141  */
2142 static void
2143 dumpStdStrings(Archive *AH)
2144 {
2145         const char *stdstrings = AH->std_strings ? "on" : "off";
2146         PQExpBuffer qry = createPQExpBuffer();
2147
2148         if (g_verbose)
2149                 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2150                                   stdstrings);
2151
2152         appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2153                                           stdstrings);
2154
2155         ArchiveEntry(AH, nilCatalogId, createDumpId(),
2156                                  "STDSTRINGS", NULL, NULL, "",
2157                                  false, "STDSTRINGS", SECTION_PRE_DATA,
2158                                  qry->data, "", NULL,
2159                                  NULL, 0,
2160                                  NULL, NULL);
2161
2162         destroyPQExpBuffer(qry);
2163 }
2164
2165
2166 /*
2167  * getBlobs:
2168  *      Collect schema-level data about large objects
2169  */
2170 static void
2171 getBlobs(Archive *fout)
2172 {
2173         PQExpBuffer blobQry = createPQExpBuffer();
2174         BlobInfo   *binfo;
2175         DumpableObject *bdata;
2176         PGresult   *res;
2177         int                     ntups;
2178         int                     i;
2179
2180         /* Verbose message */
2181         if (g_verbose)
2182                 write_msg(NULL, "reading large objects\n");
2183
2184         /* Make sure we are in proper schema */
2185         selectSourceSchema(fout, "pg_catalog");
2186
2187         /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2188         if (fout->remoteVersion >= 90000)
2189                 appendPQExpBuffer(blobQry,
2190                                                   "SELECT oid, (%s lomowner) AS rolname, lomacl"
2191                                                   " FROM pg_largeobject_metadata",
2192                                                   username_subquery);
2193         else if (fout->remoteVersion >= 70100)
2194                 appendPQExpBuffer(blobQry,
2195                                                   "SELECT DISTINCT loid, NULL::oid, NULL::oid"
2196                                                   " FROM pg_largeobject");
2197         else
2198                 appendPQExpBuffer(blobQry,
2199                                                   "SELECT oid, NULL::oid, NULL::oid"
2200                                                   " FROM pg_class WHERE relkind = 'l'");
2201
2202         res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
2203
2204         ntups = PQntuples(res);
2205         if (ntups > 0)
2206         {
2207                 /*
2208                  * Each large object has its own BLOB archive entry.
2209                  */
2210                 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2211
2212                 for (i = 0; i < ntups; i++)
2213                 {
2214                         binfo[i].dobj.objType = DO_BLOB;
2215                         binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2216                         binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
2217                         AssignDumpId(&binfo[i].dobj);
2218
2219                         binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, 0));
2220                         if (!PQgetisnull(res, i, 1))
2221                                 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, 1));
2222                         else
2223                                 binfo[i].rolname = "";
2224                         if (!PQgetisnull(res, i, 2))
2225                                 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, 2));
2226                         else
2227                                 binfo[i].blobacl = NULL;
2228                 }
2229
2230                 /*
2231                  * If we have any large objects, a "BLOBS" archive entry is needed.
2232                  * This is just a placeholder for sorting; it carries no data now.
2233                  */
2234                 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2235                 bdata->objType = DO_BLOB_DATA;
2236                 bdata->catId = nilCatalogId;
2237                 AssignDumpId(bdata);
2238                 bdata->name = pg_strdup("BLOBS");
2239         }
2240
2241         PQclear(res);
2242         destroyPQExpBuffer(blobQry);
2243 }
2244
2245 /*
2246  * dumpBlob
2247  *
2248  * dump the definition (metadata) of the given large object
2249  */
2250 static void
2251 dumpBlob(Archive *fout, BlobInfo *binfo)
2252 {
2253         PQExpBuffer cquery = createPQExpBuffer();
2254         PQExpBuffer dquery = createPQExpBuffer();
2255
2256         appendPQExpBuffer(cquery,
2257                                           "SELECT pg_catalog.lo_create('%s');\n",
2258                                           binfo->dobj.name);
2259
2260         appendPQExpBuffer(dquery,
2261                                           "SELECT pg_catalog.lo_unlink('%s');\n",
2262                                           binfo->dobj.name);
2263
2264         ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
2265                                  binfo->dobj.name,
2266                                  NULL, NULL,
2267                                  binfo->rolname, false,
2268                                  "BLOB", SECTION_PRE_DATA,
2269                                  cquery->data, dquery->data, NULL,
2270                                  binfo->dobj.dependencies, binfo->dobj.nDeps,
2271                                  NULL, NULL);
2272
2273         /* set up tag for comment and/or ACL */
2274         resetPQExpBuffer(cquery);
2275         appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2276
2277         /* Dump comment if any */
2278         dumpComment(fout, cquery->data,
2279                                 NULL, binfo->rolname,
2280                                 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2281
2282         /* Dump security label if any */
2283         dumpSecLabel(fout, cquery->data,
2284                                  NULL, binfo->rolname,
2285                                  binfo->dobj.catId, 0, binfo->dobj.dumpId);
2286
2287         /* Dump ACL if any */
2288         if (binfo->blobacl)
2289                 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2290                                 binfo->dobj.name, NULL, cquery->data,
2291                                 NULL, binfo->rolname, binfo->blobacl);
2292
2293         destroyPQExpBuffer(cquery);
2294         destroyPQExpBuffer(dquery);
2295 }
2296
2297 /*
2298  * dumpBlobs:
2299  *      dump the data contents of all large objects
2300  */
2301 static int
2302 dumpBlobs(Archive *fout, void *arg)
2303 {
2304         const char *blobQry;
2305         const char *blobFetchQry;
2306         PGconn     *conn = GetConnection(fout);
2307         PGresult   *res;
2308         char            buf[LOBBUFSIZE];
2309         int                     ntups;
2310         int                     i;
2311         int                     cnt;
2312
2313         if (g_verbose)
2314                 write_msg(NULL, "saving large objects\n");
2315
2316         /* Make sure we are in proper schema */
2317         selectSourceSchema(fout, "pg_catalog");
2318
2319         /*
2320          * Currently, we re-fetch all BLOB OIDs using a cursor.  Consider scanning
2321          * the already-in-memory dumpable objects instead...
2322          */
2323         if (fout->remoteVersion >= 90000)
2324                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2325         else if (fout->remoteVersion >= 70100)
2326                 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2327         else
2328                 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2329
2330         ExecuteSqlStatement(fout, blobQry);
2331
2332         /* Command to fetch from cursor */
2333         blobFetchQry = "FETCH 1000 IN bloboid";
2334
2335         do
2336         {
2337                 /* Do a fetch */
2338                 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
2339
2340                 /* Process the tuples, if any */
2341                 ntups = PQntuples(res);
2342                 for (i = 0; i < ntups; i++)
2343                 {
2344                         Oid                     blobOid;
2345                         int                     loFd;
2346
2347                         blobOid = atooid(PQgetvalue(res, i, 0));
2348                         /* Open the BLOB */
2349                         loFd = lo_open(conn, blobOid, INV_READ);
2350                         if (loFd == -1)
2351                                 exit_horribly(NULL, "could not open large object %u: %s",
2352                                                           blobOid, PQerrorMessage(conn));
2353
2354                         StartBlob(fout, blobOid);
2355
2356                         /* Now read it in chunks, sending data to archive */
2357                         do
2358                         {
2359                                 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
2360                                 if (cnt < 0)
2361                                         exit_horribly(NULL, "error reading large object %u: %s",
2362                                                                   blobOid, PQerrorMessage(conn));
2363
2364                                 WriteData(fout, buf, cnt);
2365                         } while (cnt > 0);
2366
2367                         lo_close(conn, loFd);
2368
2369                         EndBlob(fout, blobOid);
2370                 }
2371
2372                 PQclear(res);
2373         } while (ntups > 0);
2374
2375         return 1;
2376 }
2377
2378 static void
2379 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
2380                                                                                  PQExpBuffer upgrade_buffer,
2381                                                                                  Oid pg_type_oid)
2382 {
2383         PQExpBuffer upgrade_query = createPQExpBuffer();
2384         PGresult   *upgrade_res;
2385         Oid                     pg_type_array_oid;
2386
2387         appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2388         appendPQExpBuffer(upgrade_buffer,
2389          "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2390                                           pg_type_oid);
2391
2392         /* we only support old >= 8.3 for binary upgrades */
2393         appendPQExpBuffer(upgrade_query,
2394                                           "SELECT typarray "
2395                                           "FROM pg_catalog.pg_type "
2396                                           "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2397                                           pg_type_oid);
2398
2399         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2400
2401         pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2402
2403         if (OidIsValid(pg_type_array_oid))
2404         {
2405                 appendPQExpBuffer(upgrade_buffer,
2406                            "\n-- For binary upgrade, must preserve pg_type array oid\n");
2407                 appendPQExpBuffer(upgrade_buffer,
2408                                                   "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2409                                                   pg_type_array_oid);
2410         }
2411
2412         PQclear(upgrade_res);
2413         destroyPQExpBuffer(upgrade_query);
2414 }
2415
2416 static bool
2417 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
2418                                                                                 PQExpBuffer upgrade_buffer,
2419                                                                                 Oid pg_rel_oid)
2420 {
2421         PQExpBuffer upgrade_query = createPQExpBuffer();
2422         PGresult   *upgrade_res;
2423         Oid                     pg_type_oid;
2424         bool            toast_set = false;
2425
2426         /* we only support old >= 8.3 for binary upgrades */
2427         appendPQExpBuffer(upgrade_query,
2428                                           "SELECT c.reltype AS crel, t.reltype AS trel "
2429                                           "FROM pg_catalog.pg_class c "
2430                                           "LEFT JOIN pg_catalog.pg_class t ON "
2431                                           "  (c.reltoastrelid = t.oid) "
2432                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
2433                                           pg_rel_oid);
2434
2435         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2436
2437         pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2438
2439         binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
2440                                                                                          pg_type_oid);
2441
2442         if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2443         {
2444                 /* Toast tables do not have pg_type array rows */
2445                 Oid                     pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2446                                                                                         PQfnumber(upgrade_res, "trel")));
2447
2448                 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2449                 appendPQExpBuffer(upgrade_buffer,
2450                                                   "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2451                                                   pg_type_toast_oid);
2452
2453                 toast_set = true;
2454         }
2455
2456         PQclear(upgrade_res);
2457         destroyPQExpBuffer(upgrade_query);
2458
2459         return toast_set;
2460 }
2461
2462 static void
2463 binary_upgrade_set_pg_class_oids(Archive *fout,
2464                                                                  PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2465                                                                  bool is_index)
2466 {
2467         PQExpBuffer upgrade_query = createPQExpBuffer();
2468         PGresult   *upgrade_res;
2469         Oid                     pg_class_reltoastrelid;
2470         Oid                     pg_class_reltoastidxid;
2471
2472         appendPQExpBuffer(upgrade_query,
2473                                           "SELECT c.reltoastrelid, t.reltoastidxid "
2474                                           "FROM pg_catalog.pg_class c LEFT JOIN "
2475                                           "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2476                                           "WHERE c.oid = '%u'::pg_catalog.oid;",
2477                                           pg_class_oid);
2478
2479         upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2480
2481         pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2482         pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2483
2484         appendPQExpBuffer(upgrade_buffer,
2485                                    "\n-- For binary upgrade, must preserve pg_class oids\n");
2486
2487         if (!is_index)
2488         {
2489                 appendPQExpBuffer(upgrade_buffer,
2490                                                   "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2491                                                   pg_class_oid);
2492                 /* only tables have toast tables, not indexes */
2493                 if (OidIsValid(pg_class_reltoastrelid))
2494                 {
2495                         /*
2496                          * One complexity is that the table definition might not require
2497                          * the creation of a TOAST table, and the TOAST table might have
2498                          * been created long after table creation, when the table was
2499                          * loaded with wide data.  By setting the TOAST oid we force
2500                          * creation of the TOAST heap and TOAST index by the backend so we
2501                          * can cleanly copy the files during binary upgrade.
2502                          */
2503
2504                         appendPQExpBuffer(upgrade_buffer,
2505                                                           "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2506                                                           pg_class_reltoastrelid);
2507
2508                         /* every toast table has an index */
2509                         appendPQExpBuffer(upgrade_buffer,
2510                                                           "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2511                                                           pg_class_reltoastidxid);
2512                 }
2513         }
2514         else
2515                 appendPQExpBuffer(upgrade_buffer,
2516                                                   "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2517                                                   pg_class_oid);
2518
2519         appendPQExpBuffer(upgrade_buffer, "\n");
2520
2521         PQclear(upgrade_res);
2522         destroyPQExpBuffer(upgrade_query);
2523 }
2524
2525 /*
2526  * If the DumpableObject is a member of an extension, add a suitable
2527  * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2528  */
2529 static void
2530 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2531                                                                 DumpableObject *dobj,
2532                                                                 const char *objlabel)
2533 {
2534         DumpableObject *extobj = NULL;
2535         int                     i;
2536
2537         if (!dobj->ext_member)
2538                 return;
2539
2540         /*
2541          * Find the parent extension.  We could avoid this search if we wanted to
2542          * add a link field to DumpableObject, but the space costs of that would
2543          * be considerable.  We assume that member objects could only have a
2544          * direct dependency on their own extension, not any others.
2545          */
2546         for (i = 0; i < dobj->nDeps; i++)
2547         {
2548                 extobj = findObjectByDumpId(dobj->dependencies[i]);
2549                 if (extobj && extobj->objType == DO_EXTENSION)
2550                         break;
2551                 extobj = NULL;
2552         }
2553         if (extobj == NULL)
2554                 exit_horribly(NULL, "could not find parent extension for %s", objlabel);
2555
2556         appendPQExpBuffer(upgrade_buffer,
2557           "\n-- For binary upgrade, handle extension membership the hard way\n");
2558         appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2559                                           fmtId(extobj->name),
2560                                           objlabel);
2561 }
2562
2563 /*
2564  * getNamespaces:
2565  *        read all namespaces in the system catalogs and return them in the
2566  * NamespaceInfo* structure
2567  *
2568  *      numNamespaces is set to the number of namespaces read in
2569  */
2570 NamespaceInfo *
2571 getNamespaces(Archive *fout, int *numNamespaces)
2572 {
2573         PGresult   *res;
2574         int                     ntups;
2575         int                     i;
2576         PQExpBuffer query;
2577         NamespaceInfo *nsinfo;
2578         int                     i_tableoid;
2579         int                     i_oid;
2580         int                     i_nspname;
2581         int                     i_rolname;
2582         int                     i_nspacl;
2583
2584         /*
2585          * Before 7.3, there are no real namespaces; create two dummy entries, one
2586          * for user stuff and one for system stuff.
2587          */
2588         if (fout->remoteVersion < 70300)
2589         {
2590                 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2591
2592                 nsinfo[0].dobj.objType = DO_NAMESPACE;
2593                 nsinfo[0].dobj.catId.tableoid = 0;
2594                 nsinfo[0].dobj.catId.oid = 0;
2595                 AssignDumpId(&nsinfo[0].dobj);
2596                 nsinfo[0].dobj.name = pg_strdup("public");
2597                 nsinfo[0].rolname = pg_strdup("");
2598                 nsinfo[0].nspacl = pg_strdup("");
2599
2600                 selectDumpableNamespace(&nsinfo[0]);
2601
2602                 nsinfo[1].dobj.objType = DO_NAMESPACE;
2603                 nsinfo[1].dobj.catId.tableoid = 0;
2604                 nsinfo[1].dobj.catId.oid = 1;
2605                 AssignDumpId(&nsinfo[1].dobj);
2606                 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2607                 nsinfo[1].rolname = pg_strdup("");
2608                 nsinfo[1].nspacl = pg_strdup("");
2609
2610                 selectDumpableNamespace(&nsinfo[1]);
2611
2612                 g_namespaces = nsinfo;
2613                 g_numNamespaces = *numNamespaces = 2;
2614
2615                 return nsinfo;
2616         }
2617
2618         query = createPQExpBuffer();
2619
2620         /* Make sure we are in proper schema */
2621         selectSourceSchema(fout, "pg_catalog");
2622
2623         /*
2624          * we fetch all namespaces including system ones, so that every object we
2625          * read in can be linked to a containing namespace.
2626          */
2627         appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2628                                           "(%s nspowner) AS rolname, "
2629                                           "nspacl FROM pg_namespace",
2630                                           username_subquery);
2631
2632         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2633
2634         ntups = PQntuples(res);
2635
2636         nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2637
2638         i_tableoid = PQfnumber(res, "tableoid");
2639         i_oid = PQfnumber(res, "oid");
2640         i_nspname = PQfnumber(res, "nspname");
2641         i_rolname = PQfnumber(res, "rolname");
2642         i_nspacl = PQfnumber(res, "nspacl");
2643
2644         for (i = 0; i < ntups; i++)
2645         {
2646                 nsinfo[i].dobj.objType = DO_NAMESPACE;
2647                 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2648                 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2649                 AssignDumpId(&nsinfo[i].dobj);
2650                 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2651                 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2652                 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2653
2654                 /* Decide whether to dump this namespace */
2655                 selectDumpableNamespace(&nsinfo[i]);
2656
2657                 if (strlen(nsinfo[i].rolname) == 0)
2658                         write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2659                                           nsinfo[i].dobj.name);
2660         }
2661
2662         PQclear(res);
2663         destroyPQExpBuffer(query);
2664
2665         g_namespaces = nsinfo;
2666         g_numNamespaces = *numNamespaces = ntups;
2667
2668         return nsinfo;
2669 }
2670
2671 /*
2672  * findNamespace:
2673  *              given a namespace OID and an object OID, look up the info read by
2674  *              getNamespaces
2675  *
2676  * NB: for pre-7.3 source database, we use object OID to guess whether it's
2677  * a system object or not.      In 7.3 and later there is no guessing.
2678  */
2679 static NamespaceInfo *
2680 findNamespace(Archive *fout, Oid nsoid, Oid objoid)
2681 {
2682         int                     i;
2683
2684         if (fout->remoteVersion >= 70300)
2685         {
2686                 for (i = 0; i < g_numNamespaces; i++)
2687                 {
2688                         NamespaceInfo *nsinfo = &g_namespaces[i];
2689
2690                         if (nsoid == nsinfo->dobj.catId.oid)
2691                                 return nsinfo;
2692                 }
2693                 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
2694         }
2695         else
2696         {
2697                 /* This code depends on the layout set up by getNamespaces. */
2698                 if (objoid > g_last_builtin_oid)
2699                         i = 0;                          /* user object */
2700                 else
2701                         i = 1;                          /* system object */
2702                 return &g_namespaces[i];
2703         }
2704
2705         return NULL;                            /* keep compiler quiet */
2706 }
2707
2708 /*
2709  * getExtensions:
2710  *        read all extensions in the system catalogs and return them in the
2711  * ExtensionInfo* structure
2712  *
2713  *      numExtensions is set to the number of extensions read in
2714  */
2715 ExtensionInfo *
2716 getExtensions(Archive *fout, int *numExtensions)
2717 {
2718         PGresult   *res;
2719         int                     ntups;
2720         int                     i;
2721         PQExpBuffer query;
2722         ExtensionInfo *extinfo;
2723         int                     i_tableoid;
2724         int                     i_oid;
2725         int                     i_extname;
2726         int                     i_nspname;
2727         int                     i_extrelocatable;
2728         int                     i_extversion;
2729         int                     i_extconfig;
2730         int                     i_extcondition;
2731
2732         /*
2733          * Before 9.1, there are no extensions.
2734          */
2735         if (fout->remoteVersion < 90100)
2736         {
2737                 *numExtensions = 0;
2738                 return NULL;
2739         }
2740
2741         query = createPQExpBuffer();
2742
2743         /* Make sure we are in proper schema */
2744         selectSourceSchema(fout, "pg_catalog");
2745
2746         appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
2747                                           "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
2748                                           "FROM pg_extension x "
2749                                           "JOIN pg_namespace n ON n.oid = x.extnamespace");
2750
2751         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2752
2753         ntups = PQntuples(res);
2754
2755         extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
2756
2757         i_tableoid = PQfnumber(res, "tableoid");
2758         i_oid = PQfnumber(res, "oid");
2759         i_extname = PQfnumber(res, "extname");
2760         i_nspname = PQfnumber(res, "nspname");
2761         i_extrelocatable = PQfnumber(res, "extrelocatable");
2762         i_extversion = PQfnumber(res, "extversion");
2763         i_extconfig = PQfnumber(res, "extconfig");
2764         i_extcondition = PQfnumber(res, "extcondition");
2765
2766         for (i = 0; i < ntups; i++)
2767         {
2768                 extinfo[i].dobj.objType = DO_EXTENSION;
2769                 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2770                 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2771                 AssignDumpId(&extinfo[i].dobj);
2772                 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
2773                 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
2774                 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
2775                 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
2776                 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
2777                 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
2778
2779                 /* Decide whether we want to dump it */
2780                 selectDumpableExtension(&(extinfo[i]));
2781         }
2782
2783         PQclear(res);
2784         destroyPQExpBuffer(query);
2785
2786         *numExtensions = ntups;
2787
2788         return extinfo;
2789 }
2790
2791 /*
2792  * getTypes:
2793  *        read all types in the system catalogs and return them in the
2794  * TypeInfo* structure
2795  *
2796  *      numTypes is set to the number of types read in
2797  *
2798  * NB: this must run after getFuncs() because we assume we can do
2799  * findFuncByOid().
2800  */
2801 TypeInfo *
2802 getTypes(Archive *fout, int *numTypes)
2803 {
2804         PGresult   *res;
2805         int                     ntups;
2806         int                     i;
2807         PQExpBuffer query = createPQExpBuffer();
2808         TypeInfo   *tyinfo;
2809         ShellTypeInfo *stinfo;
2810         int                     i_tableoid;
2811         int                     i_oid;
2812         int                     i_typname;
2813         int                     i_typnamespace;
2814         int                     i_rolname;
2815         int                     i_typinput;
2816         int                     i_typoutput;
2817         int                     i_typelem;
2818         int                     i_typrelid;
2819         int                     i_typrelkind;
2820         int                     i_typtype;
2821         int                     i_typisdefined;
2822         int                     i_isarray;
2823
2824         /*
2825          * we include even the built-in types because those may be used as array
2826          * elements by user-defined types
2827          *
2828          * we filter out the built-in types when we dump out the types
2829          *
2830          * same approach for undefined (shell) types and array types
2831          *
2832          * Note: as of 8.3 we can reliably detect whether a type is an
2833          * auto-generated array type by checking the element type's typarray.
2834          * (Before that the test is capable of generating false positives.) We
2835          * still check for name beginning with '_', though, so as to avoid the
2836          * cost of the subselect probe for all standard types.  This would have to
2837          * be revisited if the backend ever allows renaming of array types.
2838          */
2839
2840         /* Make sure we are in proper schema */
2841         selectSourceSchema(fout, "pg_catalog");
2842
2843         if (fout->remoteVersion >= 80300)
2844         {
2845                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2846                                                   "typnamespace, "
2847                                                   "(%s typowner) AS rolname, "
2848                                                   "typinput::oid AS typinput, "
2849                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2850                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2851                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2852                                                   "typtype, typisdefined, "
2853                                                   "typname[0] = '_' AND typelem != 0 AND "
2854                                                   "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2855                                                   "FROM pg_type",
2856                                                   username_subquery);
2857         }
2858         else if (fout->remoteVersion >= 70300)
2859         {
2860                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2861                                                   "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 if (fout->remoteVersion >= 70100)
2873         {
2874                 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2875                                                   "0::oid AS typnamespace, "
2876                                                   "(%s typowner) AS rolname, "
2877                                                   "typinput::oid AS typinput, "
2878                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2879                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2880                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2881                                                   "typtype, typisdefined, "
2882                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2883                                                   "FROM pg_type",
2884                                                   username_subquery);
2885         }
2886         else
2887         {
2888                 appendPQExpBuffer(query, "SELECT "
2889                  "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
2890                                                   "oid, typname, "
2891                                                   "0::oid AS typnamespace, "
2892                                                   "(%s typowner) AS rolname, "
2893                                                   "typinput::oid AS typinput, "
2894                                                   "typoutput::oid AS typoutput, typelem, typrelid, "
2895                                                   "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2896                                                   "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2897                                                   "typtype, typisdefined, "
2898                                                   "typname[0] = '_' AND typelem != 0 AS isarray "
2899                                                   "FROM pg_type",
2900                                                   username_subquery);
2901         }
2902
2903         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2904
2905         ntups = PQntuples(res);
2906
2907         tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
2908
2909         i_tableoid = PQfnumber(res, "tableoid");
2910         i_oid = PQfnumber(res, "oid");
2911         i_typname = PQfnumber(res, "typname");
2912         i_typnamespace = PQfnumber(res, "typnamespace");
2913         i_rolname = PQfnumber(res, "rolname");
2914         i_typinput = PQfnumber(res, "typinput");
2915         i_typoutput = PQfnumber(res, "typoutput");
2916         i_typelem = PQfnumber(res, "typelem");
2917         i_typrelid = PQfnumber(res, "typrelid");
2918         i_typrelkind = PQfnumber(res, "typrelkind");
2919         i_typtype = PQfnumber(res, "typtype");
2920         i_typisdefined = PQfnumber(res, "typisdefined");
2921         i_isarray = PQfnumber(res, "isarray");
2922
2923         for (i = 0; i < ntups; i++)
2924         {
2925                 tyinfo[i].dobj.objType = DO_TYPE;
2926                 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2927                 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2928                 AssignDumpId(&tyinfo[i].dobj);
2929                 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
2930                 tyinfo[i].dobj.namespace =
2931                         findNamespace(fout,
2932                                                   atooid(PQgetvalue(res, i, i_typnamespace)),
2933                                                   tyinfo[i].dobj.catId.oid);
2934                 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2935                 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
2936                 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
2937                 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
2938                 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
2939                 tyinfo[i].shellType = NULL;
2940
2941                 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
2942                         tyinfo[i].isDefined = true;
2943                 else
2944                         tyinfo[i].isDefined = false;
2945
2946                 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
2947                         tyinfo[i].isArray = true;
2948                 else
2949                         tyinfo[i].isArray = false;
2950
2951                 /* Decide whether we want to dump it */
2952                 selectDumpableType(&tyinfo[i]);
2953
2954                 /*
2955                  * If it's a domain, fetch info about its constraints, if any
2956                  */
2957                 tyinfo[i].nDomChecks = 0;
2958                 tyinfo[i].domChecks = NULL;
2959                 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
2960                         getDomainConstraints(fout, &(tyinfo[i]));
2961
2962                 /*
2963                  * If it's a base type, make a DumpableObject representing a shell
2964                  * definition of the type.      We will need to dump that ahead of the I/O
2965                  * functions for the type.  Similarly, range types need a shell
2966                  * definition in case they have a canonicalize function.
2967                  *
2968                  * Note: the shell type doesn't have a catId.  You might think it
2969                  * should copy the base type's catId, but then it might capture the
2970                  * pg_depend entries for the type, which we don't want.
2971                  */
2972                 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
2973                                                                         tyinfo[i].typtype == TYPTYPE_RANGE))
2974                 {
2975                         stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
2976                         stinfo->dobj.objType = DO_SHELL_TYPE;
2977                         stinfo->dobj.catId = nilCatalogId;
2978                         AssignDumpId(&stinfo->dobj);
2979                         stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
2980                         stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
2981                         stinfo->baseType = &(tyinfo[i]);
2982                         tyinfo[i].shellType = stinfo;
2983
2984                         /*
2985                          * Initially mark the shell type as not to be dumped.  We'll only
2986                          * dump it if the I/O or canonicalize functions need to be dumped;
2987                          * this is taken care of while sorting dependencies.
2988                          */
2989                         stinfo->dobj.dump = false;
2990
2991                         /*
2992                          * However, if dumping from pre-7.3, there will be no dependency
2993                          * info so we have to fake it here.  We only need to worry about
2994                          * typinput and typoutput since the other functions only exist
2995                          * post-7.3.
2996                          */
2997                         if (fout->remoteVersion < 70300)
2998                         {
2999                                 Oid                     typinput;
3000                                 Oid                     typoutput;
3001                                 FuncInfo   *funcInfo;
3002
3003                                 typinput = atooid(PQgetvalue(res, i, i_typinput));
3004                                 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
3005
3006                                 funcInfo = findFuncByOid(typinput);
3007                                 if (funcInfo && funcInfo->dobj.dump)
3008                                 {
3009                                         /* base type depends on function */
3010                                         addObjectDependency(&tyinfo[i].dobj,
3011                                                                                 funcInfo->dobj.dumpId);
3012                                         /* function depends on shell type */
3013                                         addObjectDependency(&funcInfo->dobj,
3014                                                                                 stinfo->dobj.dumpId);
3015                                         /* mark shell type as to be dumped */
3016                                         stinfo->dobj.dump = true;
3017                                 }
3018
3019                                 funcInfo = findFuncByOid(typoutput);
3020                                 if (funcInfo && funcInfo->dobj.dump)
3021                                 {
3022                                         /* base type depends on function */
3023                                         addObjectDependency(&tyinfo[i].dobj,
3024                                                                                 funcInfo->dobj.dumpId);
3025                                         /* function depends on shell type */
3026                                         addObjectDependency(&funcInfo->dobj,
3027                                                                                 stinfo->dobj.dumpId);
3028                                         /* mark shell type as to be dumped */
3029                                         stinfo->dobj.dump = true;
3030                                 }
3031                         }
3032                 }
3033
3034                 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3035                         write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3036                                           tyinfo[i].dobj.name);
3037         }
3038
3039         *numTypes = ntups;
3040
3041         PQclear(res);
3042
3043         destroyPQExpBuffer(query);
3044
3045         return tyinfo;
3046 }
3047
3048 /*
3049  * getOperators:
3050  *        read all operators in the system catalogs and return them in the
3051  * OprInfo* structure
3052  *
3053  *      numOprs is set to the number of operators read in
3054  */
3055 OprInfo *
3056 getOperators(Archive *fout, int *numOprs)
3057 {
3058         PGresult   *res;
3059         int                     ntups;
3060         int                     i;
3061         PQExpBuffer query = createPQExpBuffer();
3062         OprInfo    *oprinfo;
3063         int                     i_tableoid;
3064         int                     i_oid;
3065         int                     i_oprname;
3066         int                     i_oprnamespace;
3067         int                     i_rolname;
3068         int                     i_oprkind;
3069         int                     i_oprcode;
3070
3071         /*
3072          * find all operators, including builtin operators; we filter out
3073          * system-defined operators at dump-out time.
3074          */
3075
3076         /* Make sure we are in proper schema */
3077         selectSourceSchema(fout, "pg_catalog");
3078
3079         if (fout->remoteVersion >= 70300)
3080         {
3081                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3082                                                   "oprnamespace, "
3083                                                   "(%s oprowner) AS rolname, "
3084                                                   "oprkind, "
3085                                                   "oprcode::oid AS oprcode "
3086                                                   "FROM pg_operator",
3087                                                   username_subquery);
3088         }
3089         else if (fout->remoteVersion >= 70100)
3090         {
3091                 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3092                                                   "0::oid AS oprnamespace, "
3093                                                   "(%s oprowner) AS rolname, "
3094                                                   "oprkind, "
3095                                                   "oprcode::oid AS oprcode "
3096                                                   "FROM pg_operator",
3097                                                   username_subquery);
3098         }
3099         else
3100         {
3101                 appendPQExpBuffer(query, "SELECT "
3102                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3103                                                   "oid, oprname, "
3104                                                   "0::oid AS oprnamespace, "
3105                                                   "(%s oprowner) AS rolname, "
3106                                                   "oprkind, "
3107                                                   "oprcode::oid AS oprcode "
3108                                                   "FROM pg_operator",
3109                                                   username_subquery);
3110         }
3111
3112         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3113
3114         ntups = PQntuples(res);
3115         *numOprs = ntups;
3116
3117         oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3118
3119         i_tableoid = PQfnumber(res, "tableoid");
3120         i_oid = PQfnumber(res, "oid");
3121         i_oprname = PQfnumber(res, "oprname");
3122         i_oprnamespace = PQfnumber(res, "oprnamespace");
3123         i_rolname = PQfnumber(res, "rolname");
3124         i_oprkind = PQfnumber(res, "oprkind");
3125         i_oprcode = PQfnumber(res, "oprcode");
3126
3127         for (i = 0; i < ntups; i++)
3128         {
3129                 oprinfo[i].dobj.objType = DO_OPERATOR;
3130                 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3131                 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3132                 AssignDumpId(&oprinfo[i].dobj);
3133                 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3134                 oprinfo[i].dobj.namespace =
3135                         findNamespace(fout,
3136                                                   atooid(PQgetvalue(res, i, i_oprnamespace)),
3137                                                   oprinfo[i].dobj.catId.oid);
3138                 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3139                 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3140                 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3141
3142                 /* Decide whether we want to dump it */
3143                 selectDumpableObject(&(oprinfo[i].dobj));
3144
3145                 if (strlen(oprinfo[i].rolname) == 0)
3146                         write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3147                                           oprinfo[i].dobj.name);
3148         }
3149
3150         PQclear(res);
3151
3152         destroyPQExpBuffer(query);
3153
3154         return oprinfo;
3155 }
3156
3157 /*
3158  * getCollations:
3159  *        read all collations in the system catalogs and return them in the
3160  * CollInfo* structure
3161  *
3162  *      numCollations is set to the number of collations read in
3163  */
3164 CollInfo *
3165 getCollations(Archive *fout, int *numCollations)
3166 {
3167         PGresult   *res;
3168         int                     ntups;
3169         int                     i;
3170         PQExpBuffer query;
3171         CollInfo   *collinfo;
3172         int                     i_tableoid;
3173         int                     i_oid;
3174         int                     i_collname;
3175         int                     i_collnamespace;
3176         int                     i_rolname;
3177
3178         /* Collations didn't exist pre-9.1 */
3179         if (fout->remoteVersion < 90100)
3180         {
3181                 *numCollations = 0;
3182                 return NULL;
3183         }
3184
3185         query = createPQExpBuffer();
3186
3187         /*
3188          * find all collations, including builtin collations; we filter out
3189          * system-defined collations at dump-out time.
3190          */
3191
3192         /* Make sure we are in proper schema */
3193         selectSourceSchema(fout, "pg_catalog");
3194
3195         appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3196                                           "collnamespace, "
3197                                           "(%s collowner) AS rolname "
3198                                           "FROM pg_collation",
3199                                           username_subquery);
3200
3201         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3202
3203         ntups = PQntuples(res);
3204         *numCollations = ntups;
3205
3206         collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3207
3208         i_tableoid = PQfnumber(res, "tableoid");
3209         i_oid = PQfnumber(res, "oid");
3210         i_collname = PQfnumber(res, "collname");
3211         i_collnamespace = PQfnumber(res, "collnamespace");
3212         i_rolname = PQfnumber(res, "rolname");
3213
3214         for (i = 0; i < ntups; i++)
3215         {
3216                 collinfo[i].dobj.objType = DO_COLLATION;
3217                 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3218                 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3219                 AssignDumpId(&collinfo[i].dobj);
3220                 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3221                 collinfo[i].dobj.namespace =
3222                         findNamespace(fout,
3223                                                   atooid(PQgetvalue(res, i, i_collnamespace)),
3224                                                   collinfo[i].dobj.catId.oid);
3225                 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3226
3227                 /* Decide whether we want to dump it */
3228                 selectDumpableObject(&(collinfo[i].dobj));
3229         }
3230
3231         PQclear(res);
3232
3233         destroyPQExpBuffer(query);
3234
3235         return collinfo;
3236 }
3237
3238 /*
3239  * getConversions:
3240  *        read all conversions in the system catalogs and return them in the
3241  * ConvInfo* structure
3242  *
3243  *      numConversions is set to the number of conversions read in
3244  */
3245 ConvInfo *
3246 getConversions(Archive *fout, int *numConversions)
3247 {
3248         PGresult   *res;
3249         int                     ntups;
3250         int                     i;
3251         PQExpBuffer query = createPQExpBuffer();
3252         ConvInfo   *convinfo;
3253         int                     i_tableoid;
3254         int                     i_oid;
3255         int                     i_conname;
3256         int                     i_connamespace;
3257         int                     i_rolname;
3258
3259         /* Conversions didn't exist pre-7.3 */
3260         if (fout->remoteVersion < 70300)
3261         {
3262                 *numConversions = 0;
3263                 return NULL;
3264         }
3265
3266         /*
3267          * find all conversions, including builtin conversions; we filter out
3268          * system-defined conversions at dump-out time.
3269          */
3270
3271         /* Make sure we are in proper schema */
3272         selectSourceSchema(fout, "pg_catalog");
3273
3274         appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3275                                           "connamespace, "
3276                                           "(%s conowner) AS rolname "
3277                                           "FROM pg_conversion",
3278                                           username_subquery);
3279
3280         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3281
3282         ntups = PQntuples(res);
3283         *numConversions = ntups;
3284
3285         convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3286
3287         i_tableoid = PQfnumber(res, "tableoid");
3288         i_oid = PQfnumber(res, "oid");
3289         i_conname = PQfnumber(res, "conname");
3290         i_connamespace = PQfnumber(res, "connamespace");
3291         i_rolname = PQfnumber(res, "rolname");
3292
3293         for (i = 0; i < ntups; i++)
3294         {
3295                 convinfo[i].dobj.objType = DO_CONVERSION;
3296                 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3297                 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3298                 AssignDumpId(&convinfo[i].dobj);
3299                 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3300                 convinfo[i].dobj.namespace =
3301                         findNamespace(fout,
3302                                                   atooid(PQgetvalue(res, i, i_connamespace)),
3303                                                   convinfo[i].dobj.catId.oid);
3304                 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3305
3306                 /* Decide whether we want to dump it */
3307                 selectDumpableObject(&(convinfo[i].dobj));
3308         }
3309
3310         PQclear(res);
3311
3312         destroyPQExpBuffer(query);
3313
3314         return convinfo;
3315 }
3316
3317 /*
3318  * getOpclasses:
3319  *        read all opclasses in the system catalogs and return them in the
3320  * OpclassInfo* structure
3321  *
3322  *      numOpclasses is set to the number of opclasses read in
3323  */
3324 OpclassInfo *
3325 getOpclasses(Archive *fout, int *numOpclasses)
3326 {
3327         PGresult   *res;
3328         int                     ntups;
3329         int                     i;
3330         PQExpBuffer query = createPQExpBuffer();
3331         OpclassInfo *opcinfo;
3332         int                     i_tableoid;
3333         int                     i_oid;
3334         int                     i_opcname;
3335         int                     i_opcnamespace;
3336         int                     i_rolname;
3337
3338         /*
3339          * find all opclasses, including builtin opclasses; we filter out
3340          * system-defined opclasses at dump-out time.
3341          */
3342
3343         /* Make sure we are in proper schema */
3344         selectSourceSchema(fout, "pg_catalog");
3345
3346         if (fout->remoteVersion >= 70300)
3347         {
3348                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3349                                                   "opcnamespace, "
3350                                                   "(%s opcowner) AS rolname "
3351                                                   "FROM pg_opclass",
3352                                                   username_subquery);
3353         }
3354         else if (fout->remoteVersion >= 70100)
3355         {
3356                 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3357                                                   "0::oid AS opcnamespace, "
3358                                                   "''::name AS rolname "
3359                                                   "FROM pg_opclass");
3360         }
3361         else
3362         {
3363                 appendPQExpBuffer(query, "SELECT "
3364                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3365                                                   "oid, opcname, "
3366                                                   "0::oid AS opcnamespace, "
3367                                                   "''::name AS rolname "
3368                                                   "FROM pg_opclass");
3369         }
3370
3371         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3372
3373         ntups = PQntuples(res);
3374         *numOpclasses = ntups;
3375
3376         opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3377
3378         i_tableoid = PQfnumber(res, "tableoid");
3379         i_oid = PQfnumber(res, "oid");
3380         i_opcname = PQfnumber(res, "opcname");
3381         i_opcnamespace = PQfnumber(res, "opcnamespace");
3382         i_rolname = PQfnumber(res, "rolname");
3383
3384         for (i = 0; i < ntups; i++)
3385         {
3386                 opcinfo[i].dobj.objType = DO_OPCLASS;
3387                 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3388                 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3389                 AssignDumpId(&opcinfo[i].dobj);
3390                 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3391                 opcinfo[i].dobj.namespace =
3392                         findNamespace(fout,
3393                                                   atooid(PQgetvalue(res, i, i_opcnamespace)),
3394                                                   opcinfo[i].dobj.catId.oid);
3395                 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3396
3397                 /* Decide whether we want to dump it */
3398                 selectDumpableObject(&(opcinfo[i].dobj));
3399
3400                 if (fout->remoteVersion >= 70300)
3401                 {
3402                         if (strlen(opcinfo[i].rolname) == 0)
3403                                 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3404                                                   opcinfo[i].dobj.name);
3405                 }
3406         }
3407
3408         PQclear(res);
3409
3410         destroyPQExpBuffer(query);
3411
3412         return opcinfo;
3413 }
3414
3415 /*
3416  * getOpfamilies:
3417  *        read all opfamilies in the system catalogs and return them in the
3418  * OpfamilyInfo* structure
3419  *
3420  *      numOpfamilies is set to the number of opfamilies read in
3421  */
3422 OpfamilyInfo *
3423 getOpfamilies(Archive *fout, int *numOpfamilies)
3424 {
3425         PGresult   *res;
3426         int                     ntups;
3427         int                     i;
3428         PQExpBuffer query;
3429         OpfamilyInfo *opfinfo;
3430         int                     i_tableoid;
3431         int                     i_oid;
3432         int                     i_opfname;
3433         int                     i_opfnamespace;
3434         int                     i_rolname;
3435
3436         /* Before 8.3, there is no separate concept of opfamilies */
3437         if (fout->remoteVersion < 80300)
3438         {
3439                 *numOpfamilies = 0;
3440                 return NULL;
3441         }
3442
3443         query = createPQExpBuffer();
3444
3445         /*
3446          * find all opfamilies, including builtin opfamilies; we filter out
3447          * system-defined opfamilies at dump-out time.
3448          */
3449
3450         /* Make sure we are in proper schema */
3451         selectSourceSchema(fout, "pg_catalog");
3452
3453         appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3454                                           "opfnamespace, "
3455                                           "(%s opfowner) AS rolname "
3456                                           "FROM pg_opfamily",
3457                                           username_subquery);
3458
3459         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3460
3461         ntups = PQntuples(res);
3462         *numOpfamilies = ntups;
3463
3464         opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3465
3466         i_tableoid = PQfnumber(res, "tableoid");
3467         i_oid = PQfnumber(res, "oid");
3468         i_opfname = PQfnumber(res, "opfname");
3469         i_opfnamespace = PQfnumber(res, "opfnamespace");
3470         i_rolname = PQfnumber(res, "rolname");
3471
3472         for (i = 0; i < ntups; i++)
3473         {
3474                 opfinfo[i].dobj.objType = DO_OPFAMILY;
3475                 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3476                 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3477                 AssignDumpId(&opfinfo[i].dobj);
3478                 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3479                 opfinfo[i].dobj.namespace =
3480                         findNamespace(fout,
3481                                                   atooid(PQgetvalue(res, i, i_opfnamespace)),
3482                                                   opfinfo[i].dobj.catId.oid);
3483                 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3484
3485                 /* Decide whether we want to dump it */
3486                 selectDumpableObject(&(opfinfo[i].dobj));
3487
3488                 if (fout->remoteVersion >= 70300)
3489                 {
3490                         if (strlen(opfinfo[i].rolname) == 0)
3491                                 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3492                                                   opfinfo[i].dobj.name);
3493                 }
3494         }
3495
3496         PQclear(res);
3497
3498         destroyPQExpBuffer(query);
3499
3500         return opfinfo;
3501 }
3502
3503 /*
3504  * getAggregates:
3505  *        read all the user-defined aggregates in the system catalogs and
3506  * return them in the AggInfo* structure
3507  *
3508  * numAggs is set to the number of aggregates read in
3509  */
3510 AggInfo *
3511 getAggregates(Archive *fout, int *numAggs)
3512 {
3513         PGresult   *res;
3514         int                     ntups;
3515         int                     i;
3516         PQExpBuffer query = createPQExpBuffer();
3517         AggInfo    *agginfo;
3518         int                     i_tableoid;
3519         int                     i_oid;
3520         int                     i_aggname;
3521         int                     i_aggnamespace;
3522         int                     i_pronargs;
3523         int                     i_proargtypes;
3524         int                     i_rolname;
3525         int                     i_aggacl;
3526
3527         /* Make sure we are in proper schema */
3528         selectSourceSchema(fout, "pg_catalog");
3529
3530         /*
3531          * Find all user-defined aggregates.  See comment in getFuncs() for the
3532          * rationale behind the filtering logic.
3533          */
3534
3535         if (fout->remoteVersion >= 80200)
3536         {
3537                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3538                                                   "pronamespace AS aggnamespace, "
3539                                                   "pronargs, proargtypes, "
3540                                                   "(%s proowner) AS rolname, "
3541                                                   "proacl AS aggacl "
3542                                                   "FROM pg_proc p "
3543                                                   "WHERE proisagg AND ("
3544                                                   "pronamespace != "
3545                                                   "(SELECT oid FROM pg_namespace "
3546                                                   "WHERE nspname = 'pg_catalog')",
3547                                                   username_subquery);
3548                 if (binary_upgrade && fout->remoteVersion >= 90100)
3549                         appendPQExpBuffer(query,
3550                                                           " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3551                                                           "classid = 'pg_proc'::regclass AND "
3552                                                           "objid = p.oid AND "
3553                                                           "refclassid = 'pg_extension'::regclass AND "
3554                                                           "deptype = 'e')");
3555                 appendPQExpBuffer(query, ")");
3556         }
3557         else if (fout->remoteVersion >= 70300)
3558         {
3559                 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3560                                                   "pronamespace AS aggnamespace, "
3561                                                   "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3562                                                   "proargtypes, "
3563                                                   "(%s proowner) AS rolname, "
3564                                                   "proacl AS aggacl "
3565                                                   "FROM pg_proc "
3566                                                   "WHERE proisagg "
3567                                                   "AND pronamespace != "
3568                            "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3569                                                   username_subquery);
3570         }
3571         else if (fout->remoteVersion >= 70100)
3572         {
3573                 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3574                                                   "0::oid AS aggnamespace, "
3575                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3576                                                   "aggbasetype AS proargtypes, "
3577                                                   "(%s aggowner) AS rolname, "
3578                                                   "'{=X}' AS aggacl "
3579                                                   "FROM pg_aggregate "
3580                                                   "where oid > '%u'::oid",
3581                                                   username_subquery,
3582                                                   g_last_builtin_oid);
3583         }
3584         else
3585         {
3586                 appendPQExpBuffer(query, "SELECT "
3587                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3588                                                   "oid, aggname, "
3589                                                   "0::oid AS aggnamespace, "
3590                                   "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3591                                                   "aggbasetype AS proargtypes, "
3592                                                   "(%s aggowner) AS rolname, "
3593                                                   "'{=X}' AS aggacl "
3594                                                   "FROM pg_aggregate "
3595                                                   "where oid > '%u'::oid",
3596                                                   username_subquery,
3597                                                   g_last_builtin_oid);
3598         }
3599
3600         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3601
3602         ntups = PQntuples(res);
3603         *numAggs = ntups;
3604
3605         agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3606
3607         i_tableoid = PQfnumber(res, "tableoid");
3608         i_oid = PQfnumber(res, "oid");
3609         i_aggname = PQfnumber(res, "aggname");
3610         i_aggnamespace = PQfnumber(res, "aggnamespace");
3611         i_pronargs = PQfnumber(res, "pronargs");
3612         i_proargtypes = PQfnumber(res, "proargtypes");
3613         i_rolname = PQfnumber(res, "rolname");
3614         i_aggacl = PQfnumber(res, "aggacl");
3615
3616         for (i = 0; i < ntups; i++)
3617         {
3618                 agginfo[i].aggfn.dobj.objType = DO_AGG;
3619                 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3620                 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3621                 AssignDumpId(&agginfo[i].aggfn.dobj);
3622                 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3623                 agginfo[i].aggfn.dobj.namespace =
3624                         findNamespace(fout,
3625                                                   atooid(PQgetvalue(res, i, i_aggnamespace)),
3626                                                   agginfo[i].aggfn.dobj.catId.oid);
3627                 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3628                 if (strlen(agginfo[i].aggfn.rolname) == 0)
3629                         write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3630                                           agginfo[i].aggfn.dobj.name);
3631                 agginfo[i].aggfn.lang = InvalidOid;             /* not currently interesting */
3632                 agginfo[i].aggfn.prorettype = InvalidOid;               /* not saved */
3633                 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3634                 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3635                 if (agginfo[i].aggfn.nargs == 0)
3636                         agginfo[i].aggfn.argtypes = NULL;
3637                 else
3638                 {
3639                         agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3640                         if (fout->remoteVersion >= 70300)
3641                                 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3642                                                           agginfo[i].aggfn.argtypes,
3643                                                           agginfo[i].aggfn.nargs);
3644                         else
3645                                 /* it's just aggbasetype */
3646                                 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3647                 }
3648
3649                 /* Decide whether we want to dump it */
3650                 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3651         }
3652
3653         PQclear(res);
3654
3655         destroyPQExpBuffer(query);
3656
3657         return agginfo;
3658 }
3659
3660 /*
3661  * getFuncs:
3662  *        read all the user-defined functions in the system catalogs and
3663  * return them in the FuncInfo* structure
3664  *
3665  * numFuncs is set to the number of functions read in
3666  */
3667 FuncInfo *
3668 getFuncs(Archive *fout, int *numFuncs)
3669 {
3670         PGresult   *res;
3671         int                     ntups;
3672         int                     i;
3673         PQExpBuffer query = createPQExpBuffer();
3674         FuncInfo   *finfo;
3675         int                     i_tableoid;
3676         int                     i_oid;
3677         int                     i_proname;
3678         int                     i_pronamespace;
3679         int                     i_rolname;
3680         int                     i_prolang;
3681         int                     i_pronargs;
3682         int                     i_proargtypes;
3683         int                     i_prorettype;
3684         int                     i_proacl;
3685
3686         /* Make sure we are in proper schema */
3687         selectSourceSchema(fout, "pg_catalog");
3688
3689         /*
3690          * Find all user-defined functions.  Normally we can exclude functions in
3691          * pg_catalog, which is worth doing since there are several thousand of
3692          * 'em.  However, there are some extensions that create functions in
3693          * pg_catalog.  In normal dumps we can still ignore those --- but in
3694          * binary-upgrade mode, we must dump the member objects of the extension,
3695          * so be sure to fetch any such functions.
3696          *
3697          * Also, in 9.2 and up, exclude functions that are internally dependent on
3698          * something else, since presumably those will be created as a result of
3699          * creating the something else.  This currently only acts to suppress
3700          * constructor functions for range types.  Note that this is OK only
3701          * because the constructors don't have any dependencies the range type
3702          * doesn't have; otherwise we might not get creation ordering correct.
3703          */
3704
3705         if (fout->remoteVersion >= 70300)
3706         {
3707                 appendPQExpBuffer(query,
3708                                                   "SELECT tableoid, oid, proname, prolang, "
3709                                                   "pronargs, proargtypes, prorettype, proacl, "
3710                                                   "pronamespace, "
3711                                                   "(%s proowner) AS rolname "
3712                                                   "FROM pg_proc p "
3713                                                   "WHERE NOT proisagg AND ("
3714                                                   "pronamespace != "
3715                                                   "(SELECT oid FROM pg_namespace "
3716                                                   "WHERE nspname = 'pg_catalog')",
3717                                                   username_subquery);
3718                 if (fout->remoteVersion >= 90200)
3719                         appendPQExpBuffer(query,
3720                                                           "\n  AND NOT EXISTS (SELECT 1 FROM pg_depend "
3721                                                           "WHERE classid = 'pg_proc'::regclass AND "
3722                                                           "objid = p.oid AND deptype = 'i')");
3723                 if (binary_upgrade && fout->remoteVersion >= 90100)
3724                         appendPQExpBuffer(query,
3725                                                           "\n  OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3726                                                           "classid = 'pg_proc'::regclass AND "
3727                                                           "objid = p.oid AND "
3728                                                           "refclassid = 'pg_extension'::regclass AND "
3729                                                           "deptype = 'e')");
3730                 appendPQExpBuffer(query, ")");
3731         }
3732         else if (fout->remoteVersion >= 70100)
3733         {
3734                 appendPQExpBuffer(query,
3735                                                   "SELECT tableoid, oid, proname, prolang, "
3736                                                   "pronargs, proargtypes, prorettype, "
3737                                                   "'{=X}' AS proacl, "
3738                                                   "0::oid AS pronamespace, "
3739                                                   "(%s proowner) AS rolname "
3740                                                   "FROM pg_proc "
3741                                                   "WHERE pg_proc.oid > '%u'::oid",
3742                                                   username_subquery,
3743                                                   g_last_builtin_oid);
3744         }
3745         else
3746         {
3747                 appendPQExpBuffer(query,
3748                                                   "SELECT "
3749                                                   "(SELECT oid FROM pg_class "
3750                                                   " WHERE relname = 'pg_proc') AS tableoid, "
3751                                                   "oid, proname, prolang, "
3752                                                   "pronargs, proargtypes, prorettype, "
3753                                                   "'{=X}' AS proacl, "
3754                                                   "0::oid AS pronamespace, "
3755                                                   "(%s proowner) AS rolname "
3756                                                   "FROM pg_proc "
3757                                                   "where pg_proc.oid > '%u'::oid",
3758                                                   username_subquery,
3759                                                   g_last_builtin_oid);
3760         }
3761
3762         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3763
3764         ntups = PQntuples(res);
3765
3766         *numFuncs = ntups;
3767
3768         finfo = (FuncInfo *) pg_calloc(ntups, sizeof(FuncInfo));
3769
3770         i_tableoid = PQfnumber(res, "tableoid");
3771         i_oid = PQfnumber(res, "oid");
3772         i_proname = PQfnumber(res, "proname");
3773         i_pronamespace = PQfnumber(res, "pronamespace");
3774         i_rolname = PQfnumber(res, "rolname");
3775         i_prolang = PQfnumber(res, "prolang");
3776         i_pronargs = PQfnumber(res, "pronargs");
3777         i_proargtypes = PQfnumber(res, "proargtypes");
3778         i_prorettype = PQfnumber(res, "prorettype");
3779         i_proacl = PQfnumber(res, "proacl");
3780
3781         for (i = 0; i < ntups; i++)
3782         {
3783                 finfo[i].dobj.objType = DO_FUNC;
3784                 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3785                 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3786                 AssignDumpId(&finfo[i].dobj);
3787                 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
3788                 finfo[i].dobj.namespace =
3789                         findNamespace(fout,
3790                                                   atooid(PQgetvalue(res, i, i_pronamespace)),
3791                                                   finfo[i].dobj.catId.oid);
3792                 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3793                 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
3794                 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
3795                 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
3796                 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
3797                 if (finfo[i].nargs == 0)
3798                         finfo[i].argtypes = NULL;
3799                 else
3800                 {
3801                         finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
3802                         parseOidArray(PQgetvalue(res, i, i_proargtypes),
3803                                                   finfo[i].argtypes, finfo[i].nargs);
3804                 }
3805
3806                 /* Decide whether we want to dump it */
3807                 selectDumpableObject(&(finfo[i].dobj));
3808
3809                 if (strlen(finfo[i].rolname) == 0)
3810                         write_msg(NULL,
3811                                  "WARNING: owner of function \"%s\" appears to be invalid\n",
3812                                           finfo[i].dobj.name);
3813         }
3814
3815         PQclear(res);
3816
3817         destroyPQExpBuffer(query);
3818
3819         return finfo;
3820 }
3821
3822 /*
3823  * getTables
3824  *        read all the user-defined tables (no indexes, no catalogs)
3825  * in the system catalogs return them in the TableInfo* structure
3826  *
3827  * numTables is set to the number of tables read in
3828  */
3829 TableInfo *
3830 getTables(Archive *fout, int *numTables)
3831 {
3832         PGresult   *res;
3833         int                     ntups;
3834         int                     i;
3835         PQExpBuffer query = createPQExpBuffer();
3836         TableInfo  *tblinfo;
3837         int                     i_reltableoid;
3838         int                     i_reloid;
3839         int                     i_relname;
3840         int                     i_relnamespace;
3841         int                     i_relkind;
3842         int                     i_relacl;
3843         int                     i_rolname;
3844         int                     i_relchecks;
3845         int                     i_relhastriggers;
3846         int                     i_relhasindex;
3847         int                     i_relhasrules;
3848         int                     i_relhasoids;
3849         int                     i_relfrozenxid;
3850         int                     i_toastoid;
3851         int                     i_toastfrozenxid;
3852         int                     i_relpersistence;
3853         int                     i_owning_tab;
3854         int                     i_owning_col;
3855         int                     i_reltablespace;
3856         int                     i_reloptions;
3857         int                     i_toastreloptions;
3858         int                     i_reloftype;
3859
3860         /* Make sure we are in proper schema */
3861         selectSourceSchema(fout, "pg_catalog");
3862
3863         /*
3864          * Find all the tables (including views and sequences).
3865          *
3866          * We include system catalogs, so that we can work if a user table is
3867          * defined to inherit from a system catalog (pretty weird, but...)
3868          *
3869          * We ignore tables that are not type 'r' (ordinary relation), 'S'
3870          * (sequence), 'v' (view), or 'c' (composite type).
3871          *
3872          * Composite-type table entries won't be dumped as such, but we have to
3873          * make a DumpableObject for them so that we can track dependencies of the
3874          * composite type (pg_depend entries for columns of the composite type
3875          * link to the pg_class entry not the pg_type entry).
3876          *
3877          * Note: in this phase we should collect only a minimal amount of
3878          * information about each table, basically just enough to decide if it is
3879          * interesting. We must fetch all tables in this phase because otherwise
3880          * we cannot correctly identify inherited columns, owned sequences, etc.
3881          */
3882
3883         if (fout->remoteVersion >= 90100)
3884         {
3885                 /*
3886                  * Left join to pick up dependency info linking sequences to their
3887                  * owning column, if any (note this dependency is AUTO as of 8.2)
3888                  */
3889                 appendPQExpBuffer(query,
3890                                                   "SELECT c.tableoid, c.oid, c.relname, "
3891                                                   "c.relacl, c.relkind, c.relnamespace, "
3892                                                   "(%s c.relowner) AS rolname, "
3893                                                   "c.relchecks, c.relhastriggers, "
3894                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3895                                                   "c.relfrozenxid, tc.oid AS toid, "
3896                                                   "tc.relfrozenxid AS tfrozenxid, "
3897                                                   "c.relpersistence, "
3898                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3899                                                   "d.refobjid AS owning_tab, "
3900                                                   "d.refobjsubid AS owning_col, "
3901                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3902                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3903                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3904                                                   "FROM pg_class c "
3905                                                   "LEFT JOIN pg_depend d ON "
3906                                                   "(c.relkind = '%c' AND "
3907                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3908                                                   "d.objsubid = 0 AND "
3909                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
3910                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3911                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c') "
3912                                                   "ORDER BY c.oid",
3913                                                   username_subquery,
3914                                                   RELKIND_SEQUENCE,
3915                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3916                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
3917                                                   RELKIND_FOREIGN_TABLE);
3918         }
3919         else if (fout->remoteVersion >= 90000)
3920         {
3921                 /*
3922                  * Left join to pick up dependency info linking sequences to their
3923                  * owning column, if any (note this dependency is AUTO as of 8.2)
3924                  */
3925                 appendPQExpBuffer(query,
3926                                                   "SELECT c.tableoid, c.oid, c.relname, "
3927                                                   "c.relacl, c.relkind, c.relnamespace, "
3928                                                   "(%s c.relowner) AS rolname, "
3929                                                   "c.relchecks, c.relhastriggers, "
3930                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3931                                                   "c.relfrozenxid, tc.oid AS toid, "
3932                                                   "tc.relfrozenxid AS tfrozenxid, "
3933                                                   "'p' AS relpersistence, "
3934                                                   "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3935                                                   "d.refobjid AS owning_tab, "
3936                                                   "d.refobjsubid AS owning_col, "
3937                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3938                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3939                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3940                                                   "FROM pg_class c "
3941                                                   "LEFT JOIN pg_depend d ON "
3942                                                   "(c.relkind = '%c' AND "
3943                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3944                                                   "d.objsubid = 0 AND "
3945                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
3946                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3947                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3948                                                   "ORDER BY c.oid",
3949                                                   username_subquery,
3950                                                   RELKIND_SEQUENCE,
3951                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3952                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3953         }
3954         else if (fout->remoteVersion >= 80400)
3955         {
3956                 /*
3957                  * Left join to pick up dependency info linking sequences to their
3958                  * owning column, if any (note this dependency is AUTO as of 8.2)
3959                  */
3960                 appendPQExpBuffer(query,
3961                                                   "SELECT c.tableoid, c.oid, c.relname, "
3962                                                   "c.relacl, c.relkind, c.relnamespace, "
3963                                                   "(%s c.relowner) AS rolname, "
3964                                                   "c.relchecks, c.relhastriggers, "
3965                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
3966                                                   "c.relfrozenxid, tc.oid AS toid, "
3967                                                   "tc.relfrozenxid AS tfrozenxid, "
3968                                                   "'p' AS relpersistence, "
3969                                                   "NULL AS reloftype, "
3970                                                   "d.refobjid AS owning_tab, "
3971                                                   "d.refobjsubid AS owning_col, "
3972                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3973                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
3974                                                   "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3975                                                   "FROM pg_class c "
3976                                                   "LEFT JOIN pg_depend d ON "
3977                                                   "(c.relkind = '%c' AND "
3978                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
3979                                                   "d.objsubid = 0 AND "
3980                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
3981                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3982                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3983                                                   "ORDER BY c.oid",
3984                                                   username_subquery,
3985                                                   RELKIND_SEQUENCE,
3986                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
3987                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3988         }
3989         else if (fout->remoteVersion >= 80200)
3990         {
3991                 /*
3992                  * Left join to pick up dependency info linking sequences to their
3993                  * owning column, if any (note this dependency is AUTO as of 8.2)
3994                  */
3995                 appendPQExpBuffer(query,
3996                                                   "SELECT c.tableoid, c.oid, c.relname, "
3997                                                   "c.relacl, c.relkind, c.relnamespace, "
3998                                                   "(%s c.relowner) AS rolname, "
3999                                                   "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
4000                                                   "c.relhasindex, c.relhasrules, c.relhasoids, "
4001                                                   "c.relfrozenxid, tc.oid AS toid, "
4002                                                   "tc.relfrozenxid AS tfrozenxid, "
4003                                                   "'p' AS relpersistence, "
4004                                                   "NULL AS reloftype, "
4005                                                   "d.refobjid AS owning_tab, "
4006                                                   "d.refobjsubid AS owning_col, "
4007                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4008                                                 "array_to_string(c.reloptions, ', ') AS reloptions, "
4009                                                   "NULL AS toast_reloptions "
4010                                                   "FROM pg_class c "
4011                                                   "LEFT JOIN pg_depend d ON "
4012                                                   "(c.relkind = '%c' AND "
4013                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4014                                                   "d.objsubid = 0 AND "
4015                                                   "d.refclassid = c.tableoid AND d.deptype = 'a') "
4016                                            "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4017                                                   "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4018                                                   "ORDER BY c.oid",
4019                                                   username_subquery,
4020                                                   RELKIND_SEQUENCE,
4021                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4022                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4023         }
4024         else if (fout->remoteVersion >= 80000)
4025         {
4026                 /*
4027                  * Left join to pick up dependency info linking sequences to their
4028                  * owning column, if any
4029                  */
4030                 appendPQExpBuffer(query,
4031                                                   "SELECT c.tableoid, c.oid, relname, "
4032                                                   "relacl, relkind, relnamespace, "
4033                                                   "(%s relowner) AS rolname, "
4034                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4035                                                   "relhasindex, relhasrules, relhasoids, "
4036                                                   "0 AS relfrozenxid, "
4037                                                   "0 AS toid, "
4038                                                   "0 AS tfrozenxid, "
4039                                                   "'p' AS relpersistence, "
4040                                                   "NULL AS reloftype, "
4041                                                   "d.refobjid AS owning_tab, "
4042                                                   "d.refobjsubid AS owning_col, "
4043                                                   "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4044                                                   "NULL AS reloptions, "
4045                                                   "NULL AS toast_reloptions "
4046                                                   "FROM pg_class c "
4047                                                   "LEFT JOIN pg_depend d ON "
4048                                                   "(c.relkind = '%c' AND "
4049                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4050                                                   "d.objsubid = 0 AND "
4051                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4052                                                   "WHERE relkind in ('%c', '%c', '%c', '%c') "
4053                                                   "ORDER BY c.oid",
4054                                                   username_subquery,
4055                                                   RELKIND_SEQUENCE,
4056                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4057                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4058         }
4059         else if (fout->remoteVersion >= 70300)
4060         {
4061                 /*
4062                  * Left join to pick up dependency info linking sequences to their
4063                  * owning column, if any
4064                  */
4065                 appendPQExpBuffer(query,
4066                                                   "SELECT c.tableoid, c.oid, relname, "
4067                                                   "relacl, relkind, relnamespace, "
4068                                                   "(%s relowner) AS rolname, "
4069                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4070                                                   "relhasindex, relhasrules, relhasoids, "
4071                                                   "0 AS relfrozenxid, "
4072                                                   "0 AS toid, "
4073                                                   "0 AS tfrozenxid, "
4074                                                   "'p' AS relpersistence, "
4075                                                   "NULL AS reloftype, "
4076                                                   "d.refobjid AS owning_tab, "
4077                                                   "d.refobjsubid AS owning_col, "
4078                                                   "NULL AS reltablespace, "
4079                                                   "NULL AS reloptions, "
4080                                                   "NULL AS toast_reloptions "
4081                                                   "FROM pg_class c "
4082                                                   "LEFT JOIN pg_depend d ON "
4083                                                   "(c.relkind = '%c' AND "
4084                                                   "d.classid = c.tableoid AND d.objid = c.oid AND "
4085                                                   "d.objsubid = 0 AND "
4086                                                   "d.refclassid = c.tableoid AND d.deptype = 'i') "
4087                                                   "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4088                                                   "ORDER BY c.oid",
4089                                                   username_subquery,
4090                                                   RELKIND_SEQUENCE,
4091                                                   RELKIND_RELATION, RELKIND_SEQUENCE,
4092                                                   RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4093         }
4094         else if (fout->remoteVersion >= 70200)
4095         {
4096                 appendPQExpBuffer(query,
4097                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4098                                                   "0::oid AS relnamespace, "
4099                                                   "(%s relowner) AS rolname, "
4100                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4101                                                   "relhasindex, relhasrules, relhasoids, "
4102                                                   "0 AS relfrozenxid, "
4103                                                   "0 AS toid, "
4104                                                   "0 AS tfrozenxid, "
4105                                                   "'p' AS relpersistence, "
4106                                                   "NULL AS reloftype, "
4107                                                   "NULL::oid AS owning_tab, "
4108                                                   "NULL::int4 AS owning_col, "
4109                                                   "NULL AS reltablespace, "
4110                                                   "NULL AS reloptions, "
4111                                                   "NULL AS toast_reloptions "
4112                                                   "FROM pg_class "
4113                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4114                                                   "ORDER BY oid",
4115                                                   username_subquery,
4116                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4117         }
4118         else if (fout->remoteVersion >= 70100)
4119         {
4120                 /* all tables have oids in 7.1 */
4121                 appendPQExpBuffer(query,
4122                                                   "SELECT tableoid, oid, relname, relacl, relkind, "
4123                                                   "0::oid AS relnamespace, "
4124                                                   "(%s relowner) AS rolname, "
4125                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4126                                                   "relhasindex, relhasrules, "
4127                                                   "'t'::bool AS relhasoids, "
4128                                                   "0 AS relfrozenxid, "
4129                                                   "0 AS toid, "
4130                                                   "0 AS tfrozenxid, "
4131                                                   "'p' AS relpersistence, "
4132                                                   "NULL AS reloftype, "
4133                                                   "NULL::oid AS owning_tab, "
4134                                                   "NULL::int4 AS owning_col, "
4135                                                   "NULL AS reltablespace, "
4136                                                   "NULL AS reloptions, "
4137                                                   "NULL AS toast_reloptions "
4138                                                   "FROM pg_class "
4139                                                   "WHERE relkind IN ('%c', '%c', '%c') "
4140                                                   "ORDER BY oid",
4141                                                   username_subquery,
4142                                                   RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4143         }
4144         else
4145         {
4146                 /*
4147                  * Before 7.1, view relkind was not set to 'v', so we must check if we
4148                  * have a view by looking for a rule in pg_rewrite.
4149                  */
4150                 appendPQExpBuffer(query,
4151                                                   "SELECT "
4152                 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4153                                                   "oid, relname, relacl, "
4154                                                   "CASE WHEN relhasrules and relkind = 'r' "
4155                                           "  and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4156                                           "             r.ev_class = c.oid AND r.ev_type = '1') "
4157                                                   "THEN '%c'::\"char\" "
4158                                                   "ELSE relkind END AS relkind,"
4159                                                   "0::oid AS relnamespace, "
4160                                                   "(%s relowner) AS rolname, "
4161                                                   "relchecks, (reltriggers <> 0) AS relhastriggers, "
4162                                                   "relhasindex, relhasrules, "
4163                                                   "'t'::bool AS relhasoids, "
4164                                                   "0 as relfrozenxid, "
4165                                                   "0 AS toid, "
4166                                                   "0 AS tfrozenxid, "
4167                                                   "'p' AS relpersistence, "
4168                                                   "NULL AS reloftype, "
4169                                                   "NULL::oid AS owning_tab, "
4170                                                   "NULL::int4 AS owning_col, "
4171                                                   "NULL AS reltablespace, "
4172                                                   "NULL AS reloptions, "
4173                                                   "NULL AS toast_reloptions "
4174                                                   "FROM pg_class c "
4175                                                   "WHERE relkind IN ('%c', '%c') "
4176                                                   "ORDER BY oid",
4177                                                   RELKIND_VIEW,
4178                                                   username_subquery,
4179                                                   RELKIND_RELATION, RELKIND_SEQUENCE);
4180         }
4181
4182         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4183
4184         ntups = PQntuples(res);
4185
4186         *numTables = ntups;
4187
4188         /*
4189          * Extract data from result and lock dumpable tables.  We do the locking
4190          * before anything else, to minimize the window wherein a table could
4191          * disappear under us.
4192          *
4193          * Note that we have to save info about all tables here, even when dumping
4194          * only one, because we don't yet know which tables might be inheritance
4195          * ancestors of the target table.
4196          */
4197         tblinfo = (TableInfo *) pg_calloc(ntups, sizeof(TableInfo));
4198
4199         i_reltableoid = PQfnumber(res, "tableoid");
4200         i_reloid = PQfnumber(res, "oid");
4201         i_relname = PQfnumber(res, "relname");
4202         i_relnamespace = PQfnumber(res, "relnamespace");
4203         i_relacl = PQfnumber(res, "relacl");
4204         i_relkind = PQfnumber(res, "relkind");
4205         i_rolname = PQfnumber(res, "rolname");
4206         i_relchecks = PQfnumber(res, "relchecks");
4207         i_relhastriggers = PQfnumber(res, "relhastriggers");
4208         i_relhasindex = PQfnumber(res, "relhasindex");
4209         i_relhasrules = PQfnumber(res, "relhasrules");
4210         i_relhasoids = PQfnumber(res, "relhasoids");
4211         i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4212         i_toastoid = PQfnumber(res, "toid");
4213         i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4214         i_relpersistence = PQfnumber(res, "relpersistence");
4215         i_owning_tab = PQfnumber(res, "owning_tab");
4216         i_owning_col = PQfnumber(res, "owning_col");
4217         i_reltablespace = PQfnumber(res, "reltablespace");
4218         i_reloptions = PQfnumber(res, "reloptions");
4219         i_toastreloptions = PQfnumber(res, "toast_reloptions");
4220         i_reloftype = PQfnumber(res, "reloftype");
4221
4222         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4223         {
4224                 /*
4225                  * Arrange to fail instead of waiting forever for a table lock.
4226                  *
4227                  * NB: this coding assumes that the only queries issued within the
4228                  * following loop are LOCK TABLEs; else the timeout may be undesirably
4229                  * applied to other things too.
4230                  */
4231                 resetPQExpBuffer(query);
4232                 appendPQExpBuffer(query, "SET statement_timeout = ");
4233                 appendStringLiteralConn(query, lockWaitTimeout, GetConnection(fout));
4234                 ExecuteSqlStatement(fout, query->data);
4235         }
4236
4237         for (i = 0; i < ntups; i++)
4238         {
4239                 tblinfo[i].dobj.objType = DO_TABLE;
4240                 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4241                 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4242                 AssignDumpId(&tblinfo[i].dobj);
4243                 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4244                 tblinfo[i].dobj.namespace =
4245                         findNamespace(fout,
4246                                                   atooid(PQgetvalue(res, i, i_relnamespace)),
4247                                                   tblinfo[i].dobj.catId.oid);
4248                 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4249                 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4250                 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4251                 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4252                 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4253                 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4254                 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4255                 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4256                 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4257                 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4258                 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4259                 if (PQgetisnull(res, i, i_reloftype))
4260                         tblinfo[i].reloftype = NULL;
4261                 else
4262                         tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4263                 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4264                 if (PQgetisnull(res, i, i_owning_tab))
4265                 {
4266                         tblinfo[i].owning_tab = InvalidOid;
4267                         tblinfo[i].owning_col = 0;
4268                 }
4269                 else
4270                 {
4271                         tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4272                         tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4273                 }
4274                 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4275                 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4276                 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4277
4278                 /* other fields were zeroed above */
4279
4280                 /*
4281                  * Decide whether we want to dump this table.
4282                  */
4283                 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4284                         tblinfo[i].dobj.dump = false;
4285                 else
4286                         selectDumpableTable(&tblinfo[i]);
4287                 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4288
4289                 /*
4290                  * Read-lock target tables to make sure they aren't DROPPED or altered
4291                  * in schema before we get around to dumping them.
4292                  *
4293                  * Note that we don't explicitly lock parents of the target tables; we
4294                  * assume our lock on the child is enough to prevent schema
4295                  * alterations to parent tables.
4296                  *
4297                  * NOTE: it'd be kinda nice to lock other relations too, not only
4298                  * plain tables, but the backend doesn't presently allow that.
4299                  */
4300                 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4301                 {
4302                         resetPQExpBuffer(query);
4303                         appendPQExpBuffer(query,
4304                                                           "LOCK TABLE %s IN ACCESS SHARE MODE",
4305                                                  fmtQualifiedId(fout,
4306                                                                                 tblinfo[i].dobj.namespace->dobj.name,
4307                                                                                 tblinfo[i].dobj.name));
4308                         ExecuteSqlStatement(fout, query->data);
4309                 }
4310
4311                 /* Emit notice if join for owner failed */
4312                 if (strlen(tblinfo[i].rolname) == 0)
4313                         write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4314                                           tblinfo[i].dobj.name);
4315         }
4316
4317         if (lockWaitTimeout && fout->remoteVersion >= 70300)
4318         {
4319                 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4320         }
4321
4322         PQclear(res);
4323
4324         /*
4325          * Force sequences that are "owned" by table columns to be dumped whenever
4326          * their owning table is being dumped.
4327          */
4328         for (i = 0; i < ntups; i++)
4329         {
4330                 TableInfo  *seqinfo = &tblinfo[i];
4331                 int                     j;
4332
4333                 if (!OidIsValid(seqinfo->owning_tab))
4334                         continue;                       /* not an owned sequence */
4335                 if (seqinfo->dobj.dump)
4336                         continue;                       /* no need to search */
4337
4338                 /* can't use findTableByOid yet, unfortunately */
4339                 for (j = 0; j < ntups; j++)
4340                 {
4341                         if (tblinfo[j].dobj.catId.oid == seqinfo->owning_tab)
4342                         {
4343                                 if (tblinfo[j].dobj.dump)
4344                                 {
4345                                         seqinfo->interesting = true;
4346                                         seqinfo->dobj.dump = true;
4347                                 }
4348                                 break;
4349                         }
4350                 }
4351         }
4352
4353         destroyPQExpBuffer(query);
4354
4355         return tblinfo;
4356 }
4357
4358 /*
4359  * getInherits
4360  *        read all the inheritance information
4361  * from the system catalogs return them in the InhInfo* structure
4362  *
4363  * numInherits is set to the number of pairs read in
4364  */
4365 InhInfo *
4366 getInherits(Archive *fout, int *numInherits)
4367 {
4368         PGresult   *res;
4369         int                     ntups;
4370         int                     i;
4371         PQExpBuffer query = createPQExpBuffer();
4372         InhInfo    *inhinfo;
4373
4374         int                     i_inhrelid;
4375         int                     i_inhparent;
4376
4377         /* Make sure we are in proper schema */
4378         selectSourceSchema(fout, "pg_catalog");
4379
4380         /* find all the inheritance information */
4381
4382         appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4383
4384         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4385
4386         ntups = PQntuples(res);
4387
4388         *numInherits = ntups;
4389
4390         inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4391
4392         i_inhrelid = PQfnumber(res, "inhrelid");
4393         i_inhparent = PQfnumber(res, "inhparent");
4394
4395         for (i = 0; i < ntups; i++)
4396         {
4397                 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4398                 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4399         }
4400
4401         PQclear(res);
4402
4403         destroyPQExpBuffer(query);
4404
4405         return inhinfo;
4406 }
4407
4408 /*
4409  * getIndexes
4410  *        get information about every index on a dumpable table
4411  *
4412  * Note: index data is not returned directly to the caller, but it
4413  * does get entered into the DumpableObject tables.
4414  */
4415 void
4416 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4417 {
4418         int                     i,
4419                                 j;
4420         PQExpBuffer query = createPQExpBuffer();
4421         PGresult   *res;
4422         IndxInfo   *indxinfo;
4423         ConstraintInfo *constrinfo;
4424         int                     i_tableoid,
4425                                 i_oid,
4426                                 i_indexname,
4427                                 i_indexdef,
4428                                 i_indnkeys,
4429                                 i_indkey,
4430                                 i_indisclustered,
4431                                 i_contype,
4432                                 i_conname,
4433                                 i_condeferrable,
4434                                 i_condeferred,
4435                                 i_contableoid,
4436                                 i_conoid,
4437                                 i_condef,
4438                                 i_tablespace,
4439                                 i_options;
4440         int                     ntups;
4441
4442         for (i = 0; i < numTables; i++)
4443         {
4444                 TableInfo  *tbinfo = &tblinfo[i];
4445
4446                 /* Only plain tables have indexes */
4447                 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
4448                         continue;
4449
4450                 /* Ignore indexes of tables not to be dumped */
4451                 if (!tbinfo->dobj.dump)
4452                         continue;
4453
4454                 if (g_verbose)
4455                         write_msg(NULL, "reading indexes for table \"%s\"\n",
4456                                           tbinfo->dobj.name);
4457
4458                 /* Make sure we are in proper schema so indexdef is right */
4459                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4460
4461                 /*
4462                  * The point of the messy-looking outer join is to find a constraint
4463                  * that is related by an internal dependency link to the index. If we
4464                  * find one, create a CONSTRAINT entry linked to the INDEX entry.  We
4465                  * assume an index won't have more than one internal dependency.
4466                  *
4467                  * As of 9.0 we don't need to look at pg_depend but can check for a
4468                  * match to pg_constraint.conindid.  The check on conrelid is
4469                  * redundant but useful because that column is indexed while conindid
4470                  * is not.
4471                  */
4472                 resetPQExpBuffer(query);
4473                 if (fout->remoteVersion >= 90000)
4474                 {
4475                         appendPQExpBuffer(query,
4476                                                           "SELECT t.tableoid, t.oid, "
4477                                                           "t.relname AS indexname, "
4478                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4479                                                           "t.relnatts AS indnkeys, "
4480                                                           "i.indkey, i.indisclustered, "
4481                                                           "c.contype, c.conname, "
4482                                                           "c.condeferrable, c.condeferred, "
4483                                                           "c.tableoid AS contableoid, "
4484                                                           "c.oid AS conoid, "
4485                                   "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4486                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4487                                                         "array_to_string(t.reloptions, ', ') AS options "
4488                                                           "FROM pg_catalog.pg_index i "
4489                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4490                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4491                                                           "ON (i.indrelid = c.conrelid AND "
4492                                                           "i.indexrelid = c.conindid AND "
4493                                                           "c.contype IN ('p','u','x')) "
4494                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4495                                                           "ORDER BY indexname",
4496                                                           tbinfo->dobj.catId.oid);
4497                 }
4498                 else if (fout->remoteVersion >= 80200)
4499                 {
4500                         appendPQExpBuffer(query,
4501                                                           "SELECT t.tableoid, t.oid, "
4502                                                           "t.relname AS indexname, "
4503                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4504                                                           "t.relnatts AS indnkeys, "
4505                                                           "i.indkey, i.indisclustered, "
4506                                                           "c.contype, c.conname, "
4507                                                           "c.condeferrable, c.condeferred, "
4508                                                           "c.tableoid AS contableoid, "
4509                                                           "c.oid AS conoid, "
4510                                                           "null AS condef, "
4511                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4512                                                         "array_to_string(t.reloptions, ', ') AS options "
4513                                                           "FROM pg_catalog.pg_index i "
4514                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4515                                                           "LEFT JOIN pg_catalog.pg_depend d "
4516                                                           "ON (d.classid = t.tableoid "
4517                                                           "AND d.objid = t.oid "
4518                                                           "AND d.deptype = 'i') "
4519                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4520                                                           "ON (d.refclassid = c.tableoid "
4521                                                           "AND d.refobjid = c.oid) "
4522                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4523                                                           "ORDER BY indexname",
4524                                                           tbinfo->dobj.catId.oid);
4525                 }
4526                 else if (fout->remoteVersion >= 80000)
4527                 {
4528                         appendPQExpBuffer(query,
4529                                                           "SELECT t.tableoid, t.oid, "
4530                                                           "t.relname AS indexname, "
4531                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4532                                                           "t.relnatts AS indnkeys, "
4533                                                           "i.indkey, i.indisclustered, "
4534                                                           "c.contype, c.conname, "
4535                                                           "c.condeferrable, c.condeferred, "
4536                                                           "c.tableoid AS contableoid, "
4537                                                           "c.oid AS conoid, "
4538                                                           "null AS condef, "
4539                                                           "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4540                                                           "null AS options "
4541                                                           "FROM pg_catalog.pg_index i "
4542                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4543                                                           "LEFT JOIN pg_catalog.pg_depend d "
4544                                                           "ON (d.classid = t.tableoid "
4545                                                           "AND d.objid = t.oid "
4546                                                           "AND d.deptype = 'i') "
4547                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4548                                                           "ON (d.refclassid = c.tableoid "
4549                                                           "AND d.refobjid = c.oid) "
4550                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4551                                                           "ORDER BY indexname",
4552                                                           tbinfo->dobj.catId.oid);
4553                 }
4554                 else if (fout->remoteVersion >= 70300)
4555                 {
4556                         appendPQExpBuffer(query,
4557                                                           "SELECT t.tableoid, t.oid, "
4558                                                           "t.relname AS indexname, "
4559                                          "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4560                                                           "t.relnatts AS indnkeys, "
4561                                                           "i.indkey, i.indisclustered, "
4562                                                           "c.contype, c.conname, "
4563                                                           "c.condeferrable, c.condeferred, "
4564                                                           "c.tableoid AS contableoid, "
4565                                                           "c.oid AS conoid, "
4566                                                           "null AS condef, "
4567                                                           "NULL AS tablespace, "
4568                                                           "null AS options "
4569                                                           "FROM pg_catalog.pg_index i "
4570                                           "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4571                                                           "LEFT JOIN pg_catalog.pg_depend d "
4572                                                           "ON (d.classid = t.tableoid "
4573                                                           "AND d.objid = t.oid "
4574                                                           "AND d.deptype = 'i') "
4575                                                           "LEFT JOIN pg_catalog.pg_constraint c "
4576                                                           "ON (d.refclassid = c.tableoid "
4577                                                           "AND d.refobjid = c.oid) "
4578                                                           "WHERE i.indrelid = '%u'::pg_catalog.oid "
4579                                                           "ORDER BY indexname",
4580                                                           tbinfo->dobj.catId.oid);
4581                 }
4582                 else if (fout->remoteVersion >= 70100)
4583                 {
4584                         appendPQExpBuffer(query,
4585                                                           "SELECT t.tableoid, t.oid, "
4586                                                           "t.relname AS indexname, "
4587                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
4588                                                           "t.relnatts AS indnkeys, "
4589                                                           "i.indkey, false AS indisclustered, "
4590                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
4591                                                           "ELSE '0'::char END AS contype, "
4592                                                           "t.relname AS conname, "
4593                                                           "false AS condeferrable, "
4594                                                           "false AS condeferred, "
4595                                                           "0::oid AS contableoid, "
4596                                                           "t.oid AS conoid, "
4597                                                           "null AS condef, "
4598                                                           "NULL AS tablespace, "
4599                                                           "null AS options "
4600                                                           "FROM pg_index i, pg_class t "
4601                                                           "WHERE t.oid = i.indexrelid "
4602                                                           "AND i.indrelid = '%u'::oid "
4603                                                           "ORDER BY indexname",
4604                                                           tbinfo->dobj.catId.oid);
4605                 }
4606                 else
4607                 {
4608                         appendPQExpBuffer(query,
4609                                                           "SELECT "
4610                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4611                                                           "t.oid, "
4612                                                           "t.relname AS indexname, "
4613                                                           "pg_get_indexdef(i.indexrelid) AS indexdef, "
4614                                                           "t.relnatts AS indnkeys, "
4615                                                           "i.indkey, false AS indisclustered, "
4616                                                           "CASE WHEN i.indisprimary THEN 'p'::char "
4617                                                           "ELSE '0'::char END AS contype, "
4618                                                           "t.relname AS conname, "
4619                                                           "false AS condeferrable, "
4620                                                           "false AS condeferred, "
4621                                                           "0::oid AS contableoid, "
4622                                                           "t.oid AS conoid, "
4623                                                           "null AS condef, "
4624                                                           "NULL AS tablespace, "
4625                                                           "null AS options "
4626                                                           "FROM pg_index i, pg_class t "
4627                                                           "WHERE t.oid = i.indexrelid "
4628                                                           "AND i.indrelid = '%u'::oid "
4629                                                           "ORDER BY indexname",
4630                                                           tbinfo->dobj.catId.oid);
4631                 }
4632
4633                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4634
4635                 ntups = PQntuples(res);
4636
4637                 i_tableoid = PQfnumber(res, "tableoid");
4638                 i_oid = PQfnumber(res, "oid");
4639                 i_indexname = PQfnumber(res, "indexname");
4640                 i_indexdef = PQfnumber(res, "indexdef");
4641                 i_indnkeys = PQfnumber(res, "indnkeys");
4642                 i_indkey = PQfnumber(res, "indkey");
4643                 i_indisclustered = PQfnumber(res, "indisclustered");
4644                 i_contype = PQfnumber(res, "contype");
4645                 i_conname = PQfnumber(res, "conname");
4646                 i_condeferrable = PQfnumber(res, "condeferrable");
4647                 i_condeferred = PQfnumber(res, "condeferred");
4648                 i_contableoid = PQfnumber(res, "contableoid");
4649                 i_conoid = PQfnumber(res, "conoid");
4650                 i_condef = PQfnumber(res, "condef");
4651                 i_tablespace = PQfnumber(res, "tablespace");
4652                 i_options = PQfnumber(res, "options");
4653
4654                 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
4655                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4656
4657                 for (j = 0; j < ntups; j++)
4658                 {
4659                         char            contype;
4660
4661                         indxinfo[j].dobj.objType = DO_INDEX;
4662                         indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4663                         indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4664                         AssignDumpId(&indxinfo[j].dobj);
4665                         indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
4666                         indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4667                         indxinfo[j].indextable = tbinfo;
4668                         indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
4669                         indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4670                         indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
4671                         indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
4672
4673                         /*
4674                          * In pre-7.4 releases, indkeys may contain more entries than
4675                          * indnkeys says (since indnkeys will be 1 for a functional
4676                          * index).      We don't actually care about this case since we don't
4677                          * examine indkeys except for indexes associated with PRIMARY and
4678                          * UNIQUE constraints, which are never functional indexes. But we
4679                          * have to allocate enough space to keep parseOidArray from
4680                          * complaining.
4681                          */
4682                         indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
4683                         parseOidArray(PQgetvalue(res, j, i_indkey),
4684                                                   indxinfo[j].indkeys, INDEX_MAX_KEYS);
4685                         indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4686                         contype = *(PQgetvalue(res, j, i_contype));
4687
4688                         if (contype == 'p' || contype == 'u' || contype == 'x')
4689                         {
4690                                 /*
4691                                  * If we found a constraint matching the index, create an
4692                                  * entry for it.
4693                                  *
4694                                  * In a pre-7.3 database, we take this path iff the index was
4695                                  * marked indisprimary.
4696                                  */
4697                                 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4698                                 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4699                                 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4700                                 AssignDumpId(&constrinfo[j].dobj);
4701                                 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4702                                 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4703                                 constrinfo[j].contable = tbinfo;
4704                                 constrinfo[j].condomain = NULL;
4705                                 constrinfo[j].contype = contype;
4706                                 if (contype == 'x')
4707                                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4708                                 else
4709                                         constrinfo[j].condef = NULL;
4710                                 constrinfo[j].confrelid = InvalidOid;
4711                                 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4712                                 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4713                                 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4714                                 constrinfo[j].conislocal = true;
4715                                 constrinfo[j].separate = true;
4716
4717                                 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4718
4719                                 /* If pre-7.3 DB, better make sure table comes first */
4720                                 addObjectDependency(&constrinfo[j].dobj,
4721                                                                         tbinfo->dobj.dumpId);
4722                         }
4723                         else
4724                         {
4725                                 /* Plain secondary index */
4726                                 indxinfo[j].indexconstraint = 0;
4727                         }
4728                 }
4729
4730                 PQclear(res);
4731         }
4732
4733         destroyPQExpBuffer(query);
4734 }
4735
4736 /*
4737  * getConstraints
4738  *
4739  * Get info about constraints on dumpable tables.
4740  *
4741  * Currently handles foreign keys only.
4742  * Unique and primary key constraints are handled with indexes,
4743  * while check constraints are processed in getTableAttrs().
4744  */
4745 void
4746 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
4747 {
4748         int                     i,
4749                                 j;
4750         ConstraintInfo *constrinfo;
4751         PQExpBuffer query;
4752         PGresult   *res;
4753         int                     i_contableoid,
4754                                 i_conoid,
4755                                 i_conname,
4756                                 i_confrelid,
4757                                 i_condef;
4758         int                     ntups;
4759
4760         /* pg_constraint was created in 7.3, so nothing to do if older */
4761         if (fout->remoteVersion < 70300)
4762                 return;
4763
4764         query = createPQExpBuffer();
4765
4766         for (i = 0; i < numTables; i++)
4767         {
4768                 TableInfo  *tbinfo = &tblinfo[i];
4769
4770                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4771                         continue;
4772
4773                 if (g_verbose)
4774                         write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
4775                                           tbinfo->dobj.name);
4776
4777                 /*
4778                  * select table schema to ensure constraint expr is qualified if
4779                  * needed
4780                  */
4781                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4782
4783                 resetPQExpBuffer(query);
4784                 appendPQExpBuffer(query,
4785                                                   "SELECT tableoid, oid, conname, confrelid, "
4786                                                   "pg_catalog.pg_get_constraintdef(oid) AS condef "
4787                                                   "FROM pg_catalog.pg_constraint "
4788                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
4789                                                   "AND contype = 'f'",
4790                                                   tbinfo->dobj.catId.oid);
4791                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4792
4793                 ntups = PQntuples(res);
4794
4795                 i_contableoid = PQfnumber(res, "tableoid");
4796                 i_conoid = PQfnumber(res, "oid");
4797                 i_conname = PQfnumber(res, "conname");
4798                 i_confrelid = PQfnumber(res, "confrelid");
4799                 i_condef = PQfnumber(res, "condef");
4800
4801                 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4802
4803                 for (j = 0; j < ntups; j++)
4804                 {
4805                         constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
4806                         constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4807                         constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4808                         AssignDumpId(&constrinfo[j].dobj);
4809                         constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4810                         constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4811                         constrinfo[j].contable = tbinfo;
4812                         constrinfo[j].condomain = NULL;
4813                         constrinfo[j].contype = 'f';
4814                         constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4815                         constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
4816                         constrinfo[j].conindex = 0;
4817                         constrinfo[j].condeferrable = false;
4818                         constrinfo[j].condeferred = false;
4819                         constrinfo[j].conislocal = true;
4820                         constrinfo[j].separate = true;
4821                 }
4822
4823                 PQclear(res);
4824         }
4825
4826         destroyPQExpBuffer(query);
4827 }
4828
4829 /*
4830  * getDomainConstraints
4831  *
4832  * Get info about constraints on a domain.
4833  */
4834 static void
4835 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
4836 {
4837         int                     i;
4838         ConstraintInfo *constrinfo;
4839         PQExpBuffer query;
4840         PGresult   *res;
4841         int                     i_tableoid,
4842                                 i_oid,
4843                                 i_conname,
4844                                 i_consrc;
4845         int                     ntups;
4846
4847         /* pg_constraint was created in 7.3, so nothing to do if older */
4848         if (fout->remoteVersion < 70300)
4849                 return;
4850
4851         /*
4852          * select appropriate schema to ensure names in constraint are properly
4853          * qualified
4854          */
4855         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
4856
4857         query = createPQExpBuffer();
4858
4859         if (fout->remoteVersion >= 90100)
4860                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4861                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4862                                                   "convalidated "
4863                                                   "FROM pg_catalog.pg_constraint "
4864                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4865                                                   "ORDER BY conname",
4866                                                   tyinfo->dobj.catId.oid);
4867
4868         else if (fout->remoteVersion >= 70400)
4869                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4870                                                   "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4871                                                   "true as convalidated "
4872                                                   "FROM pg_catalog.pg_constraint "
4873                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4874                                                   "ORDER BY conname",
4875                                                   tyinfo->dobj.catId.oid);
4876         else
4877                 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4878                                                   "'CHECK (' || consrc || ')' AS consrc, "
4879                                                   "true as convalidated "
4880                                                   "FROM pg_catalog.pg_constraint "
4881                                                   "WHERE contypid = '%u'::pg_catalog.oid "
4882                                                   "ORDER BY conname",
4883                                                   tyinfo->dobj.catId.oid);
4884
4885         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4886
4887         ntups = PQntuples(res);
4888
4889         i_tableoid = PQfnumber(res, "tableoid");
4890         i_oid = PQfnumber(res, "oid");
4891         i_conname = PQfnumber(res, "conname");
4892         i_consrc = PQfnumber(res, "consrc");
4893
4894         constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4895
4896         tyinfo->nDomChecks = ntups;
4897         tyinfo->domChecks = constrinfo;
4898
4899         for (i = 0; i < ntups; i++)
4900         {
4901                 bool    validated = PQgetvalue(res, i, 4)[0] == 't';
4902
4903                 constrinfo[i].dobj.objType = DO_CONSTRAINT;
4904                 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4905                 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4906                 AssignDumpId(&constrinfo[i].dobj);
4907                 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
4908                 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
4909                 constrinfo[i].contable = NULL;
4910                 constrinfo[i].condomain = tyinfo;
4911                 constrinfo[i].contype = 'c';
4912                 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
4913                 constrinfo[i].confrelid = InvalidOid;
4914                 constrinfo[i].conindex = 0;
4915                 constrinfo[i].condeferrable = false;
4916                 constrinfo[i].condeferred = false;
4917                 constrinfo[i].conislocal = true;
4918
4919                 constrinfo[i].separate = !validated;
4920
4921                 /*
4922                  * Make the domain depend on the constraint, ensuring it won't be
4923                  * output till any constraint dependencies are OK.  If the constraint
4924                  * has not been validated, it's going to be dumped after the domain
4925                  * anyway, so this doesn't matter.
4926                  */
4927                 if (validated)
4928                         addObjectDependency(&tyinfo->dobj,
4929                                                                 constrinfo[i].dobj.dumpId);
4930         }
4931
4932         PQclear(res);
4933
4934         destroyPQExpBuffer(query);
4935 }
4936
4937 /*
4938  * getRules
4939  *        get basic information about every rule in the system
4940  *
4941  * numRules is set to the number of rules read in
4942  */
4943 RuleInfo *
4944 getRules(Archive *fout, int *numRules)
4945 {
4946         PGresult   *res;
4947         int                     ntups;
4948         int                     i;
4949         PQExpBuffer query = createPQExpBuffer();
4950         RuleInfo   *ruleinfo;
4951         int                     i_tableoid;
4952         int                     i_oid;
4953         int                     i_rulename;
4954         int                     i_ruletable;
4955         int                     i_ev_type;
4956         int                     i_is_instead;
4957         int                     i_ev_enabled;
4958
4959         /* Make sure we are in proper schema */
4960         selectSourceSchema(fout, "pg_catalog");
4961
4962         if (fout->remoteVersion >= 80300)
4963         {
4964                 appendPQExpBuffer(query, "SELECT "
4965                                                   "tableoid, oid, rulename, "
4966                                                   "ev_class AS ruletable, ev_type, is_instead, "
4967                                                   "ev_enabled "
4968                                                   "FROM pg_rewrite "
4969                                                   "ORDER BY oid");
4970         }
4971         else if (fout->remoteVersion >= 70100)
4972         {
4973                 appendPQExpBuffer(query, "SELECT "
4974                                                   "tableoid, oid, rulename, "
4975                                                   "ev_class AS ruletable, ev_type, is_instead, "
4976                                                   "'O'::char AS ev_enabled "
4977                                                   "FROM pg_rewrite "
4978                                                   "ORDER BY oid");
4979         }
4980         else
4981         {
4982                 appendPQExpBuffer(query, "SELECT "
4983                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
4984                                                   "oid, rulename, "
4985                                                   "ev_class AS ruletable, ev_type, is_instead, "
4986                                                   "'O'::char AS ev_enabled "
4987                                                   "FROM pg_rewrite "
4988                                                   "ORDER BY oid");
4989         }
4990
4991         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4992
4993         ntups = PQntuples(res);
4994
4995         *numRules = ntups;
4996
4997         ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
4998
4999         i_tableoid = PQfnumber(res, "tableoid");
5000         i_oid = PQfnumber(res, "oid");
5001         i_rulename = PQfnumber(res, "rulename");
5002         i_ruletable = PQfnumber(res, "ruletable");
5003         i_ev_type = PQfnumber(res, "ev_type");
5004         i_is_instead = PQfnumber(res, "is_instead");
5005         i_ev_enabled = PQfnumber(res, "ev_enabled");
5006
5007         for (i = 0; i < ntups; i++)
5008         {
5009                 Oid                     ruletableoid;
5010
5011                 ruleinfo[i].dobj.objType = DO_RULE;
5012                 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5013                 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5014                 AssignDumpId(&ruleinfo[i].dobj);
5015                 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5016                 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5017                 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5018                 if (ruleinfo[i].ruletable == NULL)
5019                         exit_horribly(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5020                                                   ruletableoid, ruleinfo[i].dobj.catId.oid);
5021                 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5022                 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5023                 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5024                 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5025                 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5026                 if (ruleinfo[i].ruletable)
5027                 {
5028                         /*
5029                          * If the table is a view, force its ON SELECT rule to be sorted
5030                          * before the view itself --- this ensures that any dependencies
5031                          * for the rule affect the table's positioning. Other rules are
5032                          * forced to appear after their table.
5033                          */
5034                         if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
5035                                 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5036                         {
5037                                 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5038                                                                         ruleinfo[i].dobj.dumpId);
5039                                 /* We'll merge the rule into CREATE VIEW, if possible */
5040                                 ruleinfo[i].separate = false;
5041                         }
5042                         else
5043                         {
5044                                 addObjectDependency(&ruleinfo[i].dobj,
5045                                                                         ruleinfo[i].ruletable->dobj.dumpId);
5046                                 ruleinfo[i].separate = true;
5047                         }
5048                 }
5049                 else
5050                         ruleinfo[i].separate = true;
5051         }
5052
5053         PQclear(res);
5054
5055         destroyPQExpBuffer(query);
5056
5057         return ruleinfo;
5058 }
5059
5060 /*
5061  * getTriggers
5062  *        get information about every trigger on a dumpable table
5063  *
5064  * Note: trigger data is not returned directly to the caller, but it
5065  * does get entered into the DumpableObject tables.
5066  */
5067 void
5068 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5069 {
5070         int                     i,
5071                                 j;
5072         PQExpBuffer query = createPQExpBuffer();
5073         PGresult   *res;
5074         TriggerInfo *tginfo;
5075         int                     i_tableoid,
5076                                 i_oid,
5077                                 i_tgname,
5078                                 i_tgfname,
5079                                 i_tgtype,
5080                                 i_tgnargs,
5081                                 i_tgargs,
5082                                 i_tgisconstraint,
5083                                 i_tgconstrname,
5084                                 i_tgconstrrelid,
5085                                 i_tgconstrrelname,
5086                                 i_tgenabled,
5087                                 i_tgdeferrable,
5088                                 i_tginitdeferred,
5089                                 i_tgdef;
5090         int                     ntups;
5091
5092         for (i = 0; i < numTables; i++)
5093         {
5094                 TableInfo  *tbinfo = &tblinfo[i];
5095
5096                 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5097                         continue;
5098
5099                 if (g_verbose)
5100                         write_msg(NULL, "reading triggers for table \"%s\"\n",
5101                                           tbinfo->dobj.name);
5102
5103                 /*
5104                  * select table schema to ensure regproc name is qualified if needed
5105                  */
5106                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5107
5108                 resetPQExpBuffer(query);
5109                 if (fout->remoteVersion >= 90000)
5110                 {
5111                         /*
5112                          * NB: think not to use pretty=true in pg_get_triggerdef.  It
5113                          * could result in non-forward-compatible dumps of WHEN clauses
5114                          * due to under-parenthesization.
5115                          */
5116                         appendPQExpBuffer(query,
5117                                                           "SELECT tgname, "
5118                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5119                                                 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5120                                                           "tgenabled, tableoid, oid "
5121                                                           "FROM pg_catalog.pg_trigger t "
5122                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5123                                                           "AND NOT tgisinternal",
5124                                                           tbinfo->dobj.catId.oid);
5125                 }
5126                 else if (fout->remoteVersion >= 80300)
5127                 {
5128                         /*
5129                          * We ignore triggers that are tied to a foreign-key constraint
5130                          */
5131                         appendPQExpBuffer(query,
5132                                                           "SELECT tgname, "
5133                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5134                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5135                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5136                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5137                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5138                                                           "FROM pg_catalog.pg_trigger t "
5139                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5140                                                           "AND tgconstraint = 0",
5141                                                           tbinfo->dobj.catId.oid);
5142                 }
5143                 else if (fout->remoteVersion >= 70300)
5144                 {
5145                         /*
5146                          * We ignore triggers that are tied to a foreign-key constraint,
5147                          * but in these versions we have to grovel through pg_constraint
5148                          * to find out
5149                          */
5150                         appendPQExpBuffer(query,
5151                                                           "SELECT tgname, "
5152                                                           "tgfoid::pg_catalog.regproc AS tgfname, "
5153                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5154                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5155                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5156                                          "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5157                                                           "FROM pg_catalog.pg_trigger t "
5158                                                           "WHERE tgrelid = '%u'::pg_catalog.oid "
5159                                                           "AND (NOT tgisconstraint "
5160                                                           " OR NOT EXISTS"
5161                                                           "  (SELECT 1 FROM pg_catalog.pg_depend d "
5162                                                           "   JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5163                                                           "   WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5164                                                           tbinfo->dobj.catId.oid);
5165                 }
5166                 else if (fout->remoteVersion >= 70100)
5167                 {
5168                         appendPQExpBuffer(query,
5169                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5170                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5171                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5172                                                           "tgconstrrelid, tginitdeferred, tableoid, oid, "
5173                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5174                                                           "             AS tgconstrrelname "
5175                                                           "FROM pg_trigger "
5176                                                           "WHERE tgrelid = '%u'::oid",
5177                                                           tbinfo->dobj.catId.oid);
5178                 }
5179                 else
5180                 {
5181                         appendPQExpBuffer(query,
5182                                                           "SELECT tgname, tgfoid::regproc AS tgfname, "
5183                                                           "tgtype, tgnargs, tgargs, tgenabled, "
5184                                                           "tgisconstraint, tgconstrname, tgdeferrable, "
5185                                                           "tgconstrrelid, tginitdeferred, "
5186                                                           "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5187                                                           "oid, "
5188                                   "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5189                                                           "             AS tgconstrrelname "
5190                                                           "FROM pg_trigger "
5191                                                           "WHERE tgrelid = '%u'::oid",
5192                                                           tbinfo->dobj.catId.oid);
5193                 }
5194                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5195
5196                 ntups = PQntuples(res);
5197
5198                 i_tableoid = PQfnumber(res, "tableoid");
5199                 i_oid = PQfnumber(res, "oid");
5200                 i_tgname = PQfnumber(res, "tgname");
5201                 i_tgfname = PQfnumber(res, "tgfname");
5202                 i_tgtype = PQfnumber(res, "tgtype");
5203                 i_tgnargs = PQfnumber(res, "tgnargs");
5204                 i_tgargs = PQfnumber(res, "tgargs");
5205                 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5206                 i_tgconstrname = PQfnumber(res, "tgconstrname");
5207                 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5208                 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5209                 i_tgenabled = PQfnumber(res, "tgenabled");
5210                 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5211                 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5212                 i_tgdef = PQfnumber(res, "tgdef");
5213
5214                 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5215
5216                 for (j = 0; j < ntups; j++)
5217                 {
5218                         tginfo[j].dobj.objType = DO_TRIGGER;
5219                         tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5220                         tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5221                         AssignDumpId(&tginfo[j].dobj);
5222                         tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5223                         tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5224                         tginfo[j].tgtable = tbinfo;
5225                         tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5226                         if (i_tgdef >= 0)
5227                         {
5228                                 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5229
5230                                 /* remaining fields are not valid if we have tgdef */
5231                                 tginfo[j].tgfname = NULL;
5232                                 tginfo[j].tgtype = 0;
5233                                 tginfo[j].tgnargs = 0;
5234                                 tginfo[j].tgargs = NULL;
5235                                 tginfo[j].tgisconstraint = false;
5236                                 tginfo[j].tgdeferrable = false;
5237                                 tginfo[j].tginitdeferred = false;
5238                                 tginfo[j].tgconstrname = NULL;
5239                                 tginfo[j].tgconstrrelid = InvalidOid;
5240                                 tginfo[j].tgconstrrelname = NULL;
5241                         }
5242                         else
5243                         {
5244                                 tginfo[j].tgdef = NULL;
5245
5246                                 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5247                                 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5248                                 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5249                                 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5250                                 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5251                                 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5252                                 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5253
5254                                 if (tginfo[j].tgisconstraint)
5255                                 {
5256                                         tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5257                                         tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5258                                         if (OidIsValid(tginfo[j].tgconstrrelid))
5259                                         {
5260                                                 if (PQgetisnull(res, j, i_tgconstrrelname))
5261                                                         exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5262                                                                                   tginfo[j].dobj.name,
5263                                                                                   tbinfo->dobj.name,
5264                                                                                   tginfo[j].tgconstrrelid);
5265                                                 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5266                                         }
5267                                         else
5268                                                 tginfo[j].tgconstrrelname = NULL;
5269                                 }
5270                                 else
5271                                 {
5272                                         tginfo[j].tgconstrname = NULL;
5273                                         tginfo[j].tgconstrrelid = InvalidOid;
5274                                         tginfo[j].tgconstrrelname = NULL;
5275                                 }
5276                         }
5277                 }
5278
5279                 PQclear(res);
5280         }
5281
5282         destroyPQExpBuffer(query);
5283 }
5284
5285 /*
5286  * getProcLangs
5287  *        get basic information about every procedural language in the system
5288  *
5289  * numProcLangs is set to the number of langs read in
5290  *
5291  * NB: this must run after getFuncs() because we assume we can do
5292  * findFuncByOid().
5293  */
5294 ProcLangInfo *
5295 getProcLangs(Archive *fout, int *numProcLangs)
5296 {
5297         PGresult   *res;
5298         int                     ntups;
5299         int                     i;
5300         PQExpBuffer query = createPQExpBuffer();
5301         ProcLangInfo *planginfo;
5302         int                     i_tableoid;
5303         int                     i_oid;
5304         int                     i_lanname;
5305         int                     i_lanpltrusted;
5306         int                     i_lanplcallfoid;
5307         int                     i_laninline;
5308         int                     i_lanvalidator;
5309         int                     i_lanacl;
5310         int                     i_lanowner;
5311
5312         /* Make sure we are in proper schema */
5313         selectSourceSchema(fout, "pg_catalog");
5314
5315         if (fout->remoteVersion >= 90000)
5316         {
5317                 /* pg_language has a laninline column */
5318                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5319                                                   "lanname, lanpltrusted, lanplcallfoid, "
5320                                                   "laninline, lanvalidator,  lanacl, "
5321                                                   "(%s lanowner) AS lanowner "
5322                                                   "FROM pg_language "
5323                                                   "WHERE lanispl "
5324                                                   "ORDER BY oid",
5325                                                   username_subquery);
5326         }
5327         else if (fout->remoteVersion >= 80300)
5328         {
5329                 /* pg_language has a lanowner column */
5330                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5331                                                   "lanname, lanpltrusted, lanplcallfoid, "
5332                                                   "lanvalidator,  lanacl, "
5333                                                   "(%s lanowner) AS lanowner "
5334                                                   "FROM pg_language "
5335                                                   "WHERE lanispl "
5336                                                   "ORDER BY oid",
5337                                                   username_subquery);
5338         }
5339         else if (fout->remoteVersion >= 80100)
5340         {
5341                 /* Languages are owned by the bootstrap superuser, OID 10 */
5342                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5343                                                   "(%s '10') AS lanowner "
5344                                                   "FROM pg_language "
5345                                                   "WHERE lanispl "
5346                                                   "ORDER BY oid",
5347                                                   username_subquery);
5348         }
5349         else if (fout->remoteVersion >= 70400)
5350         {
5351                 /* Languages are owned by the bootstrap superuser, sysid 1 */
5352                 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5353                                                   "(%s '1') AS lanowner "
5354                                                   "FROM pg_language "
5355                                                   "WHERE lanispl "
5356                                                   "ORDER BY oid",
5357                                                   username_subquery);
5358         }
5359         else if (fout->remoteVersion >= 70100)
5360         {
5361                 /* No clear notion of an owner at all before 7.4 ... */
5362                 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5363                                                   "WHERE lanispl "
5364                                                   "ORDER BY oid");
5365         }
5366         else
5367         {
5368                 appendPQExpBuffer(query, "SELECT "
5369                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5370                                                   "oid, * FROM pg_language "
5371                                                   "WHERE lanispl "
5372                                                   "ORDER BY oid");
5373         }
5374
5375         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5376
5377         ntups = PQntuples(res);
5378
5379         *numProcLangs = ntups;
5380
5381         planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5382
5383         i_tableoid = PQfnumber(res, "tableoid");
5384         i_oid = PQfnumber(res, "oid");
5385         i_lanname = PQfnumber(res, "lanname");
5386         i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5387         i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5388         /* these may fail and return -1: */
5389         i_laninline = PQfnumber(res, "laninline");
5390         i_lanvalidator = PQfnumber(res, "lanvalidator");
5391         i_lanacl = PQfnumber(res, "lanacl");
5392         i_lanowner = PQfnumber(res, "lanowner");
5393
5394         for (i = 0; i < ntups; i++)
5395         {
5396                 planginfo[i].dobj.objType = DO_PROCLANG;
5397                 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5398                 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5399                 AssignDumpId(&planginfo[i].dobj);
5400
5401                 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5402                 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5403                 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5404                 if (i_laninline >= 0)
5405                         planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5406                 else
5407                         planginfo[i].laninline = InvalidOid;
5408                 if (i_lanvalidator >= 0)
5409                         planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5410                 else
5411                         planginfo[i].lanvalidator = InvalidOid;
5412                 if (i_lanacl >= 0)
5413                         planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5414                 else
5415                         planginfo[i].lanacl = pg_strdup("{=U}");
5416                 if (i_lanowner >= 0)
5417                         planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5418                 else
5419                         planginfo[i].lanowner = pg_strdup("");
5420
5421                 if (fout->remoteVersion < 70300)
5422                 {
5423                         /*
5424                          * We need to make a dependency to ensure the function will be
5425                          * dumped first.  (In 7.3 and later the regular dependency
5426                          * mechanism will handle this for us.)
5427                          */
5428                         FuncInfo   *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5429
5430                         if (funcInfo)
5431                                 addObjectDependency(&planginfo[i].dobj,
5432                                                                         funcInfo->dobj.dumpId);
5433                 }
5434         }
5435
5436         PQclear(res);
5437
5438         destroyPQExpBuffer(query);
5439
5440         return planginfo;
5441 }
5442
5443 /*
5444  * getCasts
5445  *        get basic information about every cast in the system
5446  *
5447  * numCasts is set to the number of casts read in
5448  */
5449 CastInfo *
5450 getCasts(Archive *fout, int *numCasts)
5451 {
5452         PGresult   *res;
5453         int                     ntups;
5454         int                     i;
5455         PQExpBuffer query = createPQExpBuffer();
5456         CastInfo   *castinfo;
5457         int                     i_tableoid;
5458         int                     i_oid;
5459         int                     i_castsource;
5460         int                     i_casttarget;
5461         int                     i_castfunc;
5462         int                     i_castcontext;
5463         int                     i_castmethod;
5464
5465         /* Make sure we are in proper schema */
5466         selectSourceSchema(fout, "pg_catalog");
5467
5468         if (fout->remoteVersion >= 80400)
5469         {
5470                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5471                                                   "castsource, casttarget, castfunc, castcontext, "
5472                                                   "castmethod "
5473                                                   "FROM pg_cast ORDER BY 3,4");
5474         }
5475         else if (fout->remoteVersion >= 70300)
5476         {
5477                 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5478                                                   "castsource, casttarget, castfunc, castcontext, "
5479                                 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
5480                                                   "FROM pg_cast ORDER BY 3,4");
5481         }
5482         else
5483         {
5484                 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
5485                                                   "t1.oid AS castsource, t2.oid AS casttarget, "
5486                                                   "p.oid AS castfunc, 'e' AS castcontext, "
5487                                                   "'f' AS castmethod "
5488                                                   "FROM pg_type t1, pg_type t2, pg_proc p "
5489                                                   "WHERE p.pronargs = 1 AND "
5490                                                   "p.proargtypes[0] = t1.oid AND "
5491                                                   "p.prorettype = t2.oid AND p.proname = t2.typname "
5492                                                   "ORDER BY 3,4");
5493         }
5494
5495         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5496
5497         ntups = PQntuples(res);
5498
5499         *numCasts = ntups;
5500
5501         castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
5502
5503         i_tableoid = PQfnumber(res, "tableoid");
5504         i_oid = PQfnumber(res, "oid");
5505         i_castsource = PQfnumber(res, "castsource");
5506         i_casttarget = PQfnumber(res, "casttarget");
5507         i_castfunc = PQfnumber(res, "castfunc");
5508         i_castcontext = PQfnumber(res, "castcontext");
5509         i_castmethod = PQfnumber(res, "castmethod");
5510
5511         for (i = 0; i < ntups; i++)
5512         {
5513                 PQExpBufferData namebuf;
5514                 TypeInfo   *sTypeInfo;
5515                 TypeInfo   *tTypeInfo;
5516
5517                 castinfo[i].dobj.objType = DO_CAST;
5518                 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5519                 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5520                 AssignDumpId(&castinfo[i].dobj);
5521                 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5522                 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5523                 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5524                 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5525                 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5526
5527                 /*
5528                  * Try to name cast as concatenation of typnames.  This is only used
5529                  * for purposes of sorting.  If we fail to find either type, the name
5530                  * will be an empty string.
5531                  */
5532                 initPQExpBuffer(&namebuf);
5533                 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5534                 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5535                 if (sTypeInfo && tTypeInfo)
5536                         appendPQExpBuffer(&namebuf, "%s %s",
5537                                                           sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5538                 castinfo[i].dobj.name = namebuf.data;
5539
5540                 if (OidIsValid(castinfo[i].castfunc))
5541                 {
5542                         /*
5543                          * We need to make a dependency to ensure the function will be
5544                          * dumped first.  (In 7.3 and later the regular dependency
5545                          * mechanism will handle this for us.)
5546                          */
5547                         FuncInfo   *funcInfo;
5548
5549                         funcInfo = findFuncByOid(castinfo[i].castfunc);
5550                         if (funcInfo)
5551                                 addObjectDependency(&castinfo[i].dobj,
5552                                                                         funcInfo->dobj.dumpId);
5553                 }
5554         }
5555
5556         PQclear(res);
5557
5558         destroyPQExpBuffer(query);
5559
5560         return castinfo;
5561 }
5562
5563 /*
5564  * getTableAttrs -
5565  *        for each interesting table, read info about its attributes
5566  *        (names, types, default values, CHECK constraints, etc)
5567  *
5568  * This is implemented in a very inefficient way right now, looping
5569  * through the tblinfo and doing a join per table to find the attrs and their
5570  * types.  However, because we want type names and so forth to be named
5571  * relative to the schema of each table, we couldn't do it in just one
5572  * query.  (Maybe one query per schema?)
5573  *
5574  *      modifies tblinfo
5575  */
5576 void
5577 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
5578 {
5579         int                     i,
5580                                 j;
5581         PQExpBuffer q = createPQExpBuffer();
5582         int                     i_attnum;
5583         int                     i_attname;
5584         int                     i_atttypname;
5585         int                     i_atttypmod;
5586         int                     i_attstattarget;
5587         int                     i_attstorage;
5588         int                     i_typstorage;
5589         int                     i_attnotnull;
5590         int                     i_atthasdef;
5591         int                     i_attisdropped;
5592         int                     i_attlen;
5593         int                     i_attalign;
5594         int                     i_attislocal;
5595         int                     i_attoptions;
5596         int                     i_attcollation;
5597         int                     i_attfdwoptions;
5598         PGresult   *res;
5599         int                     ntups;
5600         bool            hasdefaults;
5601
5602         for (i = 0; i < numTables; i++)
5603         {
5604                 TableInfo  *tbinfo = &tblinfo[i];
5605
5606                 /* Don't bother to collect info for sequences */
5607                 if (tbinfo->relkind == RELKIND_SEQUENCE)
5608                         continue;
5609
5610                 /* Don't bother with uninteresting tables, either */
5611                 if (!tbinfo->interesting)
5612                         continue;
5613
5614                 /*
5615                  * Make sure we are in proper schema for this table; this allows
5616                  * correct retrieval of formatted type names and default exprs
5617                  */
5618                 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5619
5620                 /* find all the user attributes and their types */
5621
5622                 /*
5623                  * we must read the attribute names in attribute number order! because
5624                  * we will use the attnum to index into the attnames array later.  We
5625                  * actually ask to order by "attrelid, attnum" because (at least up to
5626                  * 7.3) the planner is not smart enough to realize it needn't re-sort
5627                  * the output of an indexscan on pg_attribute_relid_attnum_index.
5628                  */
5629                 if (g_verbose)
5630                         write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5631                                           tbinfo->dobj.name);
5632
5633                 resetPQExpBuffer(q);
5634
5635                 if (fout->remoteVersion >= 90200)
5636                 {
5637                         /*
5638                          * attfdwoptions is new in 9.2.
5639                          */
5640                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5641                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5642                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5643                                                           "a.attlen, a.attalign, a.attislocal, "
5644                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5645                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5646                                                           "CASE WHEN a.attcollation <> t.typcollation "
5647                                                         "THEN a.attcollation ELSE 0 END AS attcollation, "
5648                                                           "pg_catalog.array_to_string(ARRAY("
5649                                                           "SELECT pg_catalog.quote_ident(option_name) || "
5650                                                           "' ' || pg_catalog.quote_literal(option_value) "
5651                                                           "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
5652                                                           "ORDER BY option_name"
5653                                                           "), E',\n    ') AS attfdwoptions "
5654                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5655                                                           "ON a.atttypid = t.oid "
5656                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5657                                                           "AND a.attnum > 0::pg_catalog.int2 "
5658                                                           "ORDER BY a.attrelid, a.attnum",
5659                                                           tbinfo->dobj.catId.oid);
5660                 }
5661                 else if (fout->remoteVersion >= 90100)
5662                 {
5663                         /*
5664                          * attcollation is new in 9.1.  Since we only want to dump COLLATE
5665                          * clauses for attributes whose collation is different from their
5666                          * type's default, we use a CASE here to suppress uninteresting
5667                          * attcollations cheaply.
5668                          */
5669                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5670                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5671                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5672                                                           "a.attlen, a.attalign, a.attislocal, "
5673                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5674                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5675                                                           "CASE WHEN a.attcollation <> t.typcollation "
5676                                                         "THEN a.attcollation ELSE 0 END AS attcollation, "
5677                                                           "NULL AS attfdwoptions "
5678                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5679                                                           "ON a.atttypid = t.oid "
5680                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5681                                                           "AND a.attnum > 0::pg_catalog.int2 "
5682                                                           "ORDER BY a.attrelid, a.attnum",
5683                                                           tbinfo->dobj.catId.oid);
5684                 }
5685                 else if (fout->remoteVersion >= 90000)
5686                 {
5687                         /* attoptions is new in 9.0 */
5688                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5689                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5690                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5691                                                           "a.attlen, a.attalign, a.attislocal, "
5692                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5693                                                 "array_to_string(a.attoptions, ', ') AS attoptions, "
5694                                                           "0 AS attcollation, "
5695                                                           "NULL AS attfdwoptions "
5696                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5697                                                           "ON a.atttypid = t.oid "
5698                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5699                                                           "AND a.attnum > 0::pg_catalog.int2 "
5700                                                           "ORDER BY a.attrelid, a.attnum",
5701                                                           tbinfo->dobj.catId.oid);
5702                 }
5703                 else if (fout->remoteVersion >= 70300)
5704                 {
5705                         /* need left join here to not fail on dropped columns ... */
5706                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5707                                                           "a.attstattarget, a.attstorage, t.typstorage, "
5708                                                           "a.attnotnull, a.atthasdef, a.attisdropped, "
5709                                                           "a.attlen, a.attalign, a.attislocal, "
5710                                   "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5711                                                           "'' AS attoptions, 0 AS attcollation, "
5712                                                           "NULL AS attfdwoptions "
5713                          "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5714                                                           "ON a.atttypid = t.oid "
5715                                                           "WHERE a.attrelid = '%u'::pg_catalog.oid "
5716                                                           "AND a.attnum > 0::pg_catalog.int2 "
5717                                                           "ORDER BY a.attrelid, a.attnum",
5718                                                           tbinfo->dobj.catId.oid);
5719                 }
5720                 else if (fout->remoteVersion >= 70100)
5721                 {
5722                         /*
5723                          * attstattarget doesn't exist in 7.1.  It does exist in 7.2, but
5724                          * we don't dump it because we can't tell whether it's been
5725                          * explicitly set or was just a default.
5726                          *
5727                          * attislocal doesn't exist before 7.3, either; in older databases
5728                          * we assume it's TRUE, else we'd fail to dump non-inherited atts.
5729                          */
5730                         appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5731                                                           "-1 AS attstattarget, a.attstorage, "
5732                                                           "t.typstorage, a.attnotnull, a.atthasdef, "
5733                                                           "false AS attisdropped, a.attlen, "
5734                                                           "a.attalign, true AS attislocal, "
5735                                                           "format_type(t.oid,a.atttypmod) AS atttypname, "
5736                                                           "'' AS attoptions, 0 AS attcollation, "
5737                                                           "NULL AS attfdwoptions "
5738                                                           "FROM pg_attribute a LEFT JOIN pg_type t "
5739                                                           "ON a.atttypid = t.oid "
5740                                                           "WHERE a.attrelid = '%u'::oid "
5741                                                           "AND a.attnum > 0::int2 "
5742                                                           "ORDER BY a.attrelid, a.attnum",
5743                                                           tbinfo->dobj.catId.oid);
5744                 }
5745                 else
5746                 {
5747                         /* format_type not available before 7.1 */
5748                         appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
5749                                                           "-1 AS attstattarget, "
5750                                                           "attstorage, attstorage AS typstorage, "
5751                                                           "attnotnull, atthasdef, false AS attisdropped, "
5752                                                           "attlen, attalign, "
5753                                                           "true AS attislocal, "
5754                                                           "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
5755                                                           "'' AS attoptions, 0 AS attcollation, "
5756                                                           "NULL AS attfdwoptions "
5757                                                           "FROM pg_attribute a "
5758                                                           "WHERE attrelid = '%u'::oid "
5759                                                           "AND attnum > 0::int2 "
5760                                                           "ORDER BY attrelid, attnum",
5761                                                           tbinfo->dobj.catId.oid);
5762                 }
5763
5764                 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5765
5766                 ntups = PQntuples(res);
5767
5768                 i_attnum = PQfnumber(res, "attnum");
5769                 i_attname = PQfnumber(res, "attname");
5770                 i_atttypname = PQfnumber(res, "atttypname");
5771                 i_atttypmod = PQfnumber(res, "atttypmod");
5772                 i_attstattarget = PQfnumber(res, "attstattarget");
5773                 i_attstorage = PQfnumber(res, "attstorage");
5774                 i_typstorage = PQfnumber(res, "typstorage");
5775                 i_attnotnull = PQfnumber(res, "attnotnull");
5776                 i_atthasdef = PQfnumber(res, "atthasdef");
5777                 i_attisdropped = PQfnumber(res, "attisdropped");
5778                 i_attlen = PQfnumber(res, "attlen");
5779                 i_attalign = PQfnumber(res, "attalign");
5780                 i_attislocal = PQfnumber(res, "attislocal");
5781                 i_attoptions = PQfnumber(res, "attoptions");
5782                 i_attcollation = PQfnumber(res, "attcollation");
5783                 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
5784
5785                 tbinfo->numatts = ntups;
5786                 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
5787                 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
5788                 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
5789                 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
5790                 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
5791                 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
5792                 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
5793                 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
5794                 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
5795                 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
5796                 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
5797                 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
5798                 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
5799                 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
5800                 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
5801                 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
5802                 hasdefaults = false;
5803
5804                 for (j = 0; j < ntups; j++)
5805                 {
5806                         if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
5807                                 exit_horribly(NULL,
5808                                                           "invalid column numbering in table \"%s\"\n",
5809                                                           tbinfo->dobj.name);
5810                         tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
5811                         tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
5812                         tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
5813                         tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
5814                         tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
5815                         tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
5816                         tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
5817                         tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
5818                         tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
5819                         tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
5820                         tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
5821                         tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
5822                         tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
5823                         tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
5824                         tbinfo->attrdefs[j] = NULL; /* fix below */
5825                         if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
5826                                 hasdefaults = true;
5827                         /* these flags will be set in flagInhAttrs() */
5828                         tbinfo->inhNotNull[j] = false;
5829                 }
5830
5831                 PQclear(res);
5832
5833                 /*
5834                  * Get info about column defaults
5835                  */
5836                 if (hasdefaults)
5837                 {
5838                         AttrDefInfo *attrdefs;
5839                         int                     numDefaults;
5840
5841                         if (g_verbose)
5842                                 write_msg(NULL, "finding default expressions of table \"%s\"\n",
5843                                                   tbinfo->dobj.name);
5844
5845                         resetPQExpBuffer(q);
5846                         if (fout->remoteVersion >= 70300)
5847                         {
5848                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
5849                                                    "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
5850                                                                   "FROM pg_catalog.pg_attrdef "
5851                                                                   "WHERE adrelid = '%u'::pg_catalog.oid",
5852                                                                   tbinfo->dobj.catId.oid);
5853                         }
5854                         else if (fout->remoteVersion >= 70200)
5855                         {
5856                                 /* 7.2 did not have OIDs in pg_attrdef */
5857                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
5858                                                                   "pg_get_expr(adbin, adrelid) AS adsrc "
5859                                                                   "FROM pg_attrdef "
5860                                                                   "WHERE adrelid = '%u'::oid",
5861                                                                   tbinfo->dobj.catId.oid);
5862                         }
5863                         else if (fout->remoteVersion >= 70100)
5864                         {
5865                                 /* no pg_get_expr, so must rely on adsrc */
5866                                 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
5867                                                                   "FROM pg_attrdef "
5868                                                                   "WHERE adrelid = '%u'::oid",
5869                                                                   tbinfo->dobj.catId.oid);
5870                         }
5871                         else
5872                         {
5873                                 /* no pg_get_expr, no tableoid either */
5874                                 appendPQExpBuffer(q, "SELECT "
5875                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
5876                                                                   "oid, adnum, adsrc "
5877                                                                   "FROM pg_attrdef "
5878                                                                   "WHERE adrelid = '%u'::oid",
5879                                                                   tbinfo->dobj.catId.oid);
5880                         }
5881                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5882
5883                         numDefaults = PQntuples(res);
5884                         attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
5885
5886                         for (j = 0; j < numDefaults; j++)
5887                         {
5888                                 int                     adnum;
5889
5890                                 adnum = atoi(PQgetvalue(res, j, 2));
5891
5892                                 if (adnum <= 0 || adnum > ntups)
5893                                         exit_horribly(NULL,
5894                                                                   "invalid adnum value %d for table \"%s\"\n",
5895                                                                   adnum, tbinfo->dobj.name);
5896
5897                                 /*
5898                                  * dropped columns shouldn't have defaults, but just in case,
5899                                  * ignore 'em
5900                                  */
5901                                 if (tbinfo->attisdropped[adnum - 1])
5902                                         continue;
5903
5904                                 attrdefs[j].dobj.objType = DO_ATTRDEF;
5905                                 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
5906                                 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
5907                                 AssignDumpId(&attrdefs[j].dobj);
5908                                 attrdefs[j].adtable = tbinfo;
5909                                 attrdefs[j].adnum = adnum;
5910                                 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
5911
5912                                 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
5913                                 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
5914
5915                                 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
5916
5917                                 /*
5918                                  * Defaults on a VIEW must always be dumped as separate ALTER
5919                                  * TABLE commands.      Defaults on regular tables are dumped as
5920                                  * part of the CREATE TABLE if possible, which it won't be
5921                                  * if the column is not going to be emitted explicitly.
5922                                  */
5923                                 if (tbinfo->relkind == RELKIND_VIEW)
5924                                 {
5925                                         attrdefs[j].separate = true;
5926                                         /* needed in case pre-7.3 DB: */
5927                                         addObjectDependency(&attrdefs[j].dobj,
5928                                                                                 tbinfo->dobj.dumpId);
5929                                 }
5930                                 else if (!shouldPrintColumn(tbinfo, adnum - 1))
5931                                 {
5932                                         /* column will be suppressed, print default separately */
5933                                         attrdefs[j].separate = true;
5934                                         /* needed in case pre-7.3 DB: */
5935                                         addObjectDependency(&attrdefs[j].dobj,
5936                                                                                 tbinfo->dobj.dumpId);
5937                                 }
5938                                 else
5939                                 {
5940                                         attrdefs[j].separate = false;
5941                                         /*
5942                                          * Mark the default as needing to appear before the table,
5943                                          * so that any dependencies it has must be emitted before
5944                                          * the CREATE TABLE.  If this is not possible, we'll
5945                                          * change to "separate" mode while sorting dependencies.
5946                                          */
5947                                         addObjectDependency(&tbinfo->dobj,
5948                                                                                 attrdefs[j].dobj.dumpId);
5949                                 }
5950
5951                                 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
5952                         }
5953                         PQclear(res);
5954                 }
5955
5956                 /*
5957                  * Get info about table CHECK constraints
5958                  */
5959                 if (tbinfo->ncheck > 0)
5960                 {
5961                         ConstraintInfo *constrs;
5962                         int                     numConstrs;
5963
5964                         if (g_verbose)
5965                                 write_msg(NULL, "finding check constraints for table \"%s\"\n",
5966                                                   tbinfo->dobj.name);
5967
5968                         resetPQExpBuffer(q);
5969                         if (fout->remoteVersion >= 90200)
5970                         {
5971                                 /*
5972                                  * conisonly and convalidated are new in 9.2 (actually, the latter
5973                                  * is there in 9.1, but it wasn't ever false for check constraints
5974                                  * until 9.2).
5975                                  */
5976                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5977                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5978                                                                   "conislocal, convalidated, conisonly "
5979                                                                   "FROM pg_catalog.pg_constraint "
5980                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5981                                                                   "   AND contype = 'c' "
5982                                                                   "ORDER BY conname",
5983                                                                   tbinfo->dobj.catId.oid);
5984                         }
5985                         else if (fout->remoteVersion >= 80400)
5986                         {
5987                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5988                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5989                                                                   "conislocal, true AS convalidated, "
5990                                                                   "false as conisonly "
5991                                                                   "FROM pg_catalog.pg_constraint "
5992                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
5993                                                                   "   AND contype = 'c' "
5994                                                                   "ORDER BY conname",
5995                                                                   tbinfo->dobj.catId.oid);
5996                         }
5997                         else if (fout->remoteVersion >= 70400)
5998                         {
5999                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6000                                                    "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6001                                                                   "true AS conislocal, true AS convalidated, "
6002                                                                   "false as conisonly "
6003                                                                   "FROM pg_catalog.pg_constraint "
6004                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6005                                                                   "   AND contype = 'c' "
6006                                                                   "ORDER BY conname",
6007                                                                   tbinfo->dobj.catId.oid);
6008                         }
6009                         else if (fout->remoteVersion >= 70300)
6010                         {
6011                                 /* no pg_get_constraintdef, must use consrc */
6012                                 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6013                                                                   "'CHECK (' || consrc || ')' AS consrc, "
6014                                                                   "true AS conislocal, true AS convalidated, "
6015                                                                   "false as conisonly "
6016                                                                   "FROM pg_catalog.pg_constraint "
6017                                                                   "WHERE conrelid = '%u'::pg_catalog.oid "
6018                                                                   "   AND contype = 'c' "
6019                                                                   "ORDER BY conname",
6020                                                                   tbinfo->dobj.catId.oid);
6021                         }
6022                         else if (fout->remoteVersion >= 70200)
6023                         {
6024                                 /* 7.2 did not have OIDs in pg_relcheck */
6025                                 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6026                                                                   "rcname AS conname, "
6027                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6028                                                                   "true AS conislocal, true AS convalidated, "
6029                                                                   "false as conisonly "
6030                                                                   "FROM pg_relcheck "
6031                                                                   "WHERE rcrelid = '%u'::oid "
6032                                                                   "ORDER BY rcname",
6033                                                                   tbinfo->dobj.catId.oid);
6034                         }
6035                         else if (fout->remoteVersion >= 70100)
6036                         {
6037                                 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6038                                                                   "rcname AS conname, "
6039                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6040                                                                   "true AS conislocal, true AS convalidated, "
6041                                                                   "false as conisonly "
6042                                                                   "FROM pg_relcheck "
6043                                                                   "WHERE rcrelid = '%u'::oid "
6044                                                                   "ORDER BY rcname",
6045                                                                   tbinfo->dobj.catId.oid);
6046                         }
6047                         else
6048                         {
6049                                 /* no tableoid in 7.0 */
6050                                 appendPQExpBuffer(q, "SELECT "
6051                                                                   "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6052                                                                   "oid, rcname AS conname, "
6053                                                                   "'CHECK (' || rcsrc || ')' AS consrc, "
6054                                                                   "true AS conislocal, true AS convalidated, "
6055                                                                   "false as conisonly "
6056                                                                   "FROM pg_relcheck "
6057                                                                   "WHERE rcrelid = '%u'::oid "
6058                                                                   "ORDER BY rcname",
6059                                                                   tbinfo->dobj.catId.oid);
6060                         }
6061                         res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6062
6063                         numConstrs = PQntuples(res);
6064                         if (numConstrs != tbinfo->ncheck)
6065                         {
6066                                 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6067                                                                                  "expected %d check constraints on table \"%s\" but found %d\n",
6068                                                                                  tbinfo->ncheck),
6069                                                   tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6070                                 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6071                                 exit_nicely(1);
6072                         }
6073
6074                         constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6075                         tbinfo->checkexprs = constrs;
6076
6077                         for (j = 0; j < numConstrs; j++)
6078                         {
6079                                 bool    validated = PQgetvalue(res, j, 5)[0] == 't';
6080                                 bool    isonly = PQgetvalue(res, j, 6)[0] == 't';
6081
6082                                 constrs[j].dobj.objType = DO_CONSTRAINT;
6083                                 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6084                                 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6085                                 AssignDumpId(&constrs[j].dobj);
6086                                 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6087                                 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6088                                 constrs[j].contable = tbinfo;
6089                                 constrs[j].condomain = NULL;
6090                                 constrs[j].contype = 'c';
6091                                 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6092                                 constrs[j].confrelid = InvalidOid;
6093                                 constrs[j].conindex = 0;
6094                                 constrs[j].condeferrable = false;
6095                                 constrs[j].condeferred = false;
6096                                 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6097                                 constrs[j].conisonly = isonly;
6098                                 /*
6099                                  * An unvalidated constraint needs to be dumped separately, so
6100                                  * that potentially-violating existing data is loaded before
6101                                  * the constraint.  An ONLY constraint needs to be dumped
6102                                  * separately too.
6103                                  */
6104                                 constrs[j].separate = !validated || isonly;
6105
6106                                 constrs[j].dobj.dump = tbinfo->dobj.dump;
6107
6108                                 /*
6109                                  * Mark the constraint as needing to appear before the table
6110                                  * --- this is so that any other dependencies of the
6111                                  * constraint will be emitted before we try to create the
6112                                  * table.  If the constraint is to be dumped separately, it will be
6113                                  * dumped after data is loaded anyway, so don't do it.  (There's
6114                                  * an automatic dependency in the opposite direction anyway, so
6115                                  * don't need to add one manually here.)
6116                                  */
6117                                 if (!constrs[j].separate)
6118                                         addObjectDependency(&tbinfo->dobj,
6119                                                                                 constrs[j].dobj.dumpId);
6120
6121                                 /*
6122                                  * If the constraint is inherited, this will be detected later
6123                                  * (in pre-8.4 databases).      We also detect later if the
6124                                  * constraint must be split out from the table definition.
6125                                  */
6126                         }
6127                         PQclear(res);
6128                 }
6129         }
6130
6131         destroyPQExpBuffer(q);
6132 }
6133
6134 /*
6135  * Test whether a column should be printed as part of table's CREATE TABLE.
6136  * Column number is zero-based.
6137  *
6138  * Normally this is always true, but it's false for dropped columns, as well
6139  * as those that were inherited without any local definition.  (If we print
6140  * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6141  * However, in binary_upgrade mode, we must print all such columns anyway and
6142  * fix the attislocal/attisdropped state later, so as to keep control of the
6143  * physical column order.
6144  *
6145  * This function exists because there are scattered nonobvious places that
6146  * must be kept in sync with this decision.
6147  */
6148 bool
6149 shouldPrintColumn(TableInfo *tbinfo, int colno)
6150 {
6151         if (binary_upgrade)
6152                 return true;
6153         return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6154 }
6155
6156
6157 /*
6158  * getTSParsers:
6159  *        read all text search parsers in the system catalogs and return them
6160  *        in the TSParserInfo* structure
6161  *
6162  *      numTSParsers is set to the number of parsers read in
6163  */
6164 TSParserInfo *
6165 getTSParsers(Archive *fout, int *numTSParsers)
6166 {
6167         PGresult   *res;
6168         int                     ntups;
6169         int                     i;
6170         PQExpBuffer query;
6171         TSParserInfo *prsinfo;
6172         int                     i_tableoid;
6173         int                     i_oid;
6174         int                     i_prsname;
6175         int                     i_prsnamespace;
6176         int                     i_prsstart;
6177         int                     i_prstoken;
6178         int                     i_prsend;
6179         int                     i_prsheadline;
6180         int                     i_prslextype;
6181
6182         /* Before 8.3, there is no built-in text search support */
6183         if (fout->remoteVersion < 80300)
6184         {
6185                 *numTSParsers = 0;
6186                 return NULL;
6187         }
6188
6189         query = createPQExpBuffer();
6190
6191         /*
6192          * find all text search objects, including builtin ones; we filter out
6193          * system-defined objects at dump-out time.
6194          */
6195
6196         /* Make sure we are in proper schema */
6197         selectSourceSchema(fout, "pg_catalog");
6198
6199         appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6200                                           "prsstart::oid, prstoken::oid, "
6201                                           "prsend::oid, prsheadline::oid, prslextype::oid "
6202                                           "FROM pg_ts_parser");
6203
6204         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6205
6206         ntups = PQntuples(res);
6207         *numTSParsers = ntups;
6208
6209         prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6210
6211         i_tableoid = PQfnumber(res, "tableoid");
6212         i_oid = PQfnumber(res, "oid");
6213         i_prsname = PQfnumber(res, "prsname");
6214         i_prsnamespace = PQfnumber(res, "prsnamespace");
6215         i_prsstart = PQfnumber(res, "prsstart");
6216         i_prstoken = PQfnumber(res, "prstoken");
6217         i_prsend = PQfnumber(res, "prsend");
6218         i_prsheadline = PQfnumber(res, "prsheadline");
6219         i_prslextype = PQfnumber(res, "prslextype");
6220
6221         for (i = 0; i < ntups; i++)
6222         {
6223                 prsinfo[i].dobj.objType = DO_TSPARSER;
6224                 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6225                 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6226                 AssignDumpId(&prsinfo[i].dobj);
6227                 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6228                 prsinfo[i].dobj.namespace =
6229                         findNamespace(fout,
6230                                                   atooid(PQgetvalue(res, i, i_prsnamespace)),
6231                                                   prsinfo[i].dobj.catId.oid);
6232                 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6233                 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6234                 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6235                 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6236                 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6237
6238                 /* Decide whether we want to dump it */
6239                 selectDumpableObject(&(prsinfo[i].dobj));
6240         }
6241
6242         PQclear(res);
6243
6244         destroyPQExpBuffer(query);
6245
6246         return prsinfo;
6247 }
6248
6249 /*
6250  * getTSDictionaries:
6251  *        read all text search dictionaries in the system catalogs and return them
6252  *        in the TSDictInfo* structure
6253  *
6254  *      numTSDicts is set to the number of dictionaries read in
6255  */
6256 TSDictInfo *
6257 getTSDictionaries(Archive *fout, int *numTSDicts)
6258 {
6259         PGresult   *res;
6260         int                     ntups;
6261         int                     i;
6262         PQExpBuffer query;
6263         TSDictInfo *dictinfo;
6264         int                     i_tableoid;
6265         int                     i_oid;
6266         int                     i_dictname;
6267         int                     i_dictnamespace;
6268         int                     i_rolname;
6269         int                     i_dicttemplate;
6270         int                     i_dictinitoption;
6271
6272         /* Before 8.3, there is no built-in text search support */
6273         if (fout->remoteVersion < 80300)
6274         {
6275                 *numTSDicts = 0;
6276                 return NULL;
6277         }
6278
6279         query = createPQExpBuffer();
6280
6281         /* Make sure we are in proper schema */
6282         selectSourceSchema(fout, "pg_catalog");
6283
6284         appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6285                                           "dictnamespace, (%s dictowner) AS rolname, "
6286                                           "dicttemplate, dictinitoption "
6287                                           "FROM pg_ts_dict",
6288                                           username_subquery);
6289
6290         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6291
6292         ntups = PQntuples(res);
6293         *numTSDicts = ntups;
6294
6295         dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6296
6297         i_tableoid = PQfnumber(res, "tableoid");
6298         i_oid = PQfnumber(res, "oid");
6299         i_dictname = PQfnumber(res, "dictname");
6300         i_dictnamespace = PQfnumber(res, "dictnamespace");
6301         i_rolname = PQfnumber(res, "rolname");
6302         i_dictinitoption = PQfnumber(res, "dictinitoption");
6303         i_dicttemplate = PQfnumber(res, "dicttemplate");
6304
6305         for (i = 0; i < ntups; i++)
6306         {
6307                 dictinfo[i].dobj.objType = DO_TSDICT;
6308                 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6309                 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6310                 AssignDumpId(&dictinfo[i].dobj);
6311                 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6312                 dictinfo[i].dobj.namespace =
6313                         findNamespace(fout,
6314                                                   atooid(PQgetvalue(res, i, i_dictnamespace)),
6315                                                   dictinfo[i].dobj.catId.oid);
6316                 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6317                 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6318                 if (PQgetisnull(res, i, i_dictinitoption))
6319                         dictinfo[i].dictinitoption = NULL;
6320                 else
6321                         dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6322
6323                 /* Decide whether we want to dump it */
6324                 selectDumpableObject(&(dictinfo[i].dobj));
6325         }
6326
6327         PQclear(res);
6328
6329         destroyPQExpBuffer(query);
6330
6331         return dictinfo;
6332 }
6333
6334 /*
6335  * getTSTemplates:
6336  *        read all text search templates in the system catalogs and return them
6337  *        in the TSTemplateInfo* structure
6338  *
6339  *      numTSTemplates is set to the number of templates read in
6340  */
6341 TSTemplateInfo *
6342 getTSTemplates(Archive *fout, int *numTSTemplates)
6343 {
6344         PGresult   *res;
6345         int                     ntups;
6346         int                     i;
6347         PQExpBuffer query;
6348         TSTemplateInfo *tmplinfo;
6349         int                     i_tableoid;
6350         int                     i_oid;
6351         int                     i_tmplname;
6352         int                     i_tmplnamespace;
6353         int                     i_tmplinit;
6354         int                     i_tmpllexize;
6355
6356         /* Before 8.3, there is no built-in text search support */
6357         if (fout->remoteVersion < 80300)
6358         {
6359                 *numTSTemplates = 0;
6360                 return NULL;
6361         }
6362
6363         query = createPQExpBuffer();
6364
6365         /* Make sure we are in proper schema */
6366         selectSourceSchema(fout, "pg_catalog");
6367
6368         appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6369                                           "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6370                                           "FROM pg_ts_template");
6371
6372         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6373
6374         ntups = PQntuples(res);
6375         *numTSTemplates = ntups;
6376
6377         tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6378
6379         i_tableoid = PQfnumber(res, "tableoid");
6380         i_oid = PQfnumber(res, "oid");
6381         i_tmplname = PQfnumber(res, "tmplname");
6382         i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6383         i_tmplinit = PQfnumber(res, "tmplinit");
6384         i_tmpllexize = PQfnumber(res, "tmpllexize");
6385
6386         for (i = 0; i < ntups; i++)
6387         {
6388                 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6389                 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6390                 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6391                 AssignDumpId(&tmplinfo[i].dobj);
6392                 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6393                 tmplinfo[i].dobj.namespace =
6394                         findNamespace(fout,
6395                                                   atooid(PQgetvalue(res, i, i_tmplnamespace)),
6396                                                   tmplinfo[i].dobj.catId.oid);
6397                 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6398                 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6399
6400                 /* Decide whether we want to dump it */
6401                 selectDumpableObject(&(tmplinfo[i].dobj));
6402         }
6403
6404         PQclear(res);
6405
6406         destroyPQExpBuffer(query);
6407
6408         return tmplinfo;
6409 }
6410
6411 /*
6412  * getTSConfigurations:
6413  *        read all text search configurations in the system catalogs and return
6414  *        them in the TSConfigInfo* structure
6415  *
6416  *      numTSConfigs is set to the number of configurations read in
6417  */
6418 TSConfigInfo *
6419 getTSConfigurations(Archive *fout, int *numTSConfigs)
6420 {
6421         PGresult   *res;
6422         int                     ntups;
6423         int                     i;
6424         PQExpBuffer query;
6425         TSConfigInfo *cfginfo;
6426         int                     i_tableoid;
6427         int                     i_oid;
6428         int                     i_cfgname;
6429         int                     i_cfgnamespace;
6430         int                     i_rolname;
6431         int                     i_cfgparser;
6432
6433         /* Before 8.3, there is no built-in text search support */
6434         if (fout->remoteVersion < 80300)
6435         {
6436                 *numTSConfigs = 0;
6437                 return NULL;
6438         }
6439
6440         query = createPQExpBuffer();
6441
6442         /* Make sure we are in proper schema */
6443         selectSourceSchema(fout, "pg_catalog");
6444
6445         appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6446                                           "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6447                                           "FROM pg_ts_config",
6448                                           username_subquery);
6449
6450         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6451
6452         ntups = PQntuples(res);
6453         *numTSConfigs = ntups;
6454
6455         cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6456
6457         i_tableoid = PQfnumber(res, "tableoid");
6458         i_oid = PQfnumber(res, "oid");
6459         i_cfgname = PQfnumber(res, "cfgname");
6460         i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6461         i_rolname = PQfnumber(res, "rolname");
6462         i_cfgparser = PQfnumber(res, "cfgparser");
6463
6464         for (i = 0; i < ntups; i++)
6465         {
6466                 cfginfo[i].dobj.objType = DO_TSCONFIG;
6467                 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6468                 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6469                 AssignDumpId(&cfginfo[i].dobj);
6470                 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6471                 cfginfo[i].dobj.namespace =
6472                         findNamespace(fout,
6473                                                   atooid(PQgetvalue(res, i, i_cfgnamespace)),
6474                                                   cfginfo[i].dobj.catId.oid);
6475                 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6476                 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6477
6478                 /* Decide whether we want to dump it */
6479                 selectDumpableObject(&(cfginfo[i].dobj));
6480         }
6481
6482         PQclear(res);
6483
6484         destroyPQExpBuffer(query);
6485
6486         return cfginfo;
6487 }
6488
6489 /*
6490  * getForeignDataWrappers:
6491  *        read all foreign-data wrappers in the system catalogs and return
6492  *        them in the FdwInfo* structure
6493  *
6494  *      numForeignDataWrappers is set to the number of fdws read in
6495  */
6496 FdwInfo *
6497 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
6498 {
6499         PGresult   *res;
6500         int                     ntups;
6501         int                     i;
6502         PQExpBuffer query = createPQExpBuffer();
6503         FdwInfo    *fdwinfo;
6504         int                     i_tableoid;
6505         int                     i_oid;
6506         int                     i_fdwname;
6507         int                     i_rolname;
6508         int                     i_fdwhandler;
6509         int                     i_fdwvalidator;
6510         int                     i_fdwacl;
6511         int                     i_fdwoptions;
6512
6513         /* Before 8.4, there are no foreign-data wrappers */
6514         if (fout->remoteVersion < 80400)
6515         {
6516                 *numForeignDataWrappers = 0;
6517                 return NULL;
6518         }
6519
6520         /* Make sure we are in proper schema */
6521         selectSourceSchema(fout, "pg_catalog");
6522
6523         if (fout->remoteVersion >= 90100)
6524         {
6525                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6526                                                   "(%s fdwowner) AS rolname, "
6527                                                   "fdwhandler::pg_catalog.regproc, "
6528                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
6529                                                   "array_to_string(ARRAY("
6530                                                   "SELECT quote_ident(option_name) || ' ' || "
6531                                                   "quote_literal(option_value) "
6532                                                   "FROM pg_options_to_table(fdwoptions) "
6533                                                   "ORDER BY option_name"
6534                                                   "), E',\n    ') AS fdwoptions "
6535                                                   "FROM pg_foreign_data_wrapper",
6536                                                   username_subquery);
6537         }
6538         else
6539         {
6540                 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6541                                                   "(%s fdwowner) AS rolname, "
6542                                                   "'-' AS fdwhandler, "
6543                                                   "fdwvalidator::pg_catalog.regproc, fdwacl, "
6544                                                   "array_to_string(ARRAY("
6545                                                   "SELECT quote_ident(option_name) || ' ' || "
6546                                                   "quote_literal(option_value) "
6547                                                   "FROM pg_options_to_table(fdwoptions) "
6548                                                   "ORDER BY option_name"
6549                                                   "), E',\n    ') AS fdwoptions "
6550                                                   "FROM pg_foreign_data_wrapper",
6551                                                   username_subquery);
6552         }
6553
6554         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6555
6556         ntups = PQntuples(res);
6557         *numForeignDataWrappers = ntups;
6558
6559         fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6560
6561         i_tableoid = PQfnumber(res, "tableoid");
6562         i_oid = PQfnumber(res, "oid");
6563         i_fdwname = PQfnumber(res, "fdwname");
6564         i_rolname = PQfnumber(res, "rolname");
6565         i_fdwhandler = PQfnumber(res, "fdwhandler");
6566         i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6567         i_fdwacl = PQfnumber(res, "fdwacl");
6568         i_fdwoptions = PQfnumber(res, "fdwoptions");
6569
6570         for (i = 0; i < ntups; i++)
6571         {
6572                 fdwinfo[i].dobj.objType = DO_FDW;
6573                 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6574                 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6575                 AssignDumpId(&fdwinfo[i].dobj);
6576                 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6577                 fdwinfo[i].dobj.namespace = NULL;
6578                 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6579                 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6580                 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6581                 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6582                 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6583
6584                 /* Decide whether we want to dump it */
6585                 selectDumpableObject(&(fdwinfo[i].dobj));
6586         }
6587
6588         PQclear(res);
6589
6590         destroyPQExpBuffer(query);
6591
6592         return fdwinfo;
6593 }
6594
6595 /*
6596  * getForeignServers:
6597  *        read all foreign servers in the system catalogs and return
6598  *        them in the ForeignServerInfo * structure
6599  *
6600  *      numForeignServers is set to the number of servers read in
6601  */
6602 ForeignServerInfo *
6603 getForeignServers(Archive *fout, int *numForeignServers)
6604 {
6605         PGresult   *res;
6606         int                     ntups;
6607         int                     i;
6608         PQExpBuffer query = createPQExpBuffer();
6609         ForeignServerInfo *srvinfo;
6610         int                     i_tableoid;
6611         int                     i_oid;
6612         int                     i_srvname;
6613         int                     i_rolname;
6614         int                     i_srvfdw;
6615         int                     i_srvtype;
6616         int                     i_srvversion;
6617         int                     i_srvacl;
6618         int                     i_srvoptions;
6619
6620         /* Before 8.4, there are no foreign servers */
6621         if (fout->remoteVersion < 80400)
6622         {
6623                 *numForeignServers = 0;
6624                 return NULL;
6625         }
6626
6627         /* Make sure we are in proper schema */
6628         selectSourceSchema(fout,"pg_catalog");
6629
6630         appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6631                                           "(%s srvowner) AS rolname, "
6632                                           "srvfdw, srvtype, srvversion, srvacl,"
6633                                           "array_to_string(ARRAY("
6634                                           "SELECT quote_ident(option_name) || ' ' || "
6635                                           "quote_literal(option_value) "
6636                                           "FROM pg_options_to_table(srvoptions) "
6637                                           "ORDER BY option_name"
6638                                           "), E',\n    ') AS srvoptions "
6639                                           "FROM pg_foreign_server",
6640                                           username_subquery);
6641
6642         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6643
6644         ntups = PQntuples(res);
6645         *numForeignServers = ntups;
6646
6647         srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
6648
6649         i_tableoid = PQfnumber(res, "tableoid");
6650         i_oid = PQfnumber(res, "oid");
6651         i_srvname = PQfnumber(res, "srvname");
6652         i_rolname = PQfnumber(res, "rolname");
6653         i_srvfdw = PQfnumber(res, "srvfdw");
6654         i_srvtype = PQfnumber(res, "srvtype");
6655         i_srvversion = PQfnumber(res, "srvversion");
6656         i_srvacl = PQfnumber(res, "srvacl");
6657         i_srvoptions = PQfnumber(res, "srvoptions");
6658
6659         for (i = 0; i < ntups; i++)
6660         {
6661                 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
6662                 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6663                 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6664                 AssignDumpId(&srvinfo[i].dobj);
6665                 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
6666                 srvinfo[i].dobj.namespace = NULL;
6667                 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6668                 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
6669                 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
6670                 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
6671                 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
6672                 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
6673
6674                 /* Decide whether we want to dump it */
6675                 selectDumpableObject(&(srvinfo[i].dobj));
6676         }
6677
6678         PQclear(res);
6679
6680         destroyPQExpBuffer(query);
6681
6682         return srvinfo;
6683 }
6684
6685 /*
6686  * getDefaultACLs:
6687  *        read all default ACL information in the system catalogs and return
6688  *        them in the DefaultACLInfo structure
6689  *
6690  *      numDefaultACLs is set to the number of ACLs read in
6691  */
6692 DefaultACLInfo *
6693 getDefaultACLs(Archive *fout, int *numDefaultACLs)
6694 {
6695         DefaultACLInfo *daclinfo;
6696         PQExpBuffer query;
6697         PGresult   *res;
6698         int                     i_oid;
6699         int                     i_tableoid;
6700         int                     i_defaclrole;
6701         int                     i_defaclnamespace;
6702         int                     i_defaclobjtype;
6703         int                     i_defaclacl;
6704         int                     i,
6705                                 ntups;
6706
6707         if (fout->remoteVersion < 90000)
6708         {
6709                 *numDefaultACLs = 0;
6710                 return NULL;
6711         }
6712
6713         query = createPQExpBuffer();
6714
6715         /* Make sure we are in proper schema */
6716         selectSourceSchema(fout, "pg_catalog");
6717
6718         appendPQExpBuffer(query, "SELECT oid, tableoid, "
6719                                           "(%s defaclrole) AS defaclrole, "
6720                                           "defaclnamespace, "
6721                                           "defaclobjtype, "
6722                                           "defaclacl "
6723                                           "FROM pg_default_acl",
6724                                           username_subquery);
6725
6726         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6727
6728         ntups = PQntuples(res);
6729         *numDefaultACLs = ntups;
6730
6731         daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
6732
6733         i_oid = PQfnumber(res, "oid");
6734         i_tableoid = PQfnumber(res, "tableoid");
6735         i_defaclrole = PQfnumber(res, "defaclrole");
6736         i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6737         i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6738         i_defaclacl = PQfnumber(res, "defaclacl");
6739
6740         for (i = 0; i < ntups; i++)
6741         {
6742                 Oid                     nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6743
6744                 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6745                 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6746                 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6747                 AssignDumpId(&daclinfo[i].dobj);
6748                 /* cheesy ... is it worth coming up with a better object name? */
6749                 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
6750
6751                 if (nspid != InvalidOid)
6752                         daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
6753                                                                                                  daclinfo[i].dobj.catId.oid);
6754                 else
6755                         daclinfo[i].dobj.namespace = NULL;
6756
6757                 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
6758                 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6759                 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
6760
6761                 /* Decide whether we want to dump it */
6762                 selectDumpableDefaultACL(&(daclinfo[i]));
6763         }
6764
6765         PQclear(res);
6766
6767         destroyPQExpBuffer(query);
6768
6769         return daclinfo;
6770 }
6771
6772 /*
6773  * dumpComment --
6774  *
6775  * This routine is used to dump any comments associated with the
6776  * object handed to this routine. The routine takes a constant character
6777  * string for the target part of the comment-creation command, plus
6778  * the namespace and owner of the object (for labeling the ArchiveEntry),
6779  * plus catalog ID and subid which are the lookup key for pg_description,
6780  * plus the dump ID for the object (for setting a dependency).
6781  * If a matching pg_description entry is found, it is dumped.
6782  *
6783  * Note: although this routine takes a dumpId for dependency purposes,
6784  * that purpose is just to mark the dependency in the emitted dump file
6785  * for possible future use by pg_restore.  We do NOT use it for determining
6786  * ordering of the comment in the dump file, because this routine is called
6787  * after dependency sorting occurs.  This routine should be called just after
6788  * calling ArchiveEntry() for the specified object.
6789  */
6790 static void
6791 dumpComment(Archive *fout, const char *target,
6792                         const char *namespace, const char *owner,
6793                         CatalogId catalogId, int subid, DumpId dumpId)
6794 {
6795         CommentItem *comments;
6796         int                     ncomments;
6797
6798         /* Comments are schema not data ... except blob comments are data */
6799         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6800         {
6801                 if (dataOnly)
6802                         return;
6803         }
6804         else
6805         {
6806                 if (schemaOnly)
6807                         return;
6808         }
6809
6810         /* Search for comments associated with catalogId, using table */
6811         ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6812                                                          &comments);
6813
6814         /* Is there one matching the subid? */
6815         while (ncomments > 0)
6816         {
6817                 if (comments->objsubid == subid)
6818                         break;
6819                 comments++;
6820                 ncomments--;
6821         }
6822
6823         /* If a comment exists, build COMMENT ON statement */
6824         if (ncomments > 0)
6825         {
6826                 PQExpBuffer query = createPQExpBuffer();
6827
6828                 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
6829                 appendStringLiteralAH(query, comments->descr, fout);
6830                 appendPQExpBuffer(query, ";\n");
6831
6832                 /*
6833                  * We mark comments as SECTION_NONE because they really belong in the
6834                  * same section as their parent, whether that is pre-data or
6835                  * post-data.
6836                  */
6837                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6838                                          target, namespace, NULL, owner,
6839                                          false, "COMMENT", SECTION_NONE,
6840                                          query->data, "", NULL,
6841                                          &(dumpId), 1,
6842                                          NULL, NULL);
6843
6844                 destroyPQExpBuffer(query);
6845         }
6846 }
6847
6848 /*
6849  * dumpTableComment --
6850  *
6851  * As above, but dump comments for both the specified table (or view)
6852  * and its columns.
6853  */
6854 static void
6855 dumpTableComment(Archive *fout, TableInfo *tbinfo,
6856                                  const char *reltypename)
6857 {
6858         CommentItem *comments;
6859         int                     ncomments;
6860         PQExpBuffer query;
6861         PQExpBuffer target;
6862
6863         /* Comments are SCHEMA not data */
6864         if (dataOnly)
6865                 return;
6866
6867         /* Search for comments associated with relation, using table */
6868         ncomments = findComments(fout,
6869                                                          tbinfo->dobj.catId.tableoid,
6870                                                          tbinfo->dobj.catId.oid,
6871                                                          &comments);
6872
6873         /* If comments exist, build COMMENT ON statements */
6874         if (ncomments <= 0)
6875                 return;
6876
6877         query = createPQExpBuffer();
6878         target = createPQExpBuffer();
6879
6880         while (ncomments > 0)
6881         {
6882                 const char *descr = comments->descr;
6883                 int                     objsubid = comments->objsubid;
6884
6885                 if (objsubid == 0)
6886                 {
6887                         resetPQExpBuffer(target);
6888                         appendPQExpBuffer(target, "%s %s", reltypename,
6889                                                           fmtId(tbinfo->dobj.name));
6890
6891                         resetPQExpBuffer(query);
6892                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6893                         appendStringLiteralAH(query, descr, fout);
6894                         appendPQExpBuffer(query, ";\n");
6895
6896                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
6897                                                  target->data,
6898                                                  tbinfo->dobj.namespace->dobj.name,
6899                                                  NULL, tbinfo->rolname,
6900                                                  false, "COMMENT", SECTION_NONE,
6901                                                  query->data, "", NULL,
6902                                                  &(tbinfo->dobj.dumpId), 1,
6903                                                  NULL, NULL);
6904                 }
6905                 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
6906                 {
6907                         resetPQExpBuffer(target);
6908                         appendPQExpBuffer(target, "COLUMN %s.",
6909                                                           fmtId(tbinfo->dobj.name));
6910                         appendPQExpBuffer(target, "%s",
6911                                                           fmtId(tbinfo->attnames[objsubid - 1]));
6912
6913                         resetPQExpBuffer(query);
6914                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6915                         appendStringLiteralAH(query, descr, fout);
6916                         appendPQExpBuffer(query, ";\n");
6917
6918                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
6919                                                  target->data,
6920                                                  tbinfo->dobj.namespace->dobj.name,
6921                                                  NULL, tbinfo->rolname,
6922                                                  false, "COMMENT", SECTION_NONE,
6923                                                  query->data, "", NULL,
6924                                                  &(tbinfo->dobj.dumpId), 1,
6925                                                  NULL, NULL);
6926                 }
6927
6928                 comments++;
6929                 ncomments--;
6930         }
6931
6932         destroyPQExpBuffer(query);
6933         destroyPQExpBuffer(target);
6934 }
6935
6936 /*
6937  * findComments --
6938  *
6939  * Find the comment(s), if any, associated with the given object.  All the
6940  * objsubid values associated with the given classoid/objoid are found with
6941  * one search.
6942  */
6943 static int
6944 findComments(Archive *fout, Oid classoid, Oid objoid,
6945                          CommentItem **items)
6946 {
6947         /* static storage for table of comments */
6948         static CommentItem *comments = NULL;
6949         static int      ncomments = -1;
6950
6951         CommentItem *middle = NULL;
6952         CommentItem *low;
6953         CommentItem *high;
6954         int                     nmatch;
6955
6956         /* Get comments if we didn't already */
6957         if (ncomments < 0)
6958                 ncomments = collectComments(fout, &comments);
6959
6960         /*
6961          * Pre-7.2, pg_description does not contain classoid, so collectComments
6962          * just stores a zero.  If there's a collision on object OID, well, you
6963          * get duplicate comments.
6964          */
6965         if (fout->remoteVersion < 70200)
6966                 classoid = 0;
6967
6968         /*
6969          * Do binary search to find some item matching the object.
6970          */
6971         low = &comments[0];
6972         high = &comments[ncomments - 1];
6973         while (low <= high)
6974         {
6975                 middle = low + (high - low) / 2;
6976
6977                 if (classoid < middle->classoid)
6978                         high = middle - 1;
6979                 else if (classoid > middle->classoid)
6980                         low = middle + 1;
6981                 else if (objoid < middle->objoid)
6982                         high = middle - 1;
6983                 else if (objoid > middle->objoid)
6984                         low = middle + 1;
6985                 else
6986                         break;                          /* found a match */
6987         }
6988
6989         if (low > high)                         /* no matches */
6990         {
6991                 *items = NULL;
6992                 return 0;
6993         }
6994
6995         /*
6996          * Now determine how many items match the object.  The search loop
6997          * invariant still holds: only items between low and high inclusive could
6998          * match.
6999          */
7000         nmatch = 1;
7001         while (middle > low)
7002         {
7003                 if (classoid != middle[-1].classoid ||
7004                         objoid != middle[-1].objoid)
7005                         break;
7006                 middle--;
7007                 nmatch++;
7008         }
7009
7010         *items = middle;
7011
7012         middle += nmatch;
7013         while (middle <= high)
7014         {
7015                 if (classoid != middle->classoid ||
7016                         objoid != middle->objoid)
7017                         break;
7018                 middle++;
7019                 nmatch++;
7020         }
7021
7022         return nmatch;
7023 }
7024
7025 /*
7026  * collectComments --
7027  *
7028  * Construct a table of all comments available for database objects.
7029  * We used to do per-object queries for the comments, but it's much faster
7030  * to pull them all over at once, and on most databases the memory cost
7031  * isn't high.
7032  *
7033  * The table is sorted by classoid/objid/objsubid for speed in lookup.
7034  */
7035 static int
7036 collectComments(Archive *fout, CommentItem **items)
7037 {
7038         PGresult   *res;
7039         PQExpBuffer query;
7040         int                     i_description;
7041         int                     i_classoid;
7042         int                     i_objoid;
7043         int                     i_objsubid;
7044         int                     ntups;
7045         int                     i;
7046         CommentItem *comments;
7047
7048         /*
7049          * Note we do NOT change source schema here; preserve the caller's
7050          * setting, instead.
7051          */
7052
7053         query = createPQExpBuffer();
7054
7055         if (fout->remoteVersion >= 70300)
7056         {
7057                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7058                                                   "FROM pg_catalog.pg_description "
7059                                                   "ORDER BY classoid, objoid, objsubid");
7060         }
7061         else if (fout->remoteVersion >= 70200)
7062         {
7063                 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7064                                                   "FROM pg_description "
7065                                                   "ORDER BY classoid, objoid, objsubid");
7066         }
7067         else
7068         {
7069                 /* Note: this will fail to find attribute comments in pre-7.2... */
7070                 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7071                                                   "FROM pg_description "
7072                                                   "ORDER BY objoid");
7073         }
7074
7075         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7076
7077         /* Construct lookup table containing OIDs in numeric form */
7078
7079         i_description = PQfnumber(res, "description");
7080         i_classoid = PQfnumber(res, "classoid");
7081         i_objoid = PQfnumber(res, "objoid");
7082         i_objsubid = PQfnumber(res, "objsubid");
7083
7084         ntups = PQntuples(res);
7085
7086         comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7087
7088         for (i = 0; i < ntups; i++)
7089         {
7090                 comments[i].descr = PQgetvalue(res, i, i_description);
7091                 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7092                 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7093                 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7094         }
7095
7096         /* Do NOT free the PGresult since we are keeping pointers into it */
7097         destroyPQExpBuffer(query);
7098
7099         *items = comments;
7100         return ntups;
7101 }
7102
7103 /*
7104  * dumpDumpableObject
7105  *
7106  * This routine and its subsidiaries are responsible for creating
7107  * ArchiveEntries (TOC objects) for each object to be dumped.
7108  */
7109 static void
7110 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7111 {
7112
7113         bool skip = false;
7114
7115         switch (dobj->objType)
7116         {
7117                 case DO_INDEX:
7118                 case DO_TRIGGER:
7119                 case DO_CONSTRAINT:
7120                 case DO_FK_CONSTRAINT:
7121                 case DO_RULE:
7122                         skip = !(dumpSections & DUMP_POST_DATA);
7123                         break;
7124                 case DO_TABLE_DATA:
7125                         skip = !(dumpSections & DUMP_DATA);
7126                         break;
7127                 default:
7128                         skip = !(dumpSections & DUMP_PRE_DATA);
7129         }
7130
7131         if (skip)
7132                 return;
7133
7134         switch (dobj->objType)
7135         {
7136                 case DO_NAMESPACE:
7137                         dumpNamespace(fout, (NamespaceInfo *) dobj);
7138                         break;
7139                 case DO_EXTENSION:
7140                         dumpExtension(fout, (ExtensionInfo *) dobj);
7141                         break;
7142                 case DO_TYPE:
7143                         dumpType(fout, (TypeInfo *) dobj);
7144                         break;
7145                 case DO_SHELL_TYPE:
7146                         dumpShellType(fout, (ShellTypeInfo *) dobj);
7147                         break;
7148                 case DO_FUNC:
7149                         dumpFunc(fout, (FuncInfo *) dobj);
7150                         break;
7151                 case DO_AGG:
7152                         dumpAgg(fout, (AggInfo *) dobj);
7153                         break;
7154                 case DO_OPERATOR:
7155                         dumpOpr(fout, (OprInfo *) dobj);
7156                         break;
7157                 case DO_OPCLASS:
7158                         dumpOpclass(fout, (OpclassInfo *) dobj);
7159                         break;
7160                 case DO_OPFAMILY:
7161                         dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7162                         break;
7163                 case DO_COLLATION:
7164                         dumpCollation(fout, (CollInfo *) dobj);
7165                         break;
7166                 case DO_CONVERSION:
7167                         dumpConversion(fout, (ConvInfo *) dobj);
7168                         break;
7169                 case DO_TABLE:
7170                         dumpTable(fout, (TableInfo *) dobj);
7171                         break;
7172                 case DO_ATTRDEF:
7173                         dumpAttrDef(fout, (AttrDefInfo *) dobj);
7174                         break;
7175                 case DO_INDEX:
7176                         dumpIndex(fout, (IndxInfo *) dobj);
7177                         break;
7178                 case DO_RULE:
7179                         dumpRule(fout, (RuleInfo *) dobj);
7180                         break;
7181                 case DO_TRIGGER:
7182                         dumpTrigger(fout, (TriggerInfo *) dobj);
7183                         break;
7184                 case DO_CONSTRAINT:
7185                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7186                         break;
7187                 case DO_FK_CONSTRAINT:
7188                         dumpConstraint(fout, (ConstraintInfo *) dobj);
7189                         break;
7190                 case DO_PROCLANG:
7191                         dumpProcLang(fout, (ProcLangInfo *) dobj);
7192                         break;
7193                 case DO_CAST:
7194                         dumpCast(fout, (CastInfo *) dobj);
7195                         break;
7196                 case DO_TABLE_DATA:
7197                         dumpTableData(fout, (TableDataInfo *) dobj);
7198                         break;
7199                 case DO_DUMMY_TYPE:
7200                         /* table rowtypes and array types are never dumped separately */
7201                         break;
7202                 case DO_TSPARSER:
7203                         dumpTSParser(fout, (TSParserInfo *) dobj);
7204                         break;
7205                 case DO_TSDICT:
7206                         dumpTSDictionary(fout, (TSDictInfo *) dobj);
7207                         break;
7208                 case DO_TSTEMPLATE:
7209                         dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7210                         break;
7211                 case DO_TSCONFIG:
7212                         dumpTSConfig(fout, (TSConfigInfo *) dobj);
7213                         break;
7214                 case DO_FDW:
7215                         dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7216                         break;
7217                 case DO_FOREIGN_SERVER:
7218                         dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7219                         break;
7220                 case DO_DEFAULT_ACL:
7221                         dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7222                         break;
7223                 case DO_BLOB:
7224                         dumpBlob(fout, (BlobInfo *) dobj);
7225                         break;
7226                 case DO_BLOB_DATA:
7227                         ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7228                                                  dobj->name, NULL, NULL, "",
7229                                                  false, "BLOBS", SECTION_DATA,
7230                                                  "", "", NULL,
7231                                                  dobj->dependencies, dobj->nDeps,
7232                                                  dumpBlobs, NULL);
7233                         break;
7234         }
7235 }
7236
7237 /*
7238  * dumpNamespace
7239  *        writes out to fout the queries to recreate a user-defined namespace
7240  */
7241 static void
7242 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7243 {
7244         PQExpBuffer q;
7245         PQExpBuffer delq;
7246         PQExpBuffer labelq;
7247         char       *qnspname;
7248
7249         /* Skip if not to be dumped */
7250         if (!nspinfo->dobj.dump || dataOnly)
7251                 return;
7252
7253         /* don't dump dummy namespace from pre-7.3 source */
7254         if (strlen(nspinfo->dobj.name) == 0)
7255                 return;
7256
7257         q = createPQExpBuffer();
7258         delq = createPQExpBuffer();
7259         labelq = createPQExpBuffer();
7260
7261         qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7262
7263         appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7264
7265         appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7266
7267         appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7268
7269         if (binary_upgrade)
7270                 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7271
7272         ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7273                                  nspinfo->dobj.name,
7274                                  NULL, NULL,
7275                                  nspinfo->rolname,
7276                                  false, "SCHEMA", SECTION_PRE_DATA,
7277                                  q->data, delq->data, NULL,
7278                                  nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
7279                                  NULL, NULL);
7280
7281         /* Dump Schema Comments and Security Labels */
7282         dumpComment(fout, labelq->data,
7283                                 NULL, nspinfo->rolname,
7284                                 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7285         dumpSecLabel(fout, labelq->data,
7286                                  NULL, nspinfo->rolname,
7287                                  nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7288
7289         dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7290                         qnspname, NULL, nspinfo->dobj.name, NULL,
7291                         nspinfo->rolname, nspinfo->nspacl);
7292
7293         free(qnspname);
7294
7295         destroyPQExpBuffer(q);
7296         destroyPQExpBuffer(delq);
7297         destroyPQExpBuffer(labelq);
7298 }
7299
7300 /*
7301  * dumpExtension
7302  *        writes out to fout the queries to recreate an extension
7303  */
7304 static void
7305 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7306 {
7307         PQExpBuffer q;
7308         PQExpBuffer delq;
7309         PQExpBuffer labelq;
7310         char       *qextname;
7311
7312         /* Skip if not to be dumped */
7313         if (!extinfo->dobj.dump || dataOnly)
7314                 return;
7315
7316         q = createPQExpBuffer();
7317         delq = createPQExpBuffer();
7318         labelq = createPQExpBuffer();
7319
7320         qextname = pg_strdup(fmtId(extinfo->dobj.name));
7321
7322         appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7323
7324         if (!binary_upgrade)
7325         {
7326                 /*
7327                  * In a regular dump, we use IF NOT EXISTS so that there isn't a
7328                  * problem if the extension already exists in the target database;
7329                  * this is essential for installed-by-default extensions such as
7330                  * plpgsql.
7331                  *
7332                  * In binary-upgrade mode, that doesn't work well, so instead we skip
7333                  * built-in extensions based on their OIDs; see
7334                  * selectDumpableExtension.
7335                  */
7336                 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7337                                                   qextname, fmtId(extinfo->namespace));
7338         }
7339         else
7340         {
7341                 int                     i;
7342                 int                     n;
7343
7344                 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7345                 appendPQExpBuffer(q,
7346                                                   "SELECT binary_upgrade.create_empty_extension(");
7347                 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7348                 appendPQExpBuffer(q, ", ");
7349                 appendStringLiteralAH(q, extinfo->namespace, fout);
7350                 appendPQExpBuffer(q, ", ");
7351                 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7352                 appendStringLiteralAH(q, extinfo->extversion, fout);
7353                 appendPQExpBuffer(q, ", ");
7354
7355                 /*
7356                  * Note that we're pushing extconfig (an OID array) back into
7357                  * pg_extension exactly as-is.  This is OK because pg_class OIDs are
7358                  * preserved in binary upgrade.
7359                  */
7360                 if (strlen(extinfo->extconfig) > 2)
7361                         appendStringLiteralAH(q, extinfo->extconfig, fout);
7362                 else
7363                         appendPQExpBuffer(q, "NULL");
7364                 appendPQExpBuffer(q, ", ");
7365                 if (strlen(extinfo->extcondition) > 2)
7366                         appendStringLiteralAH(q, extinfo->extcondition, fout);
7367                 else
7368                         appendPQExpBuffer(q, "NULL");
7369                 appendPQExpBuffer(q, ", ");
7370                 appendPQExpBuffer(q, "ARRAY[");
7371                 n = 0;
7372                 for (i = 0; i < extinfo->dobj.nDeps; i++)
7373                 {
7374                         DumpableObject *extobj;
7375
7376                         extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7377                         if (extobj && extobj->objType == DO_EXTENSION)
7378                         {
7379                                 if (n++ > 0)
7380                                         appendPQExpBuffer(q, ",");
7381                                 appendStringLiteralAH(q, extobj->name, fout);
7382                         }
7383                 }
7384                 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7385                 appendPQExpBuffer(q, ");\n");
7386         }
7387
7388         appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7389
7390         ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7391                                  extinfo->dobj.name,
7392                                  NULL, NULL,
7393                                  "",
7394                                  false, "EXTENSION", SECTION_PRE_DATA,
7395                                  q->data, delq->data, NULL,
7396                                  extinfo->dobj.dependencies, extinfo->dobj.nDeps,
7397                                  NULL, NULL);
7398
7399         /* Dump Extension Comments and Security Labels */
7400         dumpComment(fout, labelq->data,
7401                                 NULL, "",
7402                                 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7403         dumpSecLabel(fout, labelq->data,
7404                                  NULL, "",
7405                                  extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7406
7407         free(qextname);
7408
7409         destroyPQExpBuffer(q);
7410         destroyPQExpBuffer(delq);
7411         destroyPQExpBuffer(labelq);
7412 }
7413
7414 /*
7415  * dumpType
7416  *        writes out to fout the queries to recreate a user-defined type
7417  */
7418 static void
7419 dumpType(Archive *fout, TypeInfo *tyinfo)
7420 {
7421         /* Skip if not to be dumped */
7422         if (!tyinfo->dobj.dump || dataOnly)
7423                 return;
7424
7425         /* Dump out in proper style */
7426         if (tyinfo->typtype == TYPTYPE_BASE)
7427                 dumpBaseType(fout, tyinfo);
7428         else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7429                 dumpDomain(fout, tyinfo);
7430         else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7431                 dumpCompositeType(fout, tyinfo);
7432         else if (tyinfo->typtype == TYPTYPE_ENUM)
7433                 dumpEnumType(fout, tyinfo);
7434         else if (tyinfo->typtype == TYPTYPE_RANGE)
7435                 dumpRangeType(fout, tyinfo);
7436         else
7437                 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7438                                   tyinfo->dobj.name);
7439 }
7440
7441 /*
7442  * dumpEnumType
7443  *        writes out to fout the queries to recreate a user-defined enum type
7444  */
7445 static void
7446 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7447 {
7448         PQExpBuffer q = createPQExpBuffer();
7449         PQExpBuffer delq = createPQExpBuffer();
7450         PQExpBuffer labelq = createPQExpBuffer();
7451         PQExpBuffer query = createPQExpBuffer();
7452         PGresult   *res;
7453         int                     num,
7454                                 i;
7455         Oid                     enum_oid;
7456         char       *label;
7457
7458         /* Set proper schema search path */
7459         selectSourceSchema(fout, "pg_catalog");
7460
7461         if (fout->remoteVersion >= 90100)
7462                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7463                                                   "FROM pg_catalog.pg_enum "
7464                                                   "WHERE enumtypid = '%u'"
7465                                                   "ORDER BY enumsortorder",
7466                                                   tyinfo->dobj.catId.oid);
7467         else
7468                 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7469                                                   "FROM pg_catalog.pg_enum "
7470                                                   "WHERE enumtypid = '%u'"
7471                                                   "ORDER BY oid",
7472                                                   tyinfo->dobj.catId.oid);
7473
7474         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7475
7476         num = PQntuples(res);
7477
7478         /*
7479          * DROP must be fully qualified in case same name appears in pg_catalog.
7480          * CASCADE shouldn't be required here as for normal types since the I/O
7481          * functions are generic and do not get dropped.
7482          */
7483         appendPQExpBuffer(delq, "DROP TYPE %s.",
7484                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7485         appendPQExpBuffer(delq, "%s;\n",
7486                                           fmtId(tyinfo->dobj.name));
7487
7488         if (binary_upgrade)
7489                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7490                                                                                                  tyinfo->dobj.catId.oid);
7491
7492         appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7493                                           fmtId(tyinfo->dobj.name));
7494
7495         if (!binary_upgrade)
7496         {
7497                 /* Labels with server-assigned oids */
7498                 for (i = 0; i < num; i++)
7499                 {
7500                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7501                         if (i > 0)
7502                                 appendPQExpBuffer(q, ",");
7503                         appendPQExpBuffer(q, "\n    ");
7504                         appendStringLiteralAH(q, label, fout);
7505                 }
7506         }
7507
7508         appendPQExpBuffer(q, "\n);\n");
7509
7510         if (binary_upgrade)
7511         {
7512                 /* Labels with dump-assigned (preserved) oids */
7513                 for (i = 0; i < num; i++)
7514                 {
7515                         enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7516                         label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7517
7518                         if (i == 0)
7519                                 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7520                         appendPQExpBuffer(q,
7521                                                           "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7522                                                           enum_oid);
7523                         appendPQExpBuffer(q, "ALTER TYPE %s.",
7524                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7525                         appendPQExpBuffer(q, "%s ADD VALUE ",
7526                                                           fmtId(tyinfo->dobj.name));
7527                         appendStringLiteralAH(q, label, fout);
7528                         appendPQExpBuffer(q, ";\n\n");
7529                 }
7530         }
7531
7532         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7533
7534         if (binary_upgrade)
7535                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7536
7537         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7538                                  tyinfo->dobj.name,
7539                                  tyinfo->dobj.namespace->dobj.name,
7540                                  NULL,
7541                                  tyinfo->rolname, false,
7542                                  "TYPE", SECTION_PRE_DATA,
7543                                  q->data, delq->data, NULL,
7544                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7545                                  NULL, NULL);
7546
7547         /* Dump Type Comments and Security Labels */
7548         dumpComment(fout, labelq->data,
7549                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7550                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7551         dumpSecLabel(fout, labelq->data,
7552                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7553                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7554
7555         PQclear(res);
7556         destroyPQExpBuffer(q);
7557         destroyPQExpBuffer(delq);
7558         destroyPQExpBuffer(labelq);
7559         destroyPQExpBuffer(query);
7560 }
7561
7562 /*
7563  * dumpRangeType
7564  *        writes out to fout the queries to recreate a user-defined range type
7565  */
7566 static void
7567 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7568 {
7569         PQExpBuffer q = createPQExpBuffer();
7570         PQExpBuffer delq = createPQExpBuffer();
7571         PQExpBuffer labelq = createPQExpBuffer();
7572         PQExpBuffer query = createPQExpBuffer();
7573         PGresult   *res;
7574         Oid                     collationOid;
7575         char       *procname;
7576
7577         /*
7578          * select appropriate schema to ensure names in CREATE are properly
7579          * qualified
7580          */
7581         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7582
7583         appendPQExpBuffer(query,
7584                                           "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7585                                           "opc.opcname AS opcname, "
7586                                           "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7587                                           "  WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7588                                           "opc.opcdefault, "
7589                                           "CASE WHEN rngcollation = st.typcollation THEN 0 "
7590                                           "     ELSE rngcollation END AS collation, "
7591                                           "rngcanonical, rngsubdiff "
7592                                           "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7593                                           "     pg_catalog.pg_opclass opc "
7594                                           "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7595                                           "rngtypid = '%u'",
7596                                           tyinfo->dobj.catId.oid);
7597
7598         res = ExecuteSqlQueryForSingleRow(fout, query->data);
7599
7600         /*
7601          * DROP must be fully qualified in case same name appears in pg_catalog.
7602          * CASCADE shouldn't be required here as for normal types since the I/O
7603          * functions are generic and do not get dropped.
7604          */
7605         appendPQExpBuffer(delq, "DROP TYPE %s.",
7606                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7607         appendPQExpBuffer(delq, "%s;\n",
7608                                           fmtId(tyinfo->dobj.name));
7609
7610         if (binary_upgrade)
7611                 binary_upgrade_set_type_oids_by_type_oid(fout,
7612                                                                                                  q, tyinfo->dobj.catId.oid);
7613
7614         appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7615                                           fmtId(tyinfo->dobj.name));
7616
7617         appendPQExpBuffer(q, "\n    subtype = %s",
7618                                           PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7619
7620         /* print subtype_opclass only if not default for subtype */
7621         if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7622         {
7623                 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7624                 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7625
7626                 /* always schema-qualify, don't try to be smart */
7627                 appendPQExpBuffer(q, ",\n    subtype_opclass = %s.",
7628                                                   fmtId(nspname));
7629                 appendPQExpBuffer(q, "%s", fmtId(opcname));
7630         }
7631
7632         collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
7633         if (OidIsValid(collationOid))
7634         {
7635                 CollInfo   *coll = findCollationByOid(collationOid);
7636
7637                 if (coll)
7638                 {
7639                         /* always schema-qualify, don't try to be smart */
7640                         appendPQExpBuffer(q, ",\n    collation = %s.",
7641                                                           fmtId(coll->dobj.namespace->dobj.name));
7642                         appendPQExpBuffer(q, "%s",
7643                                                           fmtId(coll->dobj.name));
7644                 }
7645         }
7646
7647         procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
7648         if (strcmp(procname, "-") != 0)
7649                 appendPQExpBuffer(q, ",\n    canonical = %s", procname);
7650
7651         procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
7652         if (strcmp(procname, "-") != 0)
7653                 appendPQExpBuffer(q, ",\n    subtype_diff = %s", procname);
7654
7655         appendPQExpBuffer(q, "\n);\n");
7656
7657         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7658
7659         if (binary_upgrade)
7660                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7661
7662         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7663                                  tyinfo->dobj.name,
7664                                  tyinfo->dobj.namespace->dobj.name,
7665                                  NULL,
7666                                  tyinfo->rolname, false,
7667                                  "TYPE", SECTION_PRE_DATA,
7668                                  q->data, delq->data, NULL,
7669                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7670                                  NULL, NULL);
7671
7672         /* Dump Type Comments and Security Labels */
7673         dumpComment(fout, labelq->data,
7674                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7675                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7676         dumpSecLabel(fout, labelq->data,
7677                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7678                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7679
7680         PQclear(res);
7681         destroyPQExpBuffer(q);
7682         destroyPQExpBuffer(delq);
7683         destroyPQExpBuffer(labelq);
7684         destroyPQExpBuffer(query);
7685 }
7686
7687 /*
7688  * dumpBaseType
7689  *        writes out to fout the queries to recreate a user-defined base type
7690  */
7691 static void
7692 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
7693 {
7694         PQExpBuffer q = createPQExpBuffer();
7695         PQExpBuffer delq = createPQExpBuffer();
7696         PQExpBuffer labelq = createPQExpBuffer();
7697         PQExpBuffer query = createPQExpBuffer();
7698         PGresult   *res;
7699         char       *typlen;
7700         char       *typinput;
7701         char       *typoutput;
7702         char       *typreceive;
7703         char       *typsend;
7704         char       *typmodin;
7705         char       *typmodout;
7706         char       *typanalyze;
7707         Oid                     typreceiveoid;
7708         Oid                     typsendoid;
7709         Oid                     typmodinoid;
7710         Oid                     typmodoutoid;
7711         Oid                     typanalyzeoid;
7712         char       *typcategory;
7713         char       *typispreferred;
7714         char       *typdelim;
7715         char       *typbyval;
7716         char       *typalign;
7717         char       *typstorage;
7718         char       *typcollatable;
7719         char       *typdefault;
7720         bool            typdefault_is_literal = false;
7721
7722         /* Set proper schema search path so regproc references list correctly */
7723         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7724
7725         /* Fetch type-specific details */
7726         if (fout->remoteVersion >= 90100)
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                                                   "(typcollation <> 0) 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 >= 80400)
7745         {
7746                 appendPQExpBuffer(query, "SELECT typlen, "
7747                                                   "typinput, typoutput, typreceive, typsend, "
7748                                                   "typmodin, typmodout, typanalyze, "
7749                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7750                                                   "typsend::pg_catalog.oid AS typsendoid, "
7751                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7752                                                   "typmodout::pg_catalog.oid AS typmodoutoid, "
7753                                                   "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7754                                                   "typcategory, typispreferred, "
7755                                                   "typdelim, typbyval, typalign, typstorage, "
7756                                                   "false AS typcollatable, "
7757                                                   "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7758                                                   "FROM pg_catalog.pg_type "
7759                                                   "WHERE oid = '%u'::pg_catalog.oid",
7760                                                   tyinfo->dobj.catId.oid);
7761         }
7762         else if (fout->remoteVersion >= 80300)
7763         {
7764                 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
7765                 appendPQExpBuffer(query, "SELECT typlen, "
7766                                                   "typinput, typoutput, typreceive, typsend, "
7767                                                   "typmodin, typmodout, typanalyze, "
7768                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7769                                                   "typsend::pg_catalog.oid AS typsendoid, "
7770                                                   "typmodin::pg_catalog.oid AS typmodinoid, "
7771                                                   "typmodout::pg_catalog.oid 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 >= 80000)
7782         {
7783                 appendPQExpBuffer(query, "SELECT typlen, "
7784                                                   "typinput, typoutput, typreceive, typsend, "
7785                                                   "'-' AS typmodin, '-' AS typmodout, "
7786                                                   "typanalyze, "
7787                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7788                                                   "typsend::pg_catalog.oid AS typsendoid, "
7789                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7790                                                   "typanalyze::pg_catalog.oid 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 >= 70400)
7800         {
7801                 appendPQExpBuffer(query, "SELECT typlen, "
7802                                                   "typinput, typoutput, typreceive, typsend, "
7803                                                   "'-' AS typmodin, '-' AS typmodout, "
7804                                                   "'-' AS typanalyze, "
7805                                                   "typreceive::pg_catalog.oid AS typreceiveoid, "
7806                                                   "typsend::pg_catalog.oid 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 >= 70300)
7818         {
7819                 appendPQExpBuffer(query, "SELECT typlen, "
7820                                                   "typinput, typoutput, "
7821                                                   "'-' AS typreceive, '-' AS typsend, "
7822                                                   "'-' AS typmodin, '-' AS typmodout, "
7823                                                   "'-' AS typanalyze, "
7824                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7825                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7826                                                   "0 AS typanalyzeoid, "
7827                                                   "'U' AS typcategory, false AS typispreferred, "
7828                                                   "typdelim, typbyval, typalign, typstorage, "
7829                                                   "false AS typcollatable, "
7830                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7831                                                   "FROM pg_catalog.pg_type "
7832                                                   "WHERE oid = '%u'::pg_catalog.oid",
7833                                                   tyinfo->dobj.catId.oid);
7834         }
7835         else if (fout->remoteVersion >= 70200)
7836         {
7837                 /*
7838                  * Note: although pre-7.3 catalogs contain typreceive and typsend,
7839                  * ignore them because they are not right.
7840                  */
7841                 appendPQExpBuffer(query, "SELECT typlen, "
7842                                                   "typinput, typoutput, "
7843                                                   "'-' AS typreceive, '-' AS typsend, "
7844                                                   "'-' AS typmodin, '-' AS typmodout, "
7845                                                   "'-' AS typanalyze, "
7846                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7847                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7848                                                   "0 AS typanalyzeoid, "
7849                                                   "'U' AS typcategory, false AS typispreferred, "
7850                                                   "typdelim, typbyval, typalign, typstorage, "
7851                                                   "false AS typcollatable, "
7852                                                   "NULL AS typdefaultbin, typdefault "
7853                                                   "FROM pg_type "
7854                                                   "WHERE oid = '%u'::oid",
7855                                                   tyinfo->dobj.catId.oid);
7856         }
7857         else if (fout->remoteVersion >= 70100)
7858         {
7859                 /*
7860                  * Ignore pre-7.2 typdefault; the field exists but has an unusable
7861                  * representation.
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, typstorage, "
7873                                                   "false AS typcollatable, "
7874                                                   "NULL AS typdefaultbin, NULL AS typdefault "
7875                                                   "FROM pg_type "
7876                                                   "WHERE oid = '%u'::oid",
7877                                                   tyinfo->dobj.catId.oid);
7878         }
7879         else
7880         {
7881                 appendPQExpBuffer(query, "SELECT typlen, "
7882                                                   "typinput, typoutput, "
7883                                                   "'-' AS typreceive, '-' AS typsend, "
7884                                                   "'-' AS typmodin, '-' AS typmodout, "
7885                                                   "'-' AS typanalyze, "
7886                                                   "0 AS typreceiveoid, 0 AS typsendoid, "
7887                                                   "0 AS typmodinoid, 0 AS typmodoutoid, "
7888                                                   "0 AS typanalyzeoid, "
7889                                                   "'U' AS typcategory, false AS typispreferred, "
7890                                                   "typdelim, typbyval, typalign, "
7891                                                   "'p'::char AS typstorage, "
7892                                                   "false AS typcollatable, "
7893                                                   "NULL AS typdefaultbin, NULL AS typdefault "
7894                                                   "FROM pg_type "
7895                                                   "WHERE oid = '%u'::oid",
7896                                                   tyinfo->dobj.catId.oid);
7897         }
7898
7899         res = ExecuteSqlQueryForSingleRow(fout, query->data);
7900
7901         typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
7902         typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
7903         typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
7904         typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
7905         typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
7906         typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
7907         typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
7908         typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
7909         typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
7910         typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
7911         typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
7912         typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
7913         typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
7914         typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
7915         typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
7916         typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
7917         typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
7918         typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
7919         typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
7920         typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
7921         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
7922                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
7923         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
7924         {
7925                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
7926                 typdefault_is_literal = true;   /* it needs quotes */
7927         }
7928         else
7929                 typdefault = NULL;
7930
7931         /*
7932          * DROP must be fully qualified in case same name appears in pg_catalog.
7933          * The reason we include CASCADE is that the circular dependency between
7934          * the type and its I/O functions makes it impossible to drop the type any
7935          * other way.
7936          */
7937         appendPQExpBuffer(delq, "DROP TYPE %s.",
7938                                           fmtId(tyinfo->dobj.namespace->dobj.name));
7939         appendPQExpBuffer(delq, "%s CASCADE;\n",
7940                                           fmtId(tyinfo->dobj.name));
7941
7942         /* We might already have a shell type, but setting pg_type_oid is harmless */
7943         if (binary_upgrade)
7944                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7945                                                                                                  tyinfo->dobj.catId.oid);
7946
7947         appendPQExpBuffer(q,
7948                                           "CREATE TYPE %s (\n"
7949                                           "    INTERNALLENGTH = %s",
7950                                           fmtId(tyinfo->dobj.name),
7951                                           (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
7952
7953         if (fout->remoteVersion >= 70300)
7954         {
7955                 /* regproc result is correctly quoted as of 7.3 */
7956                 appendPQExpBuffer(q, ",\n    INPUT = %s", typinput);
7957                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", typoutput);
7958                 if (OidIsValid(typreceiveoid))
7959                         appendPQExpBuffer(q, ",\n    RECEIVE = %s", typreceive);
7960                 if (OidIsValid(typsendoid))
7961                         appendPQExpBuffer(q, ",\n    SEND = %s", typsend);
7962                 if (OidIsValid(typmodinoid))
7963                         appendPQExpBuffer(q, ",\n    TYPMOD_IN = %s", typmodin);
7964                 if (OidIsValid(typmodoutoid))
7965                         appendPQExpBuffer(q, ",\n    TYPMOD_OUT = %s", typmodout);
7966                 if (OidIsValid(typanalyzeoid))
7967                         appendPQExpBuffer(q, ",\n    ANALYZE = %s", typanalyze);
7968         }
7969         else
7970         {
7971                 /* regproc delivers an unquoted name before 7.3 */
7972                 /* cannot combine these because fmtId uses static result area */
7973                 appendPQExpBuffer(q, ",\n    INPUT = %s", fmtId(typinput));
7974                 appendPQExpBuffer(q, ",\n    OUTPUT = %s", fmtId(typoutput));
7975                 /* receive/send/typmodin/typmodout/analyze need not be printed */
7976         }
7977
7978         if (strcmp(typcollatable, "t") == 0)
7979                 appendPQExpBuffer(q, ",\n    COLLATABLE = true");
7980
7981         if (typdefault != NULL)
7982         {
7983                 appendPQExpBuffer(q, ",\n    DEFAULT = ");
7984                 if (typdefault_is_literal)
7985                         appendStringLiteralAH(q, typdefault, fout);
7986                 else
7987                         appendPQExpBufferStr(q, typdefault);
7988         }
7989
7990         if (OidIsValid(tyinfo->typelem))
7991         {
7992                 char       *elemType;
7993
7994                 /* reselect schema in case changed by function dump */
7995                 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7996                 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
7997                 appendPQExpBuffer(q, ",\n    ELEMENT = %s", elemType);
7998                 free(elemType);
7999         }
8000
8001         if (strcmp(typcategory, "U") != 0)
8002         {
8003                 appendPQExpBuffer(q, ",\n    CATEGORY = ");
8004                 appendStringLiteralAH(q, typcategory, fout);
8005         }
8006
8007         if (strcmp(typispreferred, "t") == 0)
8008                 appendPQExpBuffer(q, ",\n    PREFERRED = true");
8009
8010         if (typdelim && strcmp(typdelim, ",") != 0)
8011         {
8012                 appendPQExpBuffer(q, ",\n    DELIMITER = ");
8013                 appendStringLiteralAH(q, typdelim, fout);
8014         }
8015
8016         if (strcmp(typalign, "c") == 0)
8017                 appendPQExpBuffer(q, ",\n    ALIGNMENT = char");
8018         else if (strcmp(typalign, "s") == 0)
8019                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int2");
8020         else if (strcmp(typalign, "i") == 0)
8021                 appendPQExpBuffer(q, ",\n    ALIGNMENT = int4");
8022         else if (strcmp(typalign, "d") == 0)
8023                 appendPQExpBuffer(q, ",\n    ALIGNMENT = double");
8024
8025         if (strcmp(typstorage, "p") == 0)
8026                 appendPQExpBuffer(q, ",\n    STORAGE = plain");
8027         else if (strcmp(typstorage, "e") == 0)
8028                 appendPQExpBuffer(q, ",\n    STORAGE = external");
8029         else if (strcmp(typstorage, "x") == 0)
8030                 appendPQExpBuffer(q, ",\n    STORAGE = extended");
8031         else if (strcmp(typstorage, "m") == 0)
8032                 appendPQExpBuffer(q, ",\n    STORAGE = main");
8033
8034         if (strcmp(typbyval, "t") == 0)
8035                 appendPQExpBuffer(q, ",\n    PASSEDBYVALUE");
8036
8037         appendPQExpBuffer(q, "\n);\n");
8038
8039         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8040
8041         if (binary_upgrade)
8042                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8043
8044         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8045                                  tyinfo->dobj.name,
8046                                  tyinfo->dobj.namespace->dobj.name,
8047                                  NULL,
8048                                  tyinfo->rolname, false,
8049                                  "TYPE", SECTION_PRE_DATA,
8050                                  q->data, delq->data, NULL,
8051                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8052                                  NULL, NULL);
8053
8054         /* Dump Type Comments and Security Labels */
8055         dumpComment(fout, labelq->data,
8056                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8057                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8058         dumpSecLabel(fout, labelq->data,
8059                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8060                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8061
8062         PQclear(res);
8063         destroyPQExpBuffer(q);
8064         destroyPQExpBuffer(delq);
8065         destroyPQExpBuffer(labelq);
8066         destroyPQExpBuffer(query);
8067 }
8068
8069 /*
8070  * dumpDomain
8071  *        writes out to fout the queries to recreate a user-defined domain
8072  */
8073 static void
8074 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8075 {
8076         PQExpBuffer q = createPQExpBuffer();
8077         PQExpBuffer delq = createPQExpBuffer();
8078         PQExpBuffer labelq = createPQExpBuffer();
8079         PQExpBuffer query = createPQExpBuffer();
8080         PGresult   *res;
8081         int                     i;
8082         char       *typnotnull;
8083         char       *typdefn;
8084         char       *typdefault;
8085         Oid                     typcollation;
8086         bool            typdefault_is_literal = false;
8087
8088         /* Set proper schema search path so type references list correctly */
8089         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8090
8091         /* Fetch domain specific details */
8092         if (fout->remoteVersion >= 90100)
8093         {
8094                 /* typcollation is new in 9.1 */
8095                 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8096                         "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8097                                                   "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8098                                                   "t.typdefault, "
8099                                                   "CASE WHEN t.typcollation <> u.typcollation "
8100                                                   "THEN t.typcollation ELSE 0 END AS typcollation "
8101                                                   "FROM pg_catalog.pg_type t "
8102                                  "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8103                                                   "WHERE t.oid = '%u'::pg_catalog.oid",
8104                                                   tyinfo->dobj.catId.oid);
8105         }
8106         else
8107         {
8108                 /* We assume here that remoteVersion must be at least 70300 */
8109                 appendPQExpBuffer(query, "SELECT typnotnull, "
8110                                 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8111                                                   "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8112                                                   "typdefault, 0 AS typcollation "
8113                                                   "FROM pg_catalog.pg_type "
8114                                                   "WHERE oid = '%u'::pg_catalog.oid",
8115                                                   tyinfo->dobj.catId.oid);
8116         }
8117
8118         res = ExecuteSqlQueryForSingleRow(fout, query->data);
8119
8120         typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8121         typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8122         if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8123                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8124         else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8125         {
8126                 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8127                 typdefault_is_literal = true;   /* it needs quotes */
8128         }
8129         else
8130                 typdefault = NULL;
8131         typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8132
8133         if (binary_upgrade)
8134                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8135                                                                                                  tyinfo->dobj.catId.oid);
8136
8137         appendPQExpBuffer(q,
8138                                           "CREATE DOMAIN %s AS %s",
8139                                           fmtId(tyinfo->dobj.name),
8140                                           typdefn);
8141
8142         /* Print collation only if different from base type's collation */
8143         if (OidIsValid(typcollation))
8144         {
8145                 CollInfo   *coll;
8146
8147                 coll = findCollationByOid(typcollation);
8148                 if (coll)
8149                 {
8150                         /* always schema-qualify, don't try to be smart */
8151                         appendPQExpBuffer(q, " COLLATE %s.",
8152                                                           fmtId(coll->dobj.namespace->dobj.name));
8153                         appendPQExpBuffer(q, "%s",
8154                                                           fmtId(coll->dobj.name));
8155                 }
8156         }
8157
8158         if (typnotnull[0] == 't')
8159                 appendPQExpBuffer(q, " NOT NULL");
8160
8161         if (typdefault != NULL)
8162         {
8163                 appendPQExpBuffer(q, " DEFAULT ");
8164                 if (typdefault_is_literal)
8165                         appendStringLiteralAH(q, typdefault, fout);
8166                 else
8167                         appendPQExpBufferStr(q, typdefault);
8168         }
8169
8170         PQclear(res);
8171
8172         /*
8173          * Add any CHECK constraints for the domain
8174          */
8175         for (i = 0; i < tyinfo->nDomChecks; i++)
8176         {
8177                 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8178
8179                 if (!domcheck->separate)
8180                         appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8181                                                           fmtId(domcheck->dobj.name), domcheck->condef);
8182         }
8183
8184         appendPQExpBuffer(q, ";\n");
8185
8186         /*
8187          * DROP must be fully qualified in case same name appears in pg_catalog
8188          */
8189         appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8190                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8191         appendPQExpBuffer(delq, "%s;\n",
8192                                           fmtId(tyinfo->dobj.name));
8193
8194         appendPQExpBuffer(labelq, "DOMAIN %s", fmtId(tyinfo->dobj.name));
8195
8196         if (binary_upgrade)
8197                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8198
8199         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8200                                  tyinfo->dobj.name,
8201                                  tyinfo->dobj.namespace->dobj.name,
8202                                  NULL,
8203                                  tyinfo->rolname, false,
8204                                  "DOMAIN", SECTION_PRE_DATA,
8205                                  q->data, delq->data, NULL,
8206                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8207                                  NULL, NULL);
8208
8209         /* Dump Domain Comments and Security Labels */
8210         dumpComment(fout, labelq->data,
8211                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8212                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8213         dumpSecLabel(fout, labelq->data,
8214                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8215                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8216
8217         destroyPQExpBuffer(q);
8218         destroyPQExpBuffer(delq);
8219         destroyPQExpBuffer(labelq);
8220         destroyPQExpBuffer(query);
8221 }
8222
8223 /*
8224  * dumpCompositeType
8225  *        writes out to fout the queries to recreate a user-defined stand-alone
8226  *        composite type
8227  */
8228 static void
8229 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8230 {
8231         PQExpBuffer q = createPQExpBuffer();
8232         PQExpBuffer dropped = createPQExpBuffer();
8233         PQExpBuffer delq = createPQExpBuffer();
8234         PQExpBuffer labelq = createPQExpBuffer();
8235         PQExpBuffer query = createPQExpBuffer();
8236         PGresult   *res;
8237         int                     ntups;
8238         int                     i_attname;
8239         int                     i_atttypdefn;
8240         int                     i_attlen;
8241         int                     i_attalign;
8242         int                     i_attisdropped;
8243         int                     i_attcollation;
8244         int                     i_typrelid;
8245         int                     i;
8246         int                     actual_atts;
8247
8248         /* Set proper schema search path so type references list correctly */
8249         selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8250
8251         /* Fetch type specific details */
8252         if (fout->remoteVersion >= 90100)
8253         {
8254                 /*
8255                  * attcollation is new in 9.1.  Since we only want to dump COLLATE
8256                  * clauses for attributes whose collation is different from their
8257                  * type's default, we use a CASE here to suppress uninteresting
8258                  * attcollations cheaply.  atttypid will be 0 for dropped columns;
8259                  * collation does not matter for those.
8260                  */
8261                 appendPQExpBuffer(query, "SELECT a.attname, "
8262                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8263                                                   "a.attlen, a.attalign, a.attisdropped, "
8264                                                   "CASE WHEN a.attcollation <> at.typcollation "
8265                                                   "THEN a.attcollation ELSE 0 END AS attcollation, "
8266                                                   "ct.typrelid "
8267                                                   "FROM pg_catalog.pg_type ct "
8268                                 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8269                                         "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8270                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8271                                                   "ORDER BY a.attnum ",
8272                                                   tyinfo->dobj.catId.oid);
8273         }
8274         else
8275         {
8276                 /*
8277                  * We assume here that remoteVersion must be at least 70300.  Since
8278                  * ALTER TYPE could not drop columns until 9.1, attisdropped should
8279                  * always be false.
8280                  */
8281                 appendPQExpBuffer(query, "SELECT a.attname, "
8282                         "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8283                                                   "a.attlen, a.attalign, a.attisdropped, "
8284                                                   "0 AS attcollation, "
8285                                                   "ct.typrelid "
8286                                          "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8287                                                   "WHERE ct.oid = '%u'::pg_catalog.oid "
8288                                                   "AND a.attrelid = ct.typrelid "
8289                                                   "ORDER BY a.attnum ",
8290                                                   tyinfo->dobj.catId.oid);
8291         }
8292
8293         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8294
8295         ntups = PQntuples(res);
8296
8297         i_attname = PQfnumber(res, "attname");
8298         i_atttypdefn = PQfnumber(res, "atttypdefn");
8299         i_attlen = PQfnumber(res, "attlen");
8300         i_attalign = PQfnumber(res, "attalign");
8301         i_attisdropped = PQfnumber(res, "attisdropped");
8302         i_attcollation = PQfnumber(res, "attcollation");
8303         i_typrelid = PQfnumber(res, "typrelid");
8304
8305         if (binary_upgrade)
8306         {
8307                 Oid                     typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8308
8309                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8310                                                                                                  tyinfo->dobj.catId.oid);
8311                 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8312         }
8313
8314         appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8315                                           fmtId(tyinfo->dobj.name));
8316
8317         actual_atts = 0;
8318         for (i = 0; i < ntups; i++)
8319         {
8320                 char       *attname;
8321                 char       *atttypdefn;
8322                 char       *attlen;
8323                 char       *attalign;
8324                 bool            attisdropped;
8325                 Oid                     attcollation;
8326
8327                 attname = PQgetvalue(res, i, i_attname);
8328                 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8329                 attlen = PQgetvalue(res, i, i_attlen);
8330                 attalign = PQgetvalue(res, i, i_attalign);
8331                 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8332                 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8333
8334                 if (attisdropped && !binary_upgrade)
8335                         continue;
8336
8337                 /* Format properly if not first attr */
8338                 if (actual_atts++ > 0)
8339                         appendPQExpBuffer(q, ",");
8340                 appendPQExpBuffer(q, "\n\t");
8341
8342                 if (!attisdropped)
8343                 {
8344                         appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8345
8346                         /* Add collation if not default for the column type */
8347                         if (OidIsValid(attcollation))
8348                         {
8349                                 CollInfo   *coll;
8350
8351                                 coll = findCollationByOid(attcollation);
8352                                 if (coll)
8353                                 {
8354                                         /* always schema-qualify, don't try to be smart */
8355                                         appendPQExpBuffer(q, " COLLATE %s.",
8356                                                                           fmtId(coll->dobj.namespace->dobj.name));
8357                                         appendPQExpBuffer(q, "%s",
8358                                                                           fmtId(coll->dobj.name));
8359                                 }
8360                         }
8361                 }
8362                 else
8363                 {
8364                         /*
8365                          * This is a dropped attribute and we're in binary_upgrade mode.
8366                          * Insert a placeholder for it in the CREATE TYPE command, and set
8367                          * length and alignment with direct UPDATE to the catalogs
8368                          * afterwards. See similar code in dumpTableSchema().
8369                          */
8370                         appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8371
8372                         /* stash separately for insertion after the CREATE TYPE */
8373                         appendPQExpBuffer(dropped,
8374                                           "\n-- For binary upgrade, recreate dropped column.\n");
8375                         appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8376                                                           "SET attlen = %s, "
8377                                                           "attalign = '%s', attbyval = false\n"
8378                                                           "WHERE attname = ", attlen, attalign);
8379                         appendStringLiteralAH(dropped, attname, fout);
8380                         appendPQExpBuffer(dropped, "\n  AND attrelid = ");
8381                         appendStringLiteralAH(dropped, fmtId(tyinfo->dobj.name), fout);
8382                         appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8383
8384                         appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8385                                                           fmtId(tyinfo->dobj.name));
8386                         appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8387                                                           fmtId(attname));
8388                 }
8389         }
8390         appendPQExpBuffer(q, "\n);\n");
8391         appendPQExpBufferStr(q, dropped->data);
8392
8393         /*
8394          * DROP must be fully qualified in case same name appears in pg_catalog
8395          */
8396         appendPQExpBuffer(delq, "DROP TYPE %s.",
8397                                           fmtId(tyinfo->dobj.namespace->dobj.name));
8398         appendPQExpBuffer(delq, "%s;\n",
8399                                           fmtId(tyinfo->dobj.name));
8400
8401         appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8402
8403         if (binary_upgrade)
8404                 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8405
8406         ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8407                                  tyinfo->dobj.name,
8408                                  tyinfo->dobj.namespace->dobj.name,
8409                                  NULL,
8410                                  tyinfo->rolname, false,
8411                                  "TYPE", SECTION_PRE_DATA,
8412                                  q->data, delq->data, NULL,
8413                                  tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8414                                  NULL, NULL);
8415
8416
8417         /* Dump Type Comments and Security Labels */
8418         dumpComment(fout, labelq->data,
8419                                 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8420                                 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8421         dumpSecLabel(fout, labelq->data,
8422                                  tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8423                                  tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8424
8425         PQclear(res);
8426         destroyPQExpBuffer(q);
8427         destroyPQExpBuffer(dropped);
8428         destroyPQExpBuffer(delq);
8429         destroyPQExpBuffer(labelq);
8430         destroyPQExpBuffer(query);
8431
8432         /* Dump any per-column comments */
8433         dumpCompositeTypeColComments(fout, tyinfo);
8434 }
8435
8436 /*
8437  * dumpCompositeTypeColComments
8438  *        writes out to fout the queries to recreate comments on the columns of
8439  *        a user-defined stand-alone composite type
8440  */
8441 static void
8442 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8443 {
8444         CommentItem *comments;
8445         int                     ncomments;
8446         PGresult   *res;
8447         PQExpBuffer query;
8448         PQExpBuffer target;
8449         Oid                     pgClassOid;
8450         int                     i;
8451         int                     ntups;
8452         int                     i_attname;
8453         int                     i_attnum;
8454
8455         query = createPQExpBuffer();
8456
8457         /* We assume here that remoteVersion must be at least 70300 */
8458         appendPQExpBuffer(query,
8459                                           "SELECT c.tableoid, a.attname, a.attnum "
8460                                           "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8461                                           "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8462                                           "  AND NOT a.attisdropped "
8463                                           "ORDER BY a.attnum ",
8464                                           tyinfo->typrelid);
8465
8466         /* Fetch column attnames */
8467         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8468
8469         ntups = PQntuples(res);
8470         if (ntups < 1)
8471         {
8472                 PQclear(res);
8473                 destroyPQExpBuffer(query);
8474                 return;
8475         }
8476
8477         pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8478
8479         /* Search for comments associated with type's pg_class OID */
8480         ncomments = findComments(fout,
8481                                                          pgClassOid,
8482                                                          tyinfo->typrelid,
8483                                                          &comments);
8484
8485         /* If no comments exist, we're done */
8486         if (ncomments <= 0)
8487         {
8488                 PQclear(res);
8489                 destroyPQExpBuffer(query);
8490                 return;
8491         }
8492
8493         /* Build COMMENT ON statements */
8494         target = createPQExpBuffer();
8495
8496         i_attnum = PQfnumber(res, "attnum");
8497         i_attname = PQfnumber(res, "attname");
8498         while (ncomments > 0)
8499         {
8500                 const char *attname;
8501
8502                 attname = NULL;
8503                 for (i = 0; i < ntups; i++)
8504                 {
8505                         if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8506                         {
8507                                 attname = PQgetvalue(res, i, i_attname);
8508                                 break;
8509                         }
8510                 }
8511                 if (attname)                    /* just in case we don't find it */
8512                 {
8513                         const char *descr = comments->descr;
8514
8515                         resetPQExpBuffer(target);
8516                         appendPQExpBuffer(target, "COLUMN %s.",
8517                                                           fmtId(tyinfo->dobj.name));
8518                         appendPQExpBuffer(target, "%s",
8519                                                           fmtId(attname));
8520
8521                         resetPQExpBuffer(query);
8522                         appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8523                         appendStringLiteralAH(query, descr, fout);
8524                         appendPQExpBuffer(query, ";\n");
8525
8526                         ArchiveEntry(fout, nilCatalogId, createDumpId(),
8527                                                  target->data,
8528                                                  tyinfo->dobj.namespace->dobj.name,
8529                                                  NULL, tyinfo->rolname,
8530                                                  false, "COMMENT", SECTION_NONE,
8531                                                  query->data, "", NULL,
8532                                                  &(tyinfo->dobj.dumpId), 1,
8533                                                  NULL, NULL);
8534                 }
8535
8536                 comments++;
8537                 ncomments--;
8538         }
8539
8540         PQclear(res);
8541         destroyPQExpBuffer(query);
8542         destroyPQExpBuffer(target);
8543 }
8544
8545 /*
8546  * dumpShellType
8547  *        writes out to fout the queries to create a shell type
8548  *
8549  * We dump a shell definition in advance of the I/O functions for the type.
8550  */
8551 static void
8552 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8553 {
8554         PQExpBuffer q;
8555
8556         /* Skip if not to be dumped */
8557         if (!stinfo->dobj.dump || dataOnly)
8558                 return;
8559
8560         q = createPQExpBuffer();
8561
8562         /*
8563          * Note the lack of a DROP command for the shell type; any required DROP
8564          * is driven off the base type entry, instead.  This interacts with
8565          * _printTocEntry()'s use of the presence of a DROP command to decide
8566          * whether an entry needs an ALTER OWNER command.  We don't want to alter
8567          * the shell type's owner immediately on creation; that should happen only
8568          * after it's filled in, otherwise the backend complains.
8569          */
8570
8571         if (binary_upgrade)
8572                 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8573                                                                                    stinfo->baseType->dobj.catId.oid);
8574
8575         appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8576                                           fmtId(stinfo->dobj.name));
8577
8578         ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8579                                  stinfo->dobj.name,
8580                                  stinfo->dobj.namespace->dobj.name,
8581                                  NULL,
8582                                  stinfo->baseType->rolname, false,
8583                                  "SHELL TYPE", SECTION_PRE_DATA,
8584                                  q->data, "", NULL,
8585                                  stinfo->dobj.dependencies, stinfo->dobj.nDeps,
8586                                  NULL, NULL);
8587
8588         destroyPQExpBuffer(q);
8589 }
8590
8591 /*
8592  * Determine whether we want to dump definitions for procedural languages.
8593  * Since the languages themselves don't have schemas, we can't rely on
8594  * the normal schema-based selection mechanism.  We choose to dump them
8595  * whenever neither --schema nor --table was given.  (Before 8.1, we used
8596  * the dump flag of the PL's call handler function, but in 8.1 this will
8597  * probably always be false since call handlers are created in pg_catalog.)
8598  *
8599  * For some backwards compatibility with the older behavior, we forcibly
8600  * dump a PL if its handler function (and validator if any) are in a
8601  * dumpable namespace.  That case is not checked here.
8602  *
8603  * Also, if the PL belongs to an extension, we do not use this heuristic.
8604  * That case isn't checked here either.
8605  */
8606 static bool
8607 shouldDumpProcLangs(void)
8608 {
8609         if (!include_everything)
8610                 return false;
8611         /* And they're schema not data */
8612         if (dataOnly)
8613                 return false;
8614         return true;
8615 }
8616
8617 /*
8618  * dumpProcLang
8619  *                writes out to fout the queries to recreate a user-defined
8620  *                procedural language
8621  */
8622 static void
8623 dumpProcLang(Archive *fout, ProcLangInfo *plang)
8624 {
8625         PQExpBuffer defqry;
8626         PQExpBuffer delqry;
8627         PQExpBuffer labelq;
8628         bool            useParams;
8629         char       *qlanname;
8630         char       *lanschema;
8631         FuncInfo   *funcInfo;
8632         FuncInfo   *inlineInfo = NULL;
8633         FuncInfo   *validatorInfo = NULL;
8634
8635         /* Skip if not to be dumped */
8636         if (!plang->dobj.dump || dataOnly)
8637                 return;
8638
8639         /*
8640          * Try to find the support function(s).  It is not an error if we don't
8641          * find them --- if the functions are in the pg_catalog schema, as is
8642          * standard in 8.1 and up, then we won't have loaded them. (In this case
8643          * we will emit a parameterless CREATE LANGUAGE command, which will
8644          * require PL template knowledge in the backend to reload.)
8645          */
8646
8647         funcInfo = findFuncByOid(plang->lanplcallfoid);
8648         if (funcInfo != NULL && !funcInfo->dobj.dump)
8649                 funcInfo = NULL;                /* treat not-dumped same as not-found */
8650
8651         if (OidIsValid(plang->laninline))
8652         {
8653                 inlineInfo = findFuncByOid(plang->laninline);
8654                 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
8655                         inlineInfo = NULL;
8656         }
8657
8658         if (OidIsValid(plang->lanvalidator))
8659         {
8660                 validatorInfo = findFuncByOid(plang->lanvalidator);
8661                 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
8662                         validatorInfo = NULL;
8663         }
8664
8665         /*
8666          * If the functions are dumpable then emit a traditional CREATE LANGUAGE
8667          * with parameters.  Otherwise, dump only if shouldDumpProcLangs() says to
8668          * dump it.
8669          *
8670          * However, for a language that belongs to an extension, we must not use
8671          * the shouldDumpProcLangs heuristic, but just dump the language iff we're
8672          * told to (via dobj.dump).  Generally the support functions will belong
8673          * to the same extension and so have the same dump flags ... if they
8674          * don't, this might not work terribly nicely.
8675          */
8676         useParams = (funcInfo != NULL &&
8677                                  (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
8678                                  (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
8679
8680         if (!plang->dobj.ext_member)
8681         {
8682                 if (!useParams && !shouldDumpProcLangs())
8683                         return;
8684         }
8685
8686         defqry = createPQExpBuffer();
8687         delqry = createPQExpBuffer();
8688         labelq = createPQExpBuffer();
8689
8690         qlanname = pg_strdup(fmtId(plang->dobj.name));
8691
8692         /*
8693          * If dumping a HANDLER clause, treat the language as being in the handler
8694          * function's schema; this avoids cluttering the HANDLER clause. Otherwise
8695          * it doesn't really have a schema.
8696          */
8697         if (useParams)
8698                 lanschema = funcInfo->dobj.namespace->dobj.name;
8699         else
8700                 lanschema = NULL;
8701
8702         appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
8703                                           qlanname);
8704
8705         if (useParams)
8706         {
8707                 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
8708                                                   plang->lanpltrusted ? "TRUSTED " : "",
8709                                                   qlanname);
8710                 appendPQExpBuffer(defqry, " HANDLER %s",
8711                                                   fmtId(funcInfo->dobj.name));
8712                 if (OidIsValid(plang->laninline))
8713                 {
8714                         appendPQExpBuffer(defqry, " INLINE ");
8715                         /* Cope with possibility that inline is in different schema */
8716                         if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
8717                                 appendPQExpBuffer(defqry, "%s.",
8718                                                            fmtId(inlineInfo->dobj.namespace->dobj.name));
8719                         appendPQExpBuffer(defqry, "%s",
8720                                                           fmtId(inlineInfo->dobj.name));
8721                 }
8722                 if (OidIsValid(plang->lanvalidator))
8723                 {
8724                         appendPQExpBuffer(defqry, " VALIDATOR ");
8725                         /* Cope with possibility that validator is in different schema */
8726                         if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
8727                                 appendPQExpBuffer(defqry, "%s.",
8728                                                         fmtId(validatorInfo->dobj.namespace->dobj.name));
8729                         appendPQExpBuffer(defqry, "%s",
8730                                                           fmtId(validatorInfo->dobj.name));
8731                 }
8732         }
8733         else
8734         {
8735                 /*
8736                  * If not dumping parameters, then use CREATE OR REPLACE so that the
8737                  * command will not fail if the language is preinstalled in the target
8738                  * database.  We restrict the use of REPLACE to this case so as to
8739                  * eliminate the risk of replacing a language with incompatible
8740                  * parameter settings: this command will only succeed at all if there
8741                  * is a pg_pltemplate entry, and if there is one, the existing entry
8742                  * must match it too.
8743                  */
8744                 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
8745                                                   qlanname);
8746         }
8747         appendPQExpBuffer(defqry, ";\n");
8748
8749         appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
8750
8751         if (binary_upgrade)
8752                 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
8753
8754         ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
8755                                  plang->dobj.name,
8756                                  lanschema, NULL, plang->lanowner,
8757                                  false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
8758                                  defqry->data, delqry->data, NULL,
8759                                  plang->dobj.dependencies, plang->dobj.nDeps,
8760                                  NULL, NULL);
8761
8762         /* Dump Proc Lang Comments and Security Labels */
8763         dumpComment(fout, labelq->data,
8764                                 NULL, "",
8765                                 plang->dobj.catId, 0, plang->dobj.dumpId);
8766         dumpSecLabel(fout, labelq->data,
8767                                  NULL, "",
8768                                  plang->dobj.catId, 0, plang->dobj.dumpId);
8769
8770         if (plang->lanpltrusted)
8771                 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
8772                                 qlanname, NULL, plang->dobj.name,
8773                                 lanschema,
8774                                 plang->lanowner, plang->lanacl);
8775
8776         free(qlanname);
8777
8778         destroyPQExpBuffer(defqry);
8779         destroyPQExpBuffer(delqry);
8780         destroyPQExpBuffer(labelq);
8781 }
8782
8783 /*
8784  * format_function_arguments: generate function name and argument list
8785  *
8786  * This is used when we can rely on pg_get_function_arguments to format
8787  * the argument list.
8788  */
8789 static char *
8790 format_function_arguments(FuncInfo *finfo, char *funcargs)
8791 {
8792         PQExpBufferData fn;
8793
8794         initPQExpBuffer(&fn);
8795         appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
8796         return fn.data;
8797 }
8798
8799 /*
8800  * format_function_arguments_old: generate function name and argument list
8801  *
8802  * The argument type names are qualified if needed.  The function name
8803  * is never qualified.
8804  *
8805  * This is used only with pre-8.4 servers, so we aren't expecting to see
8806  * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
8807  *
8808  * Any or all of allargtypes, argmodes, argnames may be NULL.
8809  */
8810 static char *
8811 format_function_arguments_old(Archive *fout,
8812                                                           FuncInfo *finfo, int nallargs,
8813                                                           char **allargtypes,
8814                                                           char **argmodes,
8815                                                           char **argnames)
8816 {
8817         PQExpBufferData fn;
8818         int                     j;
8819
8820         initPQExpBuffer(&fn);
8821         appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8822         for (j = 0; j < nallargs; j++)
8823         {
8824                 Oid                     typid;
8825                 char       *typname;
8826                 const char *argmode;
8827                 const char *argname;
8828
8829                 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
8830                 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
8831
8832                 if (argmodes)
8833                 {
8834                         switch (argmodes[j][0])
8835                         {
8836                                 case PROARGMODE_IN:
8837                                         argmode = "";
8838                                         break;
8839                                 case PROARGMODE_OUT:
8840                                         argmode = "OUT ";
8841                                         break;
8842                                 case PROARGMODE_INOUT:
8843                                         argmode = "INOUT ";
8844                                         break;
8845                                 default:
8846                                         write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
8847                                         argmode = "";
8848                                         break;
8849                         }
8850                 }
8851                 else
8852                         argmode = "";
8853
8854                 argname = argnames ? argnames[j] : (char *) NULL;
8855                 if (argname && argname[0] == '\0')
8856                         argname = NULL;
8857
8858                 appendPQExpBuffer(&fn, "%s%s%s%s%s",
8859                                                   (j > 0) ? ", " : "",
8860                                                   argmode,
8861                                                   argname ? fmtId(argname) : "",
8862                                                   argname ? " " : "",
8863                                                   typname);
8864                 free(typname);
8865         }
8866         appendPQExpBuffer(&fn, ")");
8867         return fn.data;
8868 }
8869
8870 /*
8871  * format_function_signature: generate function name and argument list
8872  *
8873  * This is like format_function_arguments_old except that only a minimal
8874  * list of input argument types is generated; this is sufficient to
8875  * reference the function, but not to define it.
8876  *
8877  * If honor_quotes is false then the function name is never quoted.
8878  * This is appropriate for use in TOC tags, but not in SQL commands.
8879  */
8880 static char *
8881 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
8882 {
8883         PQExpBufferData fn;
8884         int                     j;
8885
8886         initPQExpBuffer(&fn);
8887         if (honor_quotes)
8888                 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8889         else
8890                 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
8891         for (j = 0; j < finfo->nargs; j++)
8892         {
8893                 char       *typname;
8894
8895                 typname = getFormattedTypeName(fout, finfo->argtypes[j],
8896                                                                            zeroAsOpaque);
8897
8898                 appendPQExpBuffer(&fn, "%s%s",
8899                                                   (j > 0) ? ", " : "",
8900                                                   typname);
8901                 free(typname);
8902         }
8903         appendPQExpBuffer(&fn, ")");
8904         return fn.data;
8905 }
8906
8907
8908 /*
8909  * dumpFunc:
8910  *        dump out one function
8911  */
8912 static void
8913 dumpFunc(Archive *fout, FuncInfo *finfo)
8914 {
8915         PQExpBuffer query;
8916         PQExpBuffer q;
8917         PQExpBuffer delqry;
8918         PQExpBuffer labelq;
8919         PQExpBuffer asPart;
8920         PGresult   *res;
8921         char       *funcsig;            /* identity signature */
8922         char       *funcfullsig;        /* full signature */
8923         char       *funcsig_tag;
8924         char       *proretset;
8925         char       *prosrc;
8926         char       *probin;
8927         char       *funcargs;
8928         char       *funciargs;
8929         char       *funcresult;
8930         char       *proallargtypes;
8931         char       *proargmodes;
8932         char       *proargnames;
8933         char       *proiswindow;
8934         char       *provolatile;
8935         char       *proisstrict;
8936         char       *prosecdef;
8937         char       *proleakproof;
8938         char       *proconfig;
8939         char       *procost;
8940         char       *prorows;
8941         char       *lanname;
8942         char       *rettypename;
8943         int                     nallargs;
8944         char      **allargtypes = NULL;
8945         char      **argmodes = NULL;
8946         char      **argnames = NULL;
8947         char      **configitems = NULL;
8948         int                     nconfigitems = 0;
8949         int                     i;
8950
8951         /* Skip if not to be dumped */
8952         if (!finfo->dobj.dump || dataOnly)
8953                 return;
8954
8955         query = createPQExpBuffer();
8956         q = createPQExpBuffer();
8957         delqry = createPQExpBuffer();
8958         labelq = createPQExpBuffer();
8959         asPart = createPQExpBuffer();
8960
8961         /* Set proper schema search path so type references list correctly */
8962         selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
8963
8964         /* Fetch function-specific details */
8965         if (fout->remoteVersion >= 90200)
8966         {
8967                 /*
8968                  * proleakproof was added at v9.2
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                                                   "proleakproof, proconfig, procost, prorows, "
8977                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8978                                                   "FROM pg_catalog.pg_proc "
8979                                                   "WHERE oid = '%u'::pg_catalog.oid",
8980                                                   finfo->dobj.catId.oid);
8981         }
8982         else if (fout->remoteVersion >= 80400)
8983         {
8984                 /*
8985                  * In 8.4 and up we rely on pg_get_function_arguments and
8986                  * pg_get_function_result instead of examining proallargtypes etc.
8987                  */
8988                 appendPQExpBuffer(query,
8989                                                   "SELECT proretset, prosrc, probin, "
8990                                         "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8991                   "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8992                                          "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8993                                                   "proiswindow, provolatile, proisstrict, prosecdef, "
8994                                                   "false AS proleakproof, "
8995                                                   " proconfig, procost, prorows, "
8996                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8997                                                   "FROM pg_catalog.pg_proc "
8998                                                   "WHERE oid = '%u'::pg_catalog.oid",
8999                                                   finfo->dobj.catId.oid);
9000         }
9001         else if (fout->remoteVersion >= 80300)
9002         {
9003                 appendPQExpBuffer(query,
9004                                                   "SELECT proretset, prosrc, probin, "
9005                                                   "proallargtypes, proargmodes, proargnames, "
9006                                                   "false AS proiswindow, "
9007                                                   "provolatile, proisstrict, prosecdef, "
9008                                                   "false AS proleakproof, "
9009                                                   "proconfig, procost, prorows, "
9010                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9011                                                   "FROM pg_catalog.pg_proc "
9012                                                   "WHERE oid = '%u'::pg_catalog.oid",
9013                                                   finfo->dobj.catId.oid);
9014         }
9015         else if (fout->remoteVersion >= 80100)
9016         {
9017                 appendPQExpBuffer(query,
9018                                                   "SELECT proretset, prosrc, probin, "
9019                                                   "proallargtypes, proargmodes, proargnames, "
9020                                                   "false AS proiswindow, "
9021                                                   "provolatile, proisstrict, prosecdef, "
9022                                                   "false AS proleakproof, "
9023                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9024                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9025                                                   "FROM pg_catalog.pg_proc "
9026                                                   "WHERE oid = '%u'::pg_catalog.oid",
9027                                                   finfo->dobj.catId.oid);
9028         }
9029         else if (fout->remoteVersion >= 80000)
9030         {
9031                 appendPQExpBuffer(query,
9032                                                   "SELECT proretset, prosrc, probin, "
9033                                                   "null AS proallargtypes, "
9034                                                   "null AS proargmodes, "
9035                                                   "proargnames, "
9036                                                   "false AS proiswindow, "
9037                                                   "provolatile, proisstrict, prosecdef, "
9038                                                   "false AS proleakproof, "
9039                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9040                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9041                                                   "FROM pg_catalog.pg_proc "
9042                                                   "WHERE oid = '%u'::pg_catalog.oid",
9043                                                   finfo->dobj.catId.oid);
9044         }
9045         else if (fout->remoteVersion >= 70300)
9046         {
9047                 appendPQExpBuffer(query,
9048                                                   "SELECT proretset, prosrc, probin, "
9049                                                   "null AS proallargtypes, "
9050                                                   "null AS proargmodes, "
9051                                                   "null AS proargnames, "
9052                                                   "false AS proiswindow, "
9053                                                   "provolatile, proisstrict, prosecdef, "
9054                                                   "false AS proleakproof, "
9055                                                   "null AS proconfig, 0 AS procost, 0 AS prorows, "
9056                                                   "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9057                                                   "FROM pg_catalog.pg_proc "
9058                                                   "WHERE oid = '%u'::pg_catalog.oid",
9059                                                   finfo->dobj.catId.oid);
9060         }
9061         else if (fout->remoteVersion >= 70100)
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                                                   "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         else
9080         {
9081                 appendPQExpBuffer(query,
9082                                                   "SELECT proretset, prosrc, probin, "
9083                                                   "null AS proallargtypes, "
9084                                                   "null AS proargmodes, "
9085                                                   "null AS proargnames, "
9086                                                   "false AS proiswindow, "
9087                          "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9088                                                   "false AS proisstrict, "
9089                                                   "false AS prosecdef, "
9090                                                   "false AS proleakproof, "
9091                                                   "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9092                   "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9093                                                   "FROM pg_proc "
9094                                                   "WHERE oid = '%u'::oid",
9095                                                   finfo->dobj.catId.oid);
9096         }
9097
9098         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9099
9100         proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9101         prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9102         probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9103         if (fout->remoteVersion >= 80400)
9104         {
9105                 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9106                 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9107                 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9108                 proallargtypes = proargmodes = proargnames = NULL;
9109         }
9110         else
9111         {
9112                 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9113                 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9114                 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9115                 funcargs = funciargs = funcresult = NULL;
9116         }
9117         proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9118         provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9119         proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9120         prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9121         proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9122         proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9123         procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9124         prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9125         lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9126
9127         /*
9128          * See backend/commands/functioncmds.c for details of how the 'AS' clause
9129          * is used.  In 8.4 and up, an unused probin is NULL (here ""); previous
9130          * versions would set it to "-".  There are no known cases in which prosrc
9131          * is unused, so the tests below for "-" are probably useless.
9132          */
9133         if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9134         {
9135                 appendPQExpBuffer(asPart, "AS ");
9136                 appendStringLiteralAH(asPart, probin, fout);
9137                 if (strcmp(prosrc, "-") != 0)
9138                 {
9139                         appendPQExpBuffer(asPart, ", ");
9140
9141                         /*
9142                          * where we have bin, use dollar quoting if allowed and src
9143                          * contains quote or backslash; else use regular quoting.
9144                          */
9145                         if (disable_dollar_quoting ||
9146                           (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9147                                 appendStringLiteralAH(asPart, prosrc, fout);
9148                         else
9149                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9150                 }
9151         }
9152         else
9153         {
9154                 if (strcmp(prosrc, "-") != 0)
9155                 {
9156                         appendPQExpBuffer(asPart, "AS ");
9157                         /* with no bin, dollar quote src unconditionally if allowed */
9158                         if (disable_dollar_quoting)
9159                                 appendStringLiteralAH(asPart, prosrc, fout);
9160                         else
9161                                 appendStringLiteralDQ(asPart, prosrc, NULL);
9162                 }
9163         }
9164
9165         nallargs = finfo->nargs;        /* unless we learn different from allargs */
9166
9167         if (proallargtypes && *proallargtypes)
9168         {
9169                 int                     nitems = 0;
9170
9171                 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9172                         nitems < finfo->nargs)
9173                 {
9174                         write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9175                         if (allargtypes)
9176                                 free(allargtypes);
9177                         allargtypes = NULL;
9178                 }
9179                 else
9180                         nallargs = nitems;
9181         }
9182
9183         if (proargmodes && *proargmodes)
9184         {
9185                 int                     nitems = 0;
9186
9187                 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9188                         nitems != nallargs)
9189                 {
9190                         write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9191                         if (argmodes)
9192                                 free(argmodes);
9193                         argmodes = NULL;
9194                 }
9195         }
9196
9197         if (proargnames && *proargnames)
9198         {
9199                 int                     nitems = 0;
9200
9201                 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9202                         nitems != nallargs)
9203                 {
9204                         write_msg(NULL, "WARNING: could not parse proargnames array\n");
9205                         if (argnames)
9206                                 free(argnames);
9207                         argnames = NULL;
9208                 }
9209         }
9210
9211         if (proconfig && *proconfig)
9212         {
9213                 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9214                 {
9215                         write_msg(NULL, "WARNING: could not parse proconfig array\n");
9216                         if (configitems)
9217                                 free(configitems);
9218                         configitems = NULL;
9219                         nconfigitems = 0;
9220                 }
9221         }
9222
9223         if (funcargs)
9224         {
9225                 /* 8.4 or later; we rely on server-side code for most of the work */
9226                 funcfullsig = format_function_arguments(finfo, funcargs);
9227                 funcsig = format_function_arguments(finfo, funciargs);
9228         }
9229         else
9230         {
9231                 /* pre-8.4, do it ourselves */
9232                 funcsig = format_function_arguments_old(fout,
9233                                                                                                 finfo, nallargs, allargtypes,
9234                                                                                                 argmodes, argnames);
9235                 funcfullsig = funcsig;
9236         }
9237
9238         funcsig_tag = format_function_signature(fout, finfo, false);
9239
9240         /*
9241          * DROP must be fully qualified in case same name appears in pg_catalog
9242          */
9243         appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9244                                           fmtId(finfo->dobj.namespace->dobj.name),
9245                                           funcsig);
9246
9247         appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9248         if (funcresult)
9249                 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9250         else
9251         {
9252                 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9253                                                                                    zeroAsOpaque);
9254                 appendPQExpBuffer(q, "RETURNS %s%s",
9255                                                   (proretset[0] == 't') ? "SETOF " : "",
9256                                                   rettypename);
9257                 free(rettypename);
9258         }
9259
9260         appendPQExpBuffer(q, "\n    LANGUAGE %s", fmtId(lanname));
9261
9262         if (proiswindow[0] == 't')
9263                 appendPQExpBuffer(q, " WINDOW");
9264
9265         if (provolatile[0] != PROVOLATILE_VOLATILE)
9266         {
9267                 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9268                         appendPQExpBuffer(q, " IMMUTABLE");
9269                 else if (provolatile[0] == PROVOLATILE_STABLE)
9270                         appendPQExpBuffer(q, " STABLE");
9271                 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9272                         exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9273                                                   finfo->dobj.name);
9274         }
9275
9276         if (proisstrict[0] == 't')
9277                 appendPQExpBuffer(q, " STRICT");
9278
9279         if (prosecdef[0] == 't')
9280                 appendPQExpBuffer(q, " SECURITY DEFINER");
9281
9282         if (proleakproof[0] == 't')
9283                 appendPQExpBuffer(q, " LEAKPROOF");
9284
9285         /*
9286          * COST and ROWS are emitted only if present and not default, so as not to
9287          * break backwards-compatibility of the dump without need.      Keep this code
9288          * in sync with the defaults in functioncmds.c.
9289          */
9290         if (strcmp(procost, "0") != 0)
9291         {
9292                 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9293                 {
9294                         /* default cost is 1 */
9295                         if (strcmp(procost, "1") != 0)
9296                                 appendPQExpBuffer(q, " COST %s", procost);
9297                 }
9298                 else
9299                 {
9300                         /* default cost is 100 */
9301                         if (strcmp(procost, "100") != 0)
9302                                 appendPQExpBuffer(q, " COST %s", procost);
9303                 }
9304         }
9305         if (proretset[0] == 't' &&
9306                 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9307                 appendPQExpBuffer(q, " ROWS %s", prorows);
9308
9309         for (i = 0; i < nconfigitems; i++)
9310         {
9311                 /* we feel free to scribble on configitems[] here */
9312                 char       *configitem = configitems[i];
9313                 char       *pos;
9314
9315                 pos = strchr(configitem, '=');
9316                 if (pos == NULL)
9317                         continue;
9318                 *pos++ = '\0';
9319                 appendPQExpBuffer(q, "\n    SET %s TO ", fmtId(configitem));
9320
9321                 /*
9322                  * Some GUC variable names are 'LIST' type and hence must not be
9323                  * quoted.
9324                  */
9325                 if (pg_strcasecmp(configitem, "DateStyle") == 0
9326                         || pg_strcasecmp(configitem, "search_path") == 0)
9327                         appendPQExpBuffer(q, "%s", pos);
9328                 else
9329                         appendStringLiteralAH(q, pos, fout);
9330         }
9331
9332         appendPQExpBuffer(q, "\n    %s;\n", asPart->data);
9333
9334         appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9335
9336         if (binary_upgrade)
9337                 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9338
9339         ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9340                                  funcsig_tag,
9341                                  finfo->dobj.namespace->dobj.name,
9342                                  NULL,
9343                                  finfo->rolname, false,
9344                                  "FUNCTION", SECTION_PRE_DATA,
9345                                  q->data, delqry->data, NULL,
9346                                  finfo->dobj.dependencies, finfo->dobj.nDeps,
9347                                  NULL, NULL);
9348
9349         /* Dump Function Comments and Security Labels */
9350         dumpComment(fout, labelq->data,
9351                                 finfo->dobj.namespace->dobj.name, finfo->rolname,
9352                                 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9353         dumpSecLabel(fout, labelq->data,
9354                                  finfo->dobj.namespace->dobj.name, finfo->rolname,
9355                                  finfo->dobj.catId, 0, finfo->dobj.dumpId);
9356
9357         dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9358                         funcsig, NULL, funcsig_tag,
9359                         finfo->dobj.namespace->dobj.name,
9360                         finfo->rolname, finfo->proacl);
9361
9362         PQclear(res);
9363
9364         destroyPQExpBuffer(query);
9365         destroyPQExpBuffer(q);
9366         destroyPQExpBuffer(delqry);
9367         destroyPQExpBuffer(labelq);
9368         destroyPQExpBuffer(asPart);
9369         free(funcsig);
9370         free(funcsig_tag);
9371         if (allargtypes)
9372                 free(allargtypes);
9373         if (argmodes)
9374                 free(argmodes);
9375         if (argnames)
9376                 free(argnames);
9377         if (configitems)
9378                 free(configitems);
9379 }
9380
9381
9382 /*
9383  * Dump a user-defined cast
9384  */
9385 static void
9386 dumpCast(Archive *fout, CastInfo *cast)
9387 {
9388         PQExpBuffer defqry;
9389         PQExpBuffer delqry;
9390         PQExpBuffer labelq;
9391         FuncInfo   *funcInfo = NULL;
9392
9393         /* Skip if not to be dumped */
9394         if (!cast->dobj.dump || dataOnly)
9395                 return;
9396
9397         /* Cannot dump if we don't have the cast function's info */
9398         if (OidIsValid(cast->castfunc))
9399         {
9400                 funcInfo = findFuncByOid(cast->castfunc);
9401                 if (funcInfo == NULL)
9402                         return;
9403         }
9404
9405         /*
9406          * As per discussion we dump casts if one or more of the underlying
9407          * objects (the conversion function and the two data types) are not
9408          * builtin AND if all of the non-builtin objects are included in the dump.
9409          * Builtin meaning, the namespace name does not start with "pg_".
9410          *
9411          * However, for a cast that belongs to an extension, we must not use this
9412          * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9413          */
9414         if (!cast->dobj.ext_member)
9415         {
9416                 TypeInfo   *sourceInfo = findTypeByOid(cast->castsource);
9417                 TypeInfo   *targetInfo = findTypeByOid(cast->casttarget);
9418
9419                 if (sourceInfo == NULL || targetInfo == NULL)
9420                         return;
9421
9422                 /*
9423                  * Skip this cast if all objects are from pg_
9424                  */
9425                 if ((funcInfo == NULL ||
9426                          strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9427                         strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9428                         strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9429                         return;
9430
9431                 /*
9432                  * Skip cast if function isn't from pg_ and is not to be dumped.
9433                  */
9434                 if (funcInfo &&
9435                         strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9436                         !funcInfo->dobj.dump)
9437                         return;
9438
9439                 /*
9440                  * Same for the source type
9441                  */
9442                 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9443                         !sourceInfo->dobj.dump)
9444                         return;
9445
9446                 /*
9447                  * and the target type.
9448                  */
9449                 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9450                         !targetInfo->dobj.dump)
9451                         return;
9452         }
9453
9454         /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9455         selectSourceSchema(fout, "pg_catalog");
9456
9457         defqry = createPQExpBuffer();
9458         delqry = createPQExpBuffer();
9459         labelq = createPQExpBuffer();
9460
9461         appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9462                                   getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9463                                   getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9464
9465         appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9466                                   getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9467                                   getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9468
9469         switch (cast->castmethod)
9470         {
9471                 case COERCION_METHOD_BINARY:
9472                         appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9473                         break;
9474                 case COERCION_METHOD_INOUT:
9475                         appendPQExpBuffer(defqry, "WITH INOUT");
9476                         break;
9477                 case COERCION_METHOD_FUNCTION:
9478                         if (funcInfo)
9479                         {
9480                                 char   *fsig = format_function_signature(fout, funcInfo, true);
9481
9482                                 /*
9483                                  * Always qualify the function name, in case it is not in
9484                                  * pg_catalog schema (format_function_signature won't qualify it).
9485                                  */
9486                                 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
9487                                                                   fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
9488                                 free(fsig);
9489                         }
9490                         else
9491                                 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
9492                         break;
9493                 default:
9494                         write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9495         }
9496
9497         if (cast->castcontext == 'a')
9498                 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9499         else if (cast->castcontext == 'i')
9500                 appendPQExpBuffer(defqry, " AS IMPLICIT");
9501         appendPQExpBuffer(defqry, ";\n");
9502
9503         appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9504                                   getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9505                                   getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9506
9507         if (binary_upgrade)
9508                 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9509
9510         ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9511                                  labelq->data,
9512                                  "pg_catalog", NULL, "",
9513                                  false, "CAST", SECTION_PRE_DATA,
9514                                  defqry->data, delqry->data, NULL,
9515                                  cast->dobj.dependencies, cast->dobj.nDeps,
9516                                  NULL, NULL);
9517
9518         /* Dump Cast Comments */
9519         dumpComment(fout, labelq->data,
9520                                 NULL, "",
9521                                 cast->dobj.catId, 0, cast->dobj.dumpId);
9522
9523         destroyPQExpBuffer(defqry);
9524         destroyPQExpBuffer(delqry);
9525         destroyPQExpBuffer(labelq);
9526 }
9527
9528 /*
9529  * dumpOpr
9530  *        write out a single operator definition
9531  */
9532 static void
9533 dumpOpr(Archive *fout, OprInfo *oprinfo)
9534 {
9535         PQExpBuffer query;
9536         PQExpBuffer q;
9537         PQExpBuffer delq;
9538         PQExpBuffer labelq;
9539         PQExpBuffer oprid;
9540         PQExpBuffer details;
9541         const char *name;
9542         PGresult   *res;
9543         int                     i_oprkind;
9544         int                     i_oprcode;
9545         int                     i_oprleft;
9546         int                     i_oprright;
9547         int                     i_oprcom;
9548         int                     i_oprnegate;
9549         int                     i_oprrest;
9550         int                     i_oprjoin;
9551         int                     i_oprcanmerge;
9552         int                     i_oprcanhash;
9553         char       *oprkind;
9554         char       *oprcode;
9555         char       *oprleft;
9556         char       *oprright;
9557         char       *oprcom;
9558         char       *oprnegate;
9559         char       *oprrest;
9560         char       *oprjoin;
9561         char       *oprcanmerge;
9562         char       *oprcanhash;
9563
9564         /* Skip if not to be dumped */
9565         if (!oprinfo->dobj.dump || dataOnly)
9566                 return;
9567
9568         /*
9569          * some operators are invalid because they were the result of user
9570          * defining operators before commutators exist
9571          */
9572         if (!OidIsValid(oprinfo->oprcode))
9573                 return;
9574
9575         query = createPQExpBuffer();
9576         q = createPQExpBuffer();
9577         delq = createPQExpBuffer();
9578         labelq = createPQExpBuffer();
9579         oprid = createPQExpBuffer();
9580         details = createPQExpBuffer();
9581
9582         /* Make sure we are in proper schema so regoperator works correctly */
9583         selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
9584
9585         if (fout->remoteVersion >= 80300)
9586         {
9587                 appendPQExpBuffer(query, "SELECT oprkind, "
9588                                                   "oprcode::pg_catalog.regprocedure, "
9589                                                   "oprleft::pg_catalog.regtype, "
9590                                                   "oprright::pg_catalog.regtype, "
9591                                                   "oprcom::pg_catalog.regoperator, "
9592                                                   "oprnegate::pg_catalog.regoperator, "
9593                                                   "oprrest::pg_catalog.regprocedure, "
9594                                                   "oprjoin::pg_catalog.regprocedure, "
9595                                                   "oprcanmerge, oprcanhash "
9596                                                   "FROM pg_catalog.pg_operator "
9597                                                   "WHERE oid = '%u'::pg_catalog.oid",
9598                                                   oprinfo->dobj.catId.oid);
9599         }
9600         else if (fout->remoteVersion >= 70300)
9601         {
9602                 appendPQExpBuffer(query, "SELECT oprkind, "
9603                                                   "oprcode::pg_catalog.regprocedure, "
9604                                                   "oprleft::pg_catalog.regtype, "
9605                                                   "oprright::pg_catalog.regtype, "
9606                                                   "oprcom::pg_catalog.regoperator, "
9607                                                   "oprnegate::pg_catalog.regoperator, "
9608                                                   "oprrest::pg_catalog.regprocedure, "
9609                                                   "oprjoin::pg_catalog.regprocedure, "
9610                                                   "(oprlsortop != 0) AS oprcanmerge, "
9611                                                   "oprcanhash "
9612                                                   "FROM pg_catalog.pg_operator "
9613                                                   "WHERE oid = '%u'::pg_catalog.oid",
9614                                                   oprinfo->dobj.catId.oid);
9615         }
9616         else if (fout->remoteVersion >= 70100)
9617         {
9618                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9619                                                   "CASE WHEN oprleft = 0 THEN '-' "
9620                                                   "ELSE format_type(oprleft, NULL) END AS oprleft, "
9621                                                   "CASE WHEN oprright = 0 THEN '-' "
9622                                                   "ELSE format_type(oprright, NULL) END AS oprright, "
9623                                                   "oprcom, oprnegate, oprrest, oprjoin, "
9624                                                   "(oprlsortop != 0) AS oprcanmerge, "
9625                                                   "oprcanhash "
9626                                                   "FROM pg_operator "
9627                                                   "WHERE oid = '%u'::oid",
9628                                                   oprinfo->dobj.catId.oid);
9629         }
9630         else
9631         {
9632                 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9633                                                   "CASE WHEN oprleft = 0 THEN '-'::name "
9634                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
9635                                                   "CASE WHEN oprright = 0 THEN '-'::name "
9636                                                   "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
9637                                                   "oprcom, oprnegate, oprrest, oprjoin, "
9638                                                   "(oprlsortop != 0) AS oprcanmerge, "
9639                                                   "oprcanhash "
9640                                                   "FROM pg_operator "
9641                                                   "WHERE oid = '%u'::oid",
9642                                                   oprinfo->dobj.catId.oid);
9643         }
9644
9645         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9646
9647         i_oprkind = PQfnumber(res, "oprkind");
9648         i_oprcode = PQfnumber(res, "oprcode");
9649         i_oprleft = PQfnumber(res, "oprleft");
9650         i_oprright = PQfnumber(res, "oprright");
9651         i_oprcom = PQfnumber(res, "oprcom");
9652         i_oprnegate = PQfnumber(res, "oprnegate");
9653         i_oprrest = PQfnumber(res, "oprrest");
9654         i_oprjoin = PQfnumber(res, "oprjoin");
9655         i_oprcanmerge = PQfnumber(res, "oprcanmerge");
9656         i_oprcanhash = PQfnumber(res, "oprcanhash");
9657
9658         oprkind = PQgetvalue(res, 0, i_oprkind);
9659         oprcode = PQgetvalue(res, 0, i_oprcode);
9660         oprleft = PQgetvalue(res, 0, i_oprleft);
9661         oprright = PQgetvalue(res, 0, i_oprright);
9662         oprcom = PQgetvalue(res, 0, i_oprcom);
9663         oprnegate = PQgetvalue(res, 0, i_oprnegate);
9664         oprrest = PQgetvalue(res, 0, i_oprrest);
9665         oprjoin = PQgetvalue(res, 0, i_oprjoin);
9666         oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
9667         oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
9668
9669         appendPQExpBuffer(details, "    PROCEDURE = %s",
9670                                           convertRegProcReference(fout, oprcode));
9671
9672         appendPQExpBuffer(oprid, "%s (",
9673                                           oprinfo->dobj.name);
9674
9675         /*
9676          * right unary means there's a left arg and left unary means there's a
9677          * right arg
9678          */
9679         if (strcmp(oprkind, "r") == 0 ||
9680                 strcmp(oprkind, "b") == 0)
9681         {
9682                 if (fout->remoteVersion >= 70100)
9683                         name = oprleft;
9684                 else
9685                         name = fmtId(oprleft);
9686                 appendPQExpBuffer(details, ",\n    LEFTARG = %s", name);
9687                 appendPQExpBuffer(oprid, "%s", name);
9688         }
9689         else
9690                 appendPQExpBuffer(oprid, "NONE");
9691
9692         if (strcmp(oprkind, "l") == 0 ||
9693                 strcmp(oprkind, "b") == 0)
9694         {
9695                 if (fout->remoteVersion >= 70100)
9696                         name = oprright;
9697                 else
9698                         name = fmtId(oprright);
9699                 appendPQExpBuffer(details, ",\n    RIGHTARG = %s", name);
9700                 appendPQExpBuffer(oprid, ", %s)", name);
9701         }
9702         else
9703                 appendPQExpBuffer(oprid, ", NONE)");
9704
9705         name = convertOperatorReference(fout, oprcom);
9706         if (name)
9707                 appendPQExpBuffer(details, ",\n    COMMUTATOR = %s", name);
9708
9709         name = convertOperatorReference(fout, oprnegate);
9710         if (name)
9711                 appendPQExpBuffer(details, ",\n    NEGATOR = %s", name);
9712
9713         if (strcmp(oprcanmerge, "t") == 0)
9714                 appendPQExpBuffer(details, ",\n    MERGES");
9715
9716         if (strcmp(oprcanhash, "t") == 0)
9717                 appendPQExpBuffer(details, ",\n    HASHES");
9718
9719         name = convertRegProcReference(fout, oprrest);
9720         if (name)
9721                 appendPQExpBuffer(details, ",\n    RESTRICT = %s", name);
9722
9723         name = convertRegProcReference(fout, oprjoin);
9724         if (name)
9725                 appendPQExpBuffer(details, ",\n    JOIN = %s", name);
9726
9727         /*
9728          * DROP must be fully qualified in case same name appears in pg_catalog
9729          */
9730         appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
9731                                           fmtId(oprinfo->dobj.namespace->dobj.name),
9732                                           oprid->data);
9733
9734         appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
9735                                           oprinfo->dobj.name, details->data);
9736
9737         appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
9738
9739         if (binary_upgrade)
9740                 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
9741
9742         ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
9743                                  oprinfo->dobj.name,
9744                                  oprinfo->dobj.namespace->dobj.name,
9745                                  NULL,
9746                                  oprinfo->rolname,
9747                                  false, "OPERATOR", SECTION_PRE_DATA,
9748                                  q->data, delq->data, NULL,
9749                                  oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
9750                                  NULL, NULL);
9751
9752         /* Dump Operator Comments */
9753         dumpComment(fout, labelq->data,
9754                                 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
9755                                 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
9756
9757         PQclear(res);
9758
9759         destroyPQExpBuffer(query);
9760         destroyPQExpBuffer(q);
9761         destroyPQExpBuffer(delq);
9762         destroyPQExpBuffer(labelq);
9763         destroyPQExpBuffer(oprid);
9764         destroyPQExpBuffer(details);
9765 }
9766
9767 /*
9768  * Convert a function reference obtained from pg_operator
9769  *
9770  * Returns what to print, or NULL if function references is InvalidOid
9771  *
9772  * In 7.3 the input is a REGPROCEDURE display; we have to strip the
9773  * argument-types part.  In prior versions, the input is a REGPROC display.
9774  */
9775 static const char *
9776 convertRegProcReference(Archive *fout, const char *proc)
9777 {
9778         /* In all cases "-" means a null reference */
9779         if (strcmp(proc, "-") == 0)
9780                 return NULL;
9781
9782         if (fout->remoteVersion >= 70300)
9783         {
9784                 char       *name;
9785                 char       *paren;
9786                 bool            inquote;
9787
9788                 name = pg_strdup(proc);
9789                 /* find non-double-quoted left paren */
9790                 inquote = false;
9791                 for (paren = name; *paren; paren++)
9792                 {
9793                         if (*paren == '(' && !inquote)
9794                         {
9795                                 *paren = '\0';
9796                                 break;
9797                         }
9798                         if (*paren == '"')
9799                                 inquote = !inquote;
9800                 }
9801                 return name;
9802         }
9803
9804         /* REGPROC before 7.3 does not quote its result */
9805         return fmtId(proc);
9806 }
9807
9808 /*
9809  * Convert an operator cross-reference obtained from pg_operator
9810  *
9811  * Returns what to print, or NULL to print nothing
9812  *
9813  * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
9814  * argument-types part, and add OPERATOR() decoration if the name is
9815  * schema-qualified.  In older versions, the input is just a numeric OID,
9816  * which we search our operator list for.
9817  */
9818 static const char *
9819 convertOperatorReference(Archive *fout, const char *opr)
9820 {
9821         OprInfo    *oprInfo;
9822
9823         /* In all cases "0" means a null reference */
9824         if (strcmp(opr, "0") == 0)
9825                 return NULL;
9826
9827         if (fout->remoteVersion >= 70300)
9828         {
9829                 char       *name;
9830                 char       *oname;
9831                 char       *ptr;
9832                 bool            inquote;
9833                 bool            sawdot;
9834
9835                 name = pg_strdup(opr);
9836                 /* find non-double-quoted left paren, and check for non-quoted dot */
9837                 inquote = false;
9838                 sawdot = false;
9839                 for (ptr = name; *ptr; ptr++)
9840                 {
9841                         if (*ptr == '"')
9842                                 inquote = !inquote;
9843                         else if (*ptr == '.' && !inquote)
9844                                 sawdot = true;
9845                         else if (*ptr == '(' && !inquote)
9846                         {
9847                                 *ptr = '\0';
9848                                 break;
9849                         }
9850                 }
9851                 /* If not schema-qualified, don't need to add OPERATOR() */
9852                 if (!sawdot)
9853                         return name;
9854                 oname = pg_malloc(strlen(name) + 11);
9855                 sprintf(oname, "OPERATOR(%s)", name);
9856                 free(name);
9857                 return oname;
9858         }
9859
9860         oprInfo = findOprByOid(atooid(opr));
9861         if (oprInfo == NULL)
9862         {
9863                 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
9864                                   opr);
9865                 return NULL;
9866         }
9867         return oprInfo->dobj.name;
9868 }
9869
9870 /*
9871  * Convert a function OID obtained from pg_ts_parser or pg_ts_template
9872  *
9873  * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
9874  * argument lists of these functions are predetermined.  Note that the
9875  * caller should ensure we are in the proper schema, because the results
9876  * are search path dependent!
9877  */
9878 static const char *
9879 convertTSFunction(Archive *fout, Oid funcOid)
9880 {
9881         char       *result;
9882         char            query[128];
9883         PGresult   *res;
9884
9885         snprintf(query, sizeof(query),
9886                          "SELECT '%u'::pg_catalog.regproc", funcOid);
9887         res = ExecuteSqlQueryForSingleRow(fout, query);
9888
9889         result = pg_strdup(PQgetvalue(res, 0, 0));
9890
9891         PQclear(res);
9892
9893         return result;
9894 }
9895
9896
9897 /*
9898  * dumpOpclass
9899  *        write out a single operator class definition
9900  */
9901 static void
9902 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
9903 {
9904         PQExpBuffer query;
9905         PQExpBuffer q;
9906         PQExpBuffer delq;
9907         PQExpBuffer labelq;
9908         PGresult   *res;
9909         int                     ntups;
9910         int                     i_opcintype;
9911         int                     i_opckeytype;
9912         int                     i_opcdefault;
9913         int                     i_opcfamily;
9914         int                     i_opcfamilyname;
9915         int                     i_opcfamilynsp;
9916         int                     i_amname;
9917         int                     i_amopstrategy;
9918         int                     i_amopreqcheck;
9919         int                     i_amopopr;
9920         int                     i_sortfamily;
9921         int                     i_sortfamilynsp;
9922         int                     i_amprocnum;
9923         int                     i_amproc;
9924         int                     i_amproclefttype;
9925         int                     i_amprocrighttype;
9926         char       *opcintype;
9927         char       *opckeytype;
9928         char       *opcdefault;
9929         char       *opcfamily;
9930         char       *opcfamilyname;
9931         char       *opcfamilynsp;
9932         char       *amname;
9933         char       *amopstrategy;
9934         char       *amopreqcheck;
9935         char       *amopopr;
9936         char       *sortfamily;
9937         char       *sortfamilynsp;
9938         char       *amprocnum;
9939         char       *amproc;
9940         char       *amproclefttype;
9941         char       *amprocrighttype;
9942         bool            needComma;
9943         int                     i;
9944
9945         /* Skip if not to be dumped */
9946         if (!opcinfo->dobj.dump || dataOnly)
9947                 return;
9948
9949         /*
9950          * XXX currently we do not implement dumping of operator classes from
9951          * pre-7.3 databases.  This could be done but it seems not worth the
9952          * trouble.
9953          */
9954         if (fout->remoteVersion < 70300)
9955                 return;
9956
9957         query = createPQExpBuffer();
9958         q = createPQExpBuffer();
9959         delq = createPQExpBuffer();
9960         labelq = createPQExpBuffer();
9961
9962         /* Make sure we are in proper schema so regoperator works correctly */
9963         selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
9964
9965         /* Get additional fields from the pg_opclass row */
9966         if (fout->remoteVersion >= 80300)
9967         {
9968                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9969                                                   "opckeytype::pg_catalog.regtype, "
9970                                                   "opcdefault, opcfamily, "
9971                                                   "opfname AS opcfamilyname, "
9972                                                   "nspname AS opcfamilynsp, "
9973                                                   "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
9974                                                   "FROM pg_catalog.pg_opclass c "
9975                                    "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
9976                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
9977                                                   "WHERE c.oid = '%u'::pg_catalog.oid",
9978                                                   opcinfo->dobj.catId.oid);
9979         }
9980         else
9981         {
9982                 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9983                                                   "opckeytype::pg_catalog.regtype, "
9984                                                   "opcdefault, NULL AS opcfamily, "
9985                                                   "NULL AS opcfamilyname, "
9986                                                   "NULL AS opcfamilynsp, "
9987                 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
9988                                                   "FROM pg_catalog.pg_opclass "
9989                                                   "WHERE oid = '%u'::pg_catalog.oid",
9990                                                   opcinfo->dobj.catId.oid);
9991         }
9992
9993         res = ExecuteSqlQueryForSingleRow(fout, query->data);
9994
9995         i_opcintype = PQfnumber(res, "opcintype");
9996         i_opckeytype = PQfnumber(res, "opckeytype");
9997         i_opcdefault = PQfnumber(res, "opcdefault");
9998         i_opcfamily = PQfnumber(res, "opcfamily");
9999         i_opcfamilyname = PQfnumber(res, "opcfamilyname");
10000         i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
10001         i_amname = PQfnumber(res, "amname");
10002
10003         opcintype = PQgetvalue(res, 0, i_opcintype);
10004         opckeytype = PQgetvalue(res, 0, i_opckeytype);
10005         opcdefault = PQgetvalue(res, 0, i_opcdefault);
10006         /* opcfamily will still be needed after we PQclear res */
10007         opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
10008         opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
10009         opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10010         /* amname will still be needed after we PQclear res */
10011         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10012
10013         /*
10014          * DROP must be fully qualified in case same name appears in pg_catalog
10015          */
10016         appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10017                                           fmtId(opcinfo->dobj.namespace->dobj.name));
10018         appendPQExpBuffer(delq, ".%s",
10019                                           fmtId(opcinfo->dobj.name));
10020         appendPQExpBuffer(delq, " USING %s;\n",
10021                                           fmtId(amname));
10022
10023         /* Build the fixed portion of the CREATE command */
10024         appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n    ",
10025                                           fmtId(opcinfo->dobj.name));
10026         if (strcmp(opcdefault, "t") == 0)
10027                 appendPQExpBuffer(q, "DEFAULT ");
10028         appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10029                                           opcintype,
10030                                           fmtId(amname));
10031         if (strlen(opcfamilyname) > 0 &&
10032                 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10033                  strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10034         {
10035                 appendPQExpBuffer(q, " FAMILY ");
10036                 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10037                         appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10038                 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10039         }
10040         appendPQExpBuffer(q, " AS\n    ");
10041
10042         needComma = false;
10043
10044         if (strcmp(opckeytype, "-") != 0)
10045         {
10046                 appendPQExpBuffer(q, "STORAGE %s",
10047                                                   opckeytype);
10048                 needComma = true;
10049         }
10050
10051         PQclear(res);
10052
10053         /*
10054          * Now fetch and print the OPERATOR entries (pg_amop rows).
10055          *
10056          * Print only those opfamily members that are tied to the opclass by
10057          * pg_depend entries.
10058          *
10059          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10060          * older server's opclass in which it is used.  This is to avoid
10061          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10062          * older server and then reload into that old version.  This can go away
10063          * once 8.3 is so old as to not be of interest to anyone.
10064          */
10065         resetPQExpBuffer(query);
10066
10067         if (fout->remoteVersion >= 90100)
10068         {
10069                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10070                                                   "amopopr::pg_catalog.regoperator, "
10071                                                   "opfname AS sortfamily, "
10072                                                   "nspname AS sortfamilynsp "
10073                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10074                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10075                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10076                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10077                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10078                                                   "AND refobjid = '%u'::pg_catalog.oid "
10079                                                   "AND amopfamily = '%s'::pg_catalog.oid "
10080                                                   "ORDER BY amopstrategy",
10081                                                   opcinfo->dobj.catId.oid,
10082                                                   opcfamily);
10083         }
10084         else if (fout->remoteVersion >= 80400)
10085         {
10086                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10087                                                   "amopopr::pg_catalog.regoperator, "
10088                                                   "NULL AS sortfamily, "
10089                                                   "NULL AS sortfamilynsp "
10090                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10091                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10092                                                   "AND refobjid = '%u'::pg_catalog.oid "
10093                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10094                                                   "AND objid = ao.oid "
10095                                                   "ORDER BY amopstrategy",
10096                                                   opcinfo->dobj.catId.oid);
10097         }
10098         else if (fout->remoteVersion >= 80300)
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 ao, pg_catalog.pg_depend "
10105                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10106                                                   "AND refobjid = '%u'::pg_catalog.oid "
10107                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10108                                                   "AND objid = ao.oid "
10109                                                   "ORDER BY amopstrategy",
10110                                                   opcinfo->dobj.catId.oid);
10111         }
10112         else
10113         {
10114                 /*
10115                  * Here, we print all entries since there are no opfamilies and hence
10116                  * no loose operators to worry about.
10117                  */
10118                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10119                                                   "amopopr::pg_catalog.regoperator, "
10120                                                   "NULL AS sortfamily, "
10121                                                   "NULL AS sortfamilynsp "
10122                                                   "FROM pg_catalog.pg_amop "
10123                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10124                                                   "ORDER BY amopstrategy",
10125                                                   opcinfo->dobj.catId.oid);
10126         }
10127
10128         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10129
10130         ntups = PQntuples(res);
10131
10132         i_amopstrategy = PQfnumber(res, "amopstrategy");
10133         i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10134         i_amopopr = PQfnumber(res, "amopopr");
10135         i_sortfamily = PQfnumber(res, "sortfamily");
10136         i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10137
10138         for (i = 0; i < ntups; i++)
10139         {
10140                 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10141                 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10142                 amopopr = PQgetvalue(res, i, i_amopopr);
10143                 sortfamily = PQgetvalue(res, i, i_sortfamily);
10144                 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10145
10146                 if (needComma)
10147                         appendPQExpBuffer(q, " ,\n    ");
10148
10149                 appendPQExpBuffer(q, "OPERATOR %s %s",
10150                                                   amopstrategy, amopopr);
10151
10152                 if (strlen(sortfamily) > 0)
10153                 {
10154                         appendPQExpBuffer(q, " FOR ORDER BY ");
10155                         if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10156                                 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10157                         appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10158                 }
10159
10160                 if (strcmp(amopreqcheck, "t") == 0)
10161                         appendPQExpBuffer(q, " RECHECK");
10162
10163                 needComma = true;
10164         }
10165
10166         PQclear(res);
10167
10168         /*
10169          * Now fetch and print the FUNCTION entries (pg_amproc rows).
10170          *
10171          * Print only those opfamily members that are tied to the opclass by
10172          * pg_depend entries.
10173          *
10174          * We print the amproclefttype/amprocrighttype even though in most cases
10175          * the backend could deduce the right values, because of the corner case
10176          * of a btree sort support function for a cross-type comparison.  That's
10177          * only allowed in 9.2 and later, but for simplicity print them in all
10178          * versions that have the columns.
10179          */
10180         resetPQExpBuffer(query);
10181
10182         if (fout->remoteVersion >= 80300)
10183         {
10184                 appendPQExpBuffer(query, "SELECT amprocnum, "
10185                                                   "amproc::pg_catalog.regprocedure, "
10186                                                   "amproclefttype::pg_catalog.regtype, "
10187                                                   "amprocrighttype::pg_catalog.regtype "
10188                                                 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10189                    "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10190                                                   "AND refobjid = '%u'::pg_catalog.oid "
10191                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10192                                                   "AND objid = ap.oid "
10193                                                   "ORDER BY amprocnum",
10194                                                   opcinfo->dobj.catId.oid);
10195         }
10196         else
10197         {
10198                 appendPQExpBuffer(query, "SELECT amprocnum, "
10199                                                   "amproc::pg_catalog.regprocedure, "
10200                                                   "'' AS amproclefttype, "
10201                                                   "'' AS amprocrighttype "
10202                                                   "FROM pg_catalog.pg_amproc "
10203                                                   "WHERE amopclaid = '%u'::pg_catalog.oid "
10204                                                   "ORDER BY amprocnum",
10205                                                   opcinfo->dobj.catId.oid);
10206         }
10207
10208         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10209
10210         ntups = PQntuples(res);
10211
10212         i_amprocnum = PQfnumber(res, "amprocnum");
10213         i_amproc = PQfnumber(res, "amproc");
10214         i_amproclefttype = PQfnumber(res, "amproclefttype");
10215         i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10216
10217         for (i = 0; i < ntups; i++)
10218         {
10219                 amprocnum = PQgetvalue(res, i, i_amprocnum);
10220                 amproc = PQgetvalue(res, i, i_amproc);
10221                 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10222                 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10223
10224                 if (needComma)
10225                         appendPQExpBuffer(q, " ,\n    ");
10226
10227                 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10228
10229                 if (*amproclefttype && *amprocrighttype)
10230                         appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10231
10232                 appendPQExpBuffer(q, " %s", amproc);
10233
10234                 needComma = true;
10235         }
10236
10237         PQclear(res);
10238
10239         appendPQExpBuffer(q, ";\n");
10240
10241         appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10242                                           fmtId(opcinfo->dobj.name));
10243         appendPQExpBuffer(labelq, " USING %s",
10244                                           fmtId(amname));
10245
10246         if (binary_upgrade)
10247                 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10248
10249         ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10250                                  opcinfo->dobj.name,
10251                                  opcinfo->dobj.namespace->dobj.name,
10252                                  NULL,
10253                                  opcinfo->rolname,
10254                                  false, "OPERATOR CLASS", SECTION_PRE_DATA,
10255                                  q->data, delq->data, NULL,
10256                                  opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
10257                                  NULL, NULL);
10258
10259         /* Dump Operator Class Comments */
10260         dumpComment(fout, labelq->data,
10261                                 NULL, opcinfo->rolname,
10262                                 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10263
10264         free(amname);
10265         destroyPQExpBuffer(query);
10266         destroyPQExpBuffer(q);
10267         destroyPQExpBuffer(delq);
10268         destroyPQExpBuffer(labelq);
10269 }
10270
10271 /*
10272  * dumpOpfamily
10273  *        write out a single operator family definition
10274  *
10275  * Note: this also dumps any "loose" operator members that aren't bound to a
10276  * specific opclass within the opfamily.
10277  */
10278 static void
10279 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10280 {
10281         PQExpBuffer query;
10282         PQExpBuffer q;
10283         PQExpBuffer delq;
10284         PQExpBuffer labelq;
10285         PGresult   *res;
10286         PGresult   *res_ops;
10287         PGresult   *res_procs;
10288         int                     ntups;
10289         int                     i_amname;
10290         int                     i_amopstrategy;
10291         int                     i_amopreqcheck;
10292         int                     i_amopopr;
10293         int                     i_sortfamily;
10294         int                     i_sortfamilynsp;
10295         int                     i_amprocnum;
10296         int                     i_amproc;
10297         int                     i_amproclefttype;
10298         int                     i_amprocrighttype;
10299         char       *amname;
10300         char       *amopstrategy;
10301         char       *amopreqcheck;
10302         char       *amopopr;
10303         char       *sortfamily;
10304         char       *sortfamilynsp;
10305         char       *amprocnum;
10306         char       *amproc;
10307         char       *amproclefttype;
10308         char       *amprocrighttype;
10309         bool            needComma;
10310         int                     i;
10311
10312         /* Skip if not to be dumped */
10313         if (!opfinfo->dobj.dump || dataOnly)
10314                 return;
10315
10316         /*
10317          * We want to dump the opfamily only if (1) it contains "loose" operators
10318          * or functions, or (2) it contains an opclass with a different name or
10319          * owner.  Otherwise it's sufficient to let it be created during creation
10320          * of the contained opclass, and not dumping it improves portability of
10321          * the dump.  Since we have to fetch the loose operators/funcs anyway, do
10322          * that first.
10323          */
10324
10325         query = createPQExpBuffer();
10326         q = createPQExpBuffer();
10327         delq = createPQExpBuffer();
10328         labelq = createPQExpBuffer();
10329
10330         /* Make sure we are in proper schema so regoperator works correctly */
10331         selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10332
10333         /*
10334          * Fetch only those opfamily members that are tied directly to the
10335          * opfamily by pg_depend entries.
10336          *
10337          * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10338          * older server's opclass in which it is used.  This is to avoid
10339          * hard-to-detect breakage if a newer pg_dump is used to dump from an
10340          * older server and then reload into that old version.  This can go away
10341          * once 8.3 is so old as to not be of interest to anyone.
10342          */
10343         if (fout->remoteVersion >= 90100)
10344         {
10345                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10346                                                   "amopopr::pg_catalog.regoperator, "
10347                                                   "opfname AS sortfamily, "
10348                                                   "nspname AS sortfamilynsp "
10349                                    "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10350                                                   "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10351                           "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10352                            "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10353                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10354                                                   "AND refobjid = '%u'::pg_catalog.oid "
10355                                                   "AND amopfamily = '%u'::pg_catalog.oid "
10356                                                   "ORDER BY amopstrategy",
10357                                                   opfinfo->dobj.catId.oid,
10358                                                   opfinfo->dobj.catId.oid);
10359         }
10360         else if (fout->remoteVersion >= 80400)
10361         {
10362                 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10363                                                   "amopopr::pg_catalog.regoperator, "
10364                                                   "NULL AS sortfamily, "
10365                                                   "NULL AS sortfamilynsp "
10366                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10367                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10368                                                   "AND refobjid = '%u'::pg_catalog.oid "
10369                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10370                                                   "AND objid = ao.oid "
10371                                                   "ORDER BY amopstrategy",
10372                                                   opfinfo->dobj.catId.oid);
10373         }
10374         else
10375         {
10376                 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10377                                                   "amopopr::pg_catalog.regoperator, "
10378                                                   "NULL AS sortfamily, "
10379                                                   "NULL AS sortfamilynsp "
10380                                                   "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10381                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10382                                                   "AND refobjid = '%u'::pg_catalog.oid "
10383                                    "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10384                                                   "AND objid = ao.oid "
10385                                                   "ORDER BY amopstrategy",
10386                                                   opfinfo->dobj.catId.oid);
10387         }
10388
10389         res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10390
10391         resetPQExpBuffer(query);
10392
10393         appendPQExpBuffer(query, "SELECT amprocnum, "
10394                                           "amproc::pg_catalog.regprocedure, "
10395                                           "amproclefttype::pg_catalog.regtype, "
10396                                           "amprocrighttype::pg_catalog.regtype "
10397                                           "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10398                   "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10399                                           "AND refobjid = '%u'::pg_catalog.oid "
10400                                  "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10401                                           "AND objid = ap.oid "
10402                                           "ORDER BY amprocnum",
10403                                           opfinfo->dobj.catId.oid);
10404
10405         res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10406
10407         if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10408         {
10409                 /* No loose members, so check contained opclasses */
10410                 resetPQExpBuffer(query);
10411
10412                 appendPQExpBuffer(query, "SELECT 1 "
10413                                                   "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10414                                                   "WHERE f.oid = '%u'::pg_catalog.oid "
10415                         "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10416                                                   "AND refobjid = f.oid "
10417                                 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10418                                                   "AND objid = c.oid "
10419                                                   "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10420                                                   "LIMIT 1",
10421                                                   opfinfo->dobj.catId.oid);
10422
10423                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10424
10425                 if (PQntuples(res) == 0)
10426                 {
10427                         /* no need to dump it, so bail out */
10428                         PQclear(res);
10429                         PQclear(res_ops);
10430                         PQclear(res_procs);
10431                         destroyPQExpBuffer(query);
10432                         destroyPQExpBuffer(q);
10433                         destroyPQExpBuffer(delq);
10434                         destroyPQExpBuffer(labelq);
10435                         return;
10436                 }
10437
10438                 PQclear(res);
10439         }
10440
10441         /* Get additional fields from the pg_opfamily row */
10442         resetPQExpBuffer(query);
10443
10444         appendPQExpBuffer(query, "SELECT "
10445          "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10446                                           "FROM pg_catalog.pg_opfamily "
10447                                           "WHERE oid = '%u'::pg_catalog.oid",
10448                                           opfinfo->dobj.catId.oid);
10449
10450         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10451
10452         i_amname = PQfnumber(res, "amname");
10453
10454         /* amname will still be needed after we PQclear res */
10455         amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10456
10457         /*
10458          * DROP must be fully qualified in case same name appears in pg_catalog
10459          */
10460         appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10461                                           fmtId(opfinfo->dobj.namespace->dobj.name));
10462         appendPQExpBuffer(delq, ".%s",
10463                                           fmtId(opfinfo->dobj.name));
10464         appendPQExpBuffer(delq, " USING %s;\n",
10465                                           fmtId(amname));
10466
10467         /* Build the fixed portion of the CREATE command */
10468         appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10469                                           fmtId(opfinfo->dobj.name));
10470         appendPQExpBuffer(q, " USING %s;\n",
10471                                           fmtId(amname));
10472
10473         PQclear(res);
10474
10475         /* Do we need an ALTER to add loose members? */
10476         if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10477         {
10478                 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10479                                                   fmtId(opfinfo->dobj.name));
10480                 appendPQExpBuffer(q, " USING %s ADD\n    ",
10481                                                   fmtId(amname));
10482
10483                 needComma = false;
10484
10485                 /*
10486                  * Now fetch and print the OPERATOR entries (pg_amop rows).
10487                  */
10488                 ntups = PQntuples(res_ops);
10489
10490                 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10491                 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10492                 i_amopopr = PQfnumber(res_ops, "amopopr");
10493                 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10494                 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10495
10496                 for (i = 0; i < ntups; i++)
10497                 {
10498                         amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10499                         amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10500                         amopopr = PQgetvalue(res_ops, i, i_amopopr);
10501                         sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10502                         sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10503
10504                         if (needComma)
10505                                 appendPQExpBuffer(q, " ,\n    ");
10506
10507                         appendPQExpBuffer(q, "OPERATOR %s %s",
10508                                                           amopstrategy, amopopr);
10509
10510                         if (strlen(sortfamily) > 0)
10511                         {
10512                                 appendPQExpBuffer(q, " FOR ORDER BY ");
10513                                 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10514                                         appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10515                                 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10516                         }
10517
10518                         if (strcmp(amopreqcheck, "t") == 0)
10519                                 appendPQExpBuffer(q, " RECHECK");
10520
10521                         needComma = true;
10522                 }
10523
10524                 /*
10525                  * Now fetch and print the FUNCTION entries (pg_amproc rows).
10526                  */
10527                 ntups = PQntuples(res_procs);
10528
10529                 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10530                 i_amproc = PQfnumber(res_procs, "amproc");
10531                 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10532                 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10533
10534                 for (i = 0; i < ntups; i++)
10535                 {
10536                         amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10537                         amproc = PQgetvalue(res_procs, i, i_amproc);
10538                         amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10539                         amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10540
10541                         if (needComma)
10542                                 appendPQExpBuffer(q, " ,\n    ");
10543
10544                         appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10545                                                           amprocnum, amproclefttype, amprocrighttype,
10546                                                           amproc);
10547
10548                         needComma = true;
10549                 }
10550
10551                 appendPQExpBuffer(q, ";\n");
10552         }
10553
10554         appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10555                                           fmtId(opfinfo->dobj.name));
10556         appendPQExpBuffer(labelq, " USING %s",
10557                                           fmtId(amname));
10558
10559         if (binary_upgrade)
10560                 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10561
10562         ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10563                                  opfinfo->dobj.name,
10564                                  opfinfo->dobj.namespace->dobj.name,
10565                                  NULL,
10566                                  opfinfo->rolname,
10567                                  false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10568                                  q->data, delq->data, NULL,
10569                                  opfinfo->dobj.dependencies, opfinfo->dobj.nDeps,
10570                                  NULL, NULL);
10571
10572         /* Dump Operator Family Comments */
10573         dumpComment(fout, labelq->data,
10574                                 NULL, opfinfo->rolname,
10575                                 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10576
10577         free(amname);
10578         PQclear(res_ops);
10579         PQclear(res_procs);
10580         destroyPQExpBuffer(query);
10581         destroyPQExpBuffer(q);
10582         destroyPQExpBuffer(delq);
10583         destroyPQExpBuffer(labelq);
10584 }
10585
10586 /*
10587  * dumpCollation
10588  *        write out a single collation definition
10589  */
10590 static void
10591 dumpCollation(Archive *fout, CollInfo *collinfo)
10592 {
10593         PQExpBuffer query;
10594         PQExpBuffer q;
10595         PQExpBuffer delq;
10596         PQExpBuffer labelq;
10597         PGresult   *res;
10598         int                     i_collcollate;
10599         int                     i_collctype;
10600         const char *collcollate;
10601         const char *collctype;
10602
10603         /* Skip if not to be dumped */
10604         if (!collinfo->dobj.dump || dataOnly)
10605                 return;
10606
10607         query = createPQExpBuffer();
10608         q = createPQExpBuffer();
10609         delq = createPQExpBuffer();
10610         labelq = createPQExpBuffer();
10611
10612         /* Make sure we are in proper schema */
10613         selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
10614
10615         /* Get conversion-specific details */
10616         appendPQExpBuffer(query, "SELECT "
10617                                           "collcollate, "
10618                                           "collctype "
10619                                           "FROM pg_catalog.pg_collation c "
10620                                           "WHERE c.oid = '%u'::pg_catalog.oid",
10621                                           collinfo->dobj.catId.oid);
10622
10623         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10624
10625         i_collcollate = PQfnumber(res, "collcollate");
10626         i_collctype = PQfnumber(res, "collctype");
10627
10628         collcollate = PQgetvalue(res, 0, i_collcollate);
10629         collctype = PQgetvalue(res, 0, i_collctype);
10630
10631         /*
10632          * DROP must be fully qualified in case same name appears in pg_catalog
10633          */
10634         appendPQExpBuffer(delq, "DROP COLLATION %s",
10635                                           fmtId(collinfo->dobj.namespace->dobj.name));
10636         appendPQExpBuffer(delq, ".%s;\n",
10637                                           fmtId(collinfo->dobj.name));
10638
10639         appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
10640                                           fmtId(collinfo->dobj.name));
10641         appendStringLiteralAH(q, collcollate, fout);
10642         appendPQExpBuffer(q, ", lc_ctype = ");
10643         appendStringLiteralAH(q, collctype, fout);
10644         appendPQExpBuffer(q, ");\n");
10645
10646         appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
10647
10648         if (binary_upgrade)
10649                 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
10650
10651         ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
10652                                  collinfo->dobj.name,
10653                                  collinfo->dobj.namespace->dobj.name,
10654                                  NULL,
10655                                  collinfo->rolname,
10656                                  false, "COLLATION", SECTION_PRE_DATA,
10657                                  q->data, delq->data, NULL,
10658                                  collinfo->dobj.dependencies, collinfo->dobj.nDeps,
10659                                  NULL, NULL);
10660
10661         /* Dump Collation Comments */
10662         dumpComment(fout, labelq->data,
10663                                 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
10664                                 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
10665
10666         PQclear(res);
10667
10668         destroyPQExpBuffer(query);
10669         destroyPQExpBuffer(q);
10670         destroyPQExpBuffer(delq);
10671         destroyPQExpBuffer(labelq);
10672 }
10673
10674 /*
10675  * dumpConversion
10676  *        write out a single conversion definition
10677  */
10678 static void
10679 dumpConversion(Archive *fout, ConvInfo *convinfo)
10680 {
10681         PQExpBuffer query;
10682         PQExpBuffer q;
10683         PQExpBuffer delq;
10684         PQExpBuffer labelq;
10685         PGresult   *res;
10686         int                     i_conforencoding;
10687         int                     i_contoencoding;
10688         int                     i_conproc;
10689         int                     i_condefault;
10690         const char *conforencoding;
10691         const char *contoencoding;
10692         const char *conproc;
10693         bool            condefault;
10694
10695         /* Skip if not to be dumped */
10696         if (!convinfo->dobj.dump || dataOnly)
10697                 return;
10698
10699         query = createPQExpBuffer();
10700         q = createPQExpBuffer();
10701         delq = createPQExpBuffer();
10702         labelq = createPQExpBuffer();
10703
10704         /* Make sure we are in proper schema */
10705         selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
10706
10707         /* Get conversion-specific details */
10708         appendPQExpBuffer(query, "SELECT "
10709                  "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
10710                    "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
10711                                           "conproc, condefault "
10712                                           "FROM pg_catalog.pg_conversion c "
10713                                           "WHERE c.oid = '%u'::pg_catalog.oid",
10714                                           convinfo->dobj.catId.oid);
10715
10716         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10717
10718         i_conforencoding = PQfnumber(res, "conforencoding");
10719         i_contoencoding = PQfnumber(res, "contoencoding");
10720         i_conproc = PQfnumber(res, "conproc");
10721         i_condefault = PQfnumber(res, "condefault");
10722
10723         conforencoding = PQgetvalue(res, 0, i_conforencoding);
10724         contoencoding = PQgetvalue(res, 0, i_contoencoding);
10725         conproc = PQgetvalue(res, 0, i_conproc);
10726         condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
10727
10728         /*
10729          * DROP must be fully qualified in case same name appears in pg_catalog
10730          */
10731         appendPQExpBuffer(delq, "DROP CONVERSION %s",
10732                                           fmtId(convinfo->dobj.namespace->dobj.name));
10733         appendPQExpBuffer(delq, ".%s;\n",
10734                                           fmtId(convinfo->dobj.name));
10735
10736         appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
10737                                           (condefault) ? "DEFAULT " : "",
10738                                           fmtId(convinfo->dobj.name));
10739         appendStringLiteralAH(q, conforencoding, fout);
10740         appendPQExpBuffer(q, " TO ");
10741         appendStringLiteralAH(q, contoencoding, fout);
10742         /* regproc is automatically quoted in 7.3 and above */
10743         appendPQExpBuffer(q, " FROM %s;\n", conproc);
10744
10745         appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
10746
10747         if (binary_upgrade)
10748                 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
10749
10750         ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
10751                                  convinfo->dobj.name,
10752                                  convinfo->dobj.namespace->dobj.name,
10753                                  NULL,
10754                                  convinfo->rolname,
10755                                  false, "CONVERSION", SECTION_PRE_DATA,
10756                                  q->data, delq->data, NULL,
10757                                  convinfo->dobj.dependencies, convinfo->dobj.nDeps,
10758                                  NULL, NULL);
10759
10760         /* Dump Conversion Comments */
10761         dumpComment(fout, labelq->data,
10762                                 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
10763                                 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
10764
10765         PQclear(res);
10766
10767         destroyPQExpBuffer(query);
10768         destroyPQExpBuffer(q);
10769         destroyPQExpBuffer(delq);
10770         destroyPQExpBuffer(labelq);
10771 }
10772
10773 /*
10774  * format_aggregate_signature: generate aggregate name and argument list
10775  *
10776  * The argument type names are qualified if needed.  The aggregate name
10777  * is never qualified.
10778  */
10779 static char *
10780 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
10781 {
10782         PQExpBufferData buf;
10783         int                     j;
10784
10785         initPQExpBuffer(&buf);
10786         if (honor_quotes)
10787                 appendPQExpBuffer(&buf, "%s",
10788                                                   fmtId(agginfo->aggfn.dobj.name));
10789         else
10790                 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
10791
10792         if (agginfo->aggfn.nargs == 0)
10793                 appendPQExpBuffer(&buf, "(*)");
10794         else
10795         {
10796                 appendPQExpBuffer(&buf, "(");
10797                 for (j = 0; j < agginfo->aggfn.nargs; j++)
10798                 {
10799                         char       *typname;
10800
10801                         typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
10802                                                                                    zeroAsOpaque);
10803
10804                         appendPQExpBuffer(&buf, "%s%s",
10805                                                           (j > 0) ? ", " : "",
10806                                                           typname);
10807                         free(typname);
10808                 }
10809                 appendPQExpBuffer(&buf, ")");
10810         }
10811         return buf.data;
10812 }
10813
10814 /*
10815  * dumpAgg
10816  *        write out a single aggregate definition
10817  */
10818 static void
10819 dumpAgg(Archive *fout, AggInfo *agginfo)
10820 {
10821         PQExpBuffer query;
10822         PQExpBuffer q;
10823         PQExpBuffer delq;
10824         PQExpBuffer labelq;
10825         PQExpBuffer details;
10826         char       *aggsig;
10827         char       *aggsig_tag;
10828         PGresult   *res;
10829         int                     i_aggtransfn;
10830         int                     i_aggfinalfn;
10831         int                     i_aggsortop;
10832         int                     i_aggtranstype;
10833         int                     i_agginitval;
10834         int                     i_convertok;
10835         const char *aggtransfn;
10836         const char *aggfinalfn;
10837         const char *aggsortop;
10838         const char *aggtranstype;
10839         const char *agginitval;
10840         bool            convertok;
10841
10842         /* Skip if not to be dumped */
10843         if (!agginfo->aggfn.dobj.dump || dataOnly)
10844                 return;
10845
10846         query = createPQExpBuffer();
10847         q = createPQExpBuffer();
10848         delq = createPQExpBuffer();
10849         labelq = createPQExpBuffer();
10850         details = createPQExpBuffer();
10851
10852         /* Make sure we are in proper schema */
10853         selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
10854
10855         /* Get aggregate-specific details */
10856         if (fout->remoteVersion >= 80100)
10857         {
10858                 appendPQExpBuffer(query, "SELECT aggtransfn, "
10859                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10860                                                   "aggsortop::pg_catalog.regoperator, "
10861                                                   "agginitval, "
10862                                                   "'t'::boolean AS convertok "
10863                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10864                                                   "WHERE a.aggfnoid = p.oid "
10865                                                   "AND p.oid = '%u'::pg_catalog.oid",
10866                                                   agginfo->aggfn.dobj.catId.oid);
10867         }
10868         else if (fout->remoteVersion >= 70300)
10869         {
10870                 appendPQExpBuffer(query, "SELECT aggtransfn, "
10871                                                   "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10872                                                   "0 AS aggsortop, "
10873                                                   "agginitval, "
10874                                                   "'t'::boolean AS convertok "
10875                                           "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10876                                                   "WHERE a.aggfnoid = p.oid "
10877                                                   "AND p.oid = '%u'::pg_catalog.oid",
10878                                                   agginfo->aggfn.dobj.catId.oid);
10879         }
10880         else if (fout->remoteVersion >= 70100)
10881         {
10882                 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
10883                                                   "format_type(aggtranstype, NULL) AS aggtranstype, "
10884                                                   "0 AS aggsortop, "
10885                                                   "agginitval, "
10886                                                   "'t'::boolean AS convertok "
10887                                                   "FROM pg_aggregate "
10888                                                   "WHERE oid = '%u'::oid",
10889                                                   agginfo->aggfn.dobj.catId.oid);
10890         }
10891         else
10892         {
10893                 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
10894                                                   "aggfinalfn, "
10895                                                   "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
10896                                                   "0 AS aggsortop, "
10897                                                   "agginitval1 AS agginitval, "
10898                                                   "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
10899                                                   "FROM pg_aggregate "
10900                                                   "WHERE oid = '%u'::oid",
10901                                                   agginfo->aggfn.dobj.catId.oid);
10902         }
10903
10904         res = ExecuteSqlQueryForSingleRow(fout, query->data);
10905
10906         i_aggtransfn = PQfnumber(res, "aggtransfn");
10907         i_aggfinalfn = PQfnumber(res, "aggfinalfn");
10908         i_aggsortop = PQfnumber(res, "aggsortop");
10909         i_aggtranstype = PQfnumber(res, "aggtranstype");
10910         i_agginitval = PQfnumber(res, "agginitval");
10911         i_convertok = PQfnumber(res, "convertok");
10912
10913         aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
10914         aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
10915         aggsortop = PQgetvalue(res, 0, i_aggsortop);
10916         aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
10917         agginitval = PQgetvalue(res, 0, i_agginitval);
10918         convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
10919
10920         aggsig = format_aggregate_signature(agginfo, fout, true);
10921         aggsig_tag = format_aggregate_signature(agginfo, fout, false);
10922
10923         if (!convertok)
10924         {
10925                 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
10926                                   aggsig);
10927                 return;
10928         }
10929
10930         if (fout->remoteVersion >= 70300)
10931         {
10932                 /* If using 7.3's regproc or regtype, data is already quoted */
10933                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
10934                                                   aggtransfn,
10935                                                   aggtranstype);
10936         }
10937         else if (fout->remoteVersion >= 70100)
10938         {
10939                 /* format_type quotes, regproc does not */
10940                 appendPQExpBuffer(details, "    SFUNC = %s,\n    STYPE = %s",
10941                                                   fmtId(aggtransfn),
10942                                                   aggtranstype);
10943         }
10944         else
10945         {
10946                 /* need quotes all around */
10947                 appendPQExpBuffer(details, "    SFUNC = %s,\n",
10948                                                   fmtId(aggtransfn));
10949                 appendPQExpBuffer(details, "    STYPE = %s",
10950                                                   fmtId(aggtranstype));
10951         }
10952
10953         if (!PQgetisnull(res, 0, i_agginitval))
10954         {
10955                 appendPQExpBuffer(details, ",\n    INITCOND = ");
10956                 appendStringLiteralAH(details, agginitval, fout);
10957         }
10958
10959         if (strcmp(aggfinalfn, "-") != 0)
10960         {
10961                 appendPQExpBuffer(details, ",\n    FINALFUNC = %s",
10962                                                   aggfinalfn);
10963         }
10964
10965         aggsortop = convertOperatorReference(fout, aggsortop);
10966         if (aggsortop)
10967         {
10968                 appendPQExpBuffer(details, ",\n    SORTOP = %s",
10969                                                   aggsortop);
10970         }
10971
10972         /*
10973          * DROP must be fully qualified in case same name appears in pg_catalog
10974          */
10975         appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
10976                                           fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
10977                                           aggsig);
10978
10979         appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
10980                                           aggsig, details->data);
10981
10982         appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
10983
10984         if (binary_upgrade)
10985                 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
10986
10987         ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
10988                                  aggsig_tag,
10989                                  agginfo->aggfn.dobj.namespace->dobj.name,
10990                                  NULL,
10991                                  agginfo->aggfn.rolname,
10992                                  false, "AGGREGATE", SECTION_PRE_DATA,
10993                                  q->data, delq->data, NULL,
10994                                  agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
10995                                  NULL, NULL);
10996
10997         /* Dump Aggregate Comments */
10998         dumpComment(fout, labelq->data,
10999                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11000                                 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11001         dumpSecLabel(fout, labelq->data,
11002                         agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11003                                  agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11004
11005         /*
11006          * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
11007          * command look like a function's GRANT; in particular this affects the
11008          * syntax for zero-argument aggregates.
11009          */
11010         free(aggsig);
11011         free(aggsig_tag);
11012
11013         aggsig = format_function_signature(fout, &agginfo->aggfn, true);
11014         aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
11015
11016         dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11017                         "FUNCTION",
11018                         aggsig, NULL, aggsig_tag,
11019                         agginfo->aggfn.dobj.namespace->dobj.name,
11020                         agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11021
11022         free(aggsig);
11023         free(aggsig_tag);
11024
11025         PQclear(res);
11026
11027         destroyPQExpBuffer(query);
11028         destroyPQExpBuffer(q);
11029         destroyPQExpBuffer(delq);
11030         destroyPQExpBuffer(labelq);
11031         destroyPQExpBuffer(details);
11032 }
11033
11034 /*
11035  * dumpTSParser
11036  *        write out a single text search parser
11037  */
11038 static void
11039 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11040 {
11041         PQExpBuffer q;
11042         PQExpBuffer delq;
11043         PQExpBuffer labelq;
11044
11045         /* Skip if not to be dumped */
11046         if (!prsinfo->dobj.dump || dataOnly)
11047                 return;
11048
11049         q = createPQExpBuffer();
11050         delq = createPQExpBuffer();
11051         labelq = createPQExpBuffer();
11052
11053         /* Make sure we are in proper schema */
11054         selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11055
11056         appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11057                                           fmtId(prsinfo->dobj.name));
11058
11059         appendPQExpBuffer(q, "    START = %s,\n",
11060                                           convertTSFunction(fout, prsinfo->prsstart));
11061         appendPQExpBuffer(q, "    GETTOKEN = %s,\n",
11062                                           convertTSFunction(fout, prsinfo->prstoken));
11063         appendPQExpBuffer(q, "    END = %s,\n",
11064                                           convertTSFunction(fout, prsinfo->prsend));
11065         if (prsinfo->prsheadline != InvalidOid)
11066                 appendPQExpBuffer(q, "    HEADLINE = %s,\n",
11067                                                   convertTSFunction(fout, prsinfo->prsheadline));
11068         appendPQExpBuffer(q, "    LEXTYPES = %s );\n",
11069                                           convertTSFunction(fout, prsinfo->prslextype));
11070
11071         /*
11072          * DROP must be fully qualified in case same name appears in pg_catalog
11073          */
11074         appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11075                                           fmtId(prsinfo->dobj.namespace->dobj.name));
11076         appendPQExpBuffer(delq, ".%s;\n",
11077                                           fmtId(prsinfo->dobj.name));
11078
11079         appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11080                                           fmtId(prsinfo->dobj.name));
11081
11082         if (binary_upgrade)
11083                 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11084
11085         ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11086                                  prsinfo->dobj.name,
11087                                  prsinfo->dobj.namespace->dobj.name,
11088                                  NULL,
11089                                  "",
11090                                  false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11091                                  q->data, delq->data, NULL,
11092                                  prsinfo->dobj.dependencies, prsinfo->dobj.nDeps,
11093                                  NULL, NULL);
11094
11095         /* Dump Parser Comments */
11096         dumpComment(fout, labelq->data,
11097                                 NULL, "",
11098                                 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11099
11100         destroyPQExpBuffer(q);
11101         destroyPQExpBuffer(delq);
11102         destroyPQExpBuffer(labelq);
11103 }
11104
11105 /*
11106  * dumpTSDictionary
11107  *        write out a single text search dictionary
11108  */
11109 static void
11110 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11111 {
11112         PQExpBuffer q;
11113         PQExpBuffer delq;
11114         PQExpBuffer labelq;
11115         PQExpBuffer query;
11116         PGresult   *res;
11117         char       *nspname;
11118         char       *tmplname;
11119
11120         /* Skip if not to be dumped */
11121         if (!dictinfo->dobj.dump || dataOnly)
11122                 return;
11123
11124         q = createPQExpBuffer();
11125         delq = createPQExpBuffer();
11126         labelq = createPQExpBuffer();
11127         query = createPQExpBuffer();
11128
11129         /* Fetch name and namespace of the dictionary's template */
11130         selectSourceSchema(fout, "pg_catalog");
11131         appendPQExpBuffer(query, "SELECT nspname, tmplname "
11132                                           "FROM pg_ts_template p, pg_namespace n "
11133                                           "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11134                                           dictinfo->dicttemplate);
11135         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11136         nspname = PQgetvalue(res, 0, 0);
11137         tmplname = PQgetvalue(res, 0, 1);
11138
11139         /* Make sure we are in proper schema */
11140         selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11141
11142         appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11143                                           fmtId(dictinfo->dobj.name));
11144
11145         appendPQExpBuffer(q, "    TEMPLATE = ");
11146         if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11147                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11148         appendPQExpBuffer(q, "%s", fmtId(tmplname));
11149
11150         PQclear(res);
11151
11152         /* the dictinitoption can be dumped straight into the command */
11153         if (dictinfo->dictinitoption)
11154                 appendPQExpBuffer(q, ",\n    %s", dictinfo->dictinitoption);
11155
11156         appendPQExpBuffer(q, " );\n");
11157
11158         /*
11159          * DROP must be fully qualified in case same name appears in pg_catalog
11160          */
11161         appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11162                                           fmtId(dictinfo->dobj.namespace->dobj.name));
11163         appendPQExpBuffer(delq, ".%s;\n",
11164                                           fmtId(dictinfo->dobj.name));
11165
11166         appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11167                                           fmtId(dictinfo->dobj.name));
11168
11169         if (binary_upgrade)
11170                 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11171
11172         ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11173                                  dictinfo->dobj.name,
11174                                  dictinfo->dobj.namespace->dobj.name,
11175                                  NULL,
11176                                  dictinfo->rolname,
11177                                  false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11178                                  q->data, delq->data, NULL,
11179                                  dictinfo->dobj.dependencies, dictinfo->dobj.nDeps,
11180                                  NULL, NULL);
11181
11182         /* Dump Dictionary Comments */
11183         dumpComment(fout, labelq->data,
11184                                 NULL, dictinfo->rolname,
11185                                 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11186
11187         destroyPQExpBuffer(q);
11188         destroyPQExpBuffer(delq);
11189         destroyPQExpBuffer(labelq);
11190         destroyPQExpBuffer(query);
11191 }
11192
11193 /*
11194  * dumpTSTemplate
11195  *        write out a single text search template
11196  */
11197 static void
11198 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11199 {
11200         PQExpBuffer q;
11201         PQExpBuffer delq;
11202         PQExpBuffer labelq;
11203
11204         /* Skip if not to be dumped */
11205         if (!tmplinfo->dobj.dump || dataOnly)
11206                 return;
11207
11208         q = createPQExpBuffer();
11209         delq = createPQExpBuffer();
11210         labelq = createPQExpBuffer();
11211
11212         /* Make sure we are in proper schema */
11213         selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11214
11215         appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11216                                           fmtId(tmplinfo->dobj.name));
11217
11218         if (tmplinfo->tmplinit != InvalidOid)
11219                 appendPQExpBuffer(q, "    INIT = %s,\n",
11220                                                   convertTSFunction(fout, tmplinfo->tmplinit));
11221         appendPQExpBuffer(q, "    LEXIZE = %s );\n",
11222                                           convertTSFunction(fout, tmplinfo->tmpllexize));
11223
11224         /*
11225          * DROP must be fully qualified in case same name appears in pg_catalog
11226          */
11227         appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11228                                           fmtId(tmplinfo->dobj.namespace->dobj.name));
11229         appendPQExpBuffer(delq, ".%s;\n",
11230                                           fmtId(tmplinfo->dobj.name));
11231
11232         appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11233                                           fmtId(tmplinfo->dobj.name));
11234
11235         if (binary_upgrade)
11236                 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11237
11238         ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11239                                  tmplinfo->dobj.name,
11240                                  tmplinfo->dobj.namespace->dobj.name,
11241                                  NULL,
11242                                  "",
11243                                  false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11244                                  q->data, delq->data, NULL,
11245                                  tmplinfo->dobj.dependencies, tmplinfo->dobj.nDeps,
11246                                  NULL, NULL);
11247
11248         /* Dump Template Comments */
11249         dumpComment(fout, labelq->data,
11250                                 NULL, "",
11251                                 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11252
11253         destroyPQExpBuffer(q);
11254         destroyPQExpBuffer(delq);
11255         destroyPQExpBuffer(labelq);
11256 }
11257
11258 /*
11259  * dumpTSConfig
11260  *        write out a single text search configuration
11261  */
11262 static void
11263 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11264 {
11265         PQExpBuffer q;
11266         PQExpBuffer delq;
11267         PQExpBuffer labelq;
11268         PQExpBuffer query;
11269         PGresult   *res;
11270         char       *nspname;
11271         char       *prsname;
11272         int                     ntups,
11273                                 i;
11274         int                     i_tokenname;
11275         int                     i_dictname;
11276
11277         /* Skip if not to be dumped */
11278         if (!cfginfo->dobj.dump || dataOnly)
11279                 return;
11280
11281         q = createPQExpBuffer();
11282         delq = createPQExpBuffer();
11283         labelq = createPQExpBuffer();
11284         query = createPQExpBuffer();
11285
11286         /* Fetch name and namespace of the config's parser */
11287         selectSourceSchema(fout, "pg_catalog");
11288         appendPQExpBuffer(query, "SELECT nspname, prsname "
11289                                           "FROM pg_ts_parser p, pg_namespace n "
11290                                           "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11291                                           cfginfo->cfgparser);
11292         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11293         nspname = PQgetvalue(res, 0, 0);
11294         prsname = PQgetvalue(res, 0, 1);
11295
11296         /* Make sure we are in proper schema */
11297         selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11298
11299         appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11300                                           fmtId(cfginfo->dobj.name));
11301
11302         appendPQExpBuffer(q, "    PARSER = ");
11303         if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11304                 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11305         appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11306
11307         PQclear(res);
11308
11309         resetPQExpBuffer(query);
11310         appendPQExpBuffer(query,
11311                                           "SELECT \n"
11312                                           "  ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11313                                           "    WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11314                                           "  m.mapdict::pg_catalog.regdictionary AS dictname \n"
11315                                           "FROM pg_catalog.pg_ts_config_map AS m \n"
11316                                           "WHERE m.mapcfg = '%u' \n"
11317                                           "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11318                                           cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11319
11320         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11321         ntups = PQntuples(res);
11322
11323         i_tokenname = PQfnumber(res, "tokenname");
11324         i_dictname = PQfnumber(res, "dictname");
11325
11326         for (i = 0; i < ntups; i++)
11327         {
11328                 char       *tokenname = PQgetvalue(res, i, i_tokenname);
11329                 char       *dictname = PQgetvalue(res, i, i_dictname);
11330
11331                 if (i == 0 ||
11332                         strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11333                 {
11334                         /* starting a new token type, so start a new command */
11335                         if (i > 0)
11336                                 appendPQExpBuffer(q, ";\n");
11337                         appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11338                                                           fmtId(cfginfo->dobj.name));
11339                         /* tokenname needs quoting, dictname does NOT */
11340                         appendPQExpBuffer(q, "    ADD MAPPING FOR %s WITH %s",
11341                                                           fmtId(tokenname), dictname);
11342                 }
11343                 else
11344                         appendPQExpBuffer(q, ", %s", dictname);
11345         }
11346
11347         if (ntups > 0)
11348                 appendPQExpBuffer(q, ";\n");
11349
11350         PQclear(res);
11351
11352         /*
11353          * DROP must be fully qualified in case same name appears in pg_catalog
11354          */
11355         appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11356                                           fmtId(cfginfo->dobj.namespace->dobj.name));
11357         appendPQExpBuffer(delq, ".%s;\n",
11358                                           fmtId(cfginfo->dobj.name));
11359
11360         appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11361                                           fmtId(cfginfo->dobj.name));
11362
11363         if (binary_upgrade)
11364                 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11365
11366         ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11367                                  cfginfo->dobj.name,
11368                                  cfginfo->dobj.namespace->dobj.name,
11369                                  NULL,
11370                                  cfginfo->rolname,
11371                                  false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11372                                  q->data, delq->data, NULL,
11373                                  cfginfo->dobj.dependencies, cfginfo->dobj.nDeps,
11374                                  NULL, NULL);
11375
11376         /* Dump Configuration Comments */
11377         dumpComment(fout, labelq->data,
11378                                 NULL, cfginfo->rolname,
11379                                 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11380
11381         destroyPQExpBuffer(q);
11382         destroyPQExpBuffer(delq);
11383         destroyPQExpBuffer(labelq);
11384         destroyPQExpBuffer(query);
11385 }
11386
11387 /*
11388  * dumpForeignDataWrapper
11389  *        write out a single foreign-data wrapper definition
11390  */
11391 static void
11392 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11393 {
11394         PQExpBuffer q;
11395         PQExpBuffer delq;
11396         PQExpBuffer labelq;
11397         char       *qfdwname;
11398
11399         /* Skip if not to be dumped */
11400         if (!fdwinfo->dobj.dump || dataOnly)
11401                 return;
11402
11403         /*
11404          * FDWs that belong to an extension are dumped based on their "dump"
11405          * field. Otherwise omit them if we are only dumping some specific object.
11406          */
11407         if (!fdwinfo->dobj.ext_member)
11408                 if (!include_everything)
11409                         return;
11410
11411         q = createPQExpBuffer();
11412         delq = createPQExpBuffer();
11413         labelq = createPQExpBuffer();
11414
11415         qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11416
11417         appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11418                                           qfdwname);
11419
11420         if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11421                 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11422
11423         if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11424                 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11425
11426         if (strlen(fdwinfo->fdwoptions) > 0)
11427                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", fdwinfo->fdwoptions);
11428
11429         appendPQExpBuffer(q, ";\n");
11430
11431         appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11432                                           qfdwname);
11433
11434         appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11435                                           qfdwname);
11436
11437         if (binary_upgrade)
11438                 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11439
11440         ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11441                                  fdwinfo->dobj.name,
11442                                  NULL,
11443                                  NULL,
11444                                  fdwinfo->rolname,
11445                                  false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11446                                  q->data, delq->data, NULL,
11447                                  fdwinfo->dobj.dependencies, fdwinfo->dobj.nDeps,
11448                                  NULL, NULL);
11449
11450         /* Handle the ACL */
11451         dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11452                         "FOREIGN DATA WRAPPER",
11453                         qfdwname, NULL, fdwinfo->dobj.name,
11454                         NULL, fdwinfo->rolname,
11455                         fdwinfo->fdwacl);
11456
11457         /* Dump Foreign Data Wrapper Comments */
11458         dumpComment(fout, labelq->data,
11459                                 NULL, fdwinfo->rolname,
11460                                 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11461
11462         free(qfdwname);
11463
11464         destroyPQExpBuffer(q);
11465         destroyPQExpBuffer(delq);
11466         destroyPQExpBuffer(labelq);
11467 }
11468
11469 /*
11470  * dumpForeignServer
11471  *        write out a foreign server definition
11472  */
11473 static void
11474 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11475 {
11476         PQExpBuffer q;
11477         PQExpBuffer delq;
11478         PQExpBuffer labelq;
11479         PQExpBuffer query;
11480         PGresult   *res;
11481         char       *qsrvname;
11482         char       *fdwname;
11483
11484         /* Skip if not to be dumped */
11485         if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11486                 return;
11487
11488         q = createPQExpBuffer();
11489         delq = createPQExpBuffer();
11490         labelq = createPQExpBuffer();
11491         query = createPQExpBuffer();
11492
11493         qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11494
11495         /* look up the foreign-data wrapper */
11496         selectSourceSchema(fout, "pg_catalog");
11497         appendPQExpBuffer(query, "SELECT fdwname "
11498                                           "FROM pg_foreign_data_wrapper w "
11499                                           "WHERE w.oid = '%u'",
11500                                           srvinfo->srvfdw);
11501         res = ExecuteSqlQueryForSingleRow(fout, query->data);
11502         fdwname = PQgetvalue(res, 0, 0);
11503
11504         appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11505         if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11506         {
11507                 appendPQExpBuffer(q, " TYPE ");
11508                 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11509         }
11510         if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11511         {
11512                 appendPQExpBuffer(q, " VERSION ");
11513                 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11514         }
11515
11516         appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11517         appendPQExpBuffer(q, "%s", fmtId(fdwname));
11518
11519         if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11520                 appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", srvinfo->srvoptions);
11521
11522         appendPQExpBuffer(q, ";\n");
11523
11524         appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11525                                           qsrvname);
11526
11527         appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11528
11529         if (binary_upgrade)
11530                 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11531
11532         ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11533                                  srvinfo->dobj.name,
11534                                  NULL,
11535                                  NULL,
11536                                  srvinfo->rolname,
11537                                  false, "SERVER", SECTION_PRE_DATA,
11538                                  q->data, delq->data, NULL,
11539                                  srvinfo->dobj.dependencies, srvinfo->dobj.nDeps,
11540                                  NULL, NULL);
11541
11542         /* Handle the ACL */
11543         dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11544                         "FOREIGN SERVER",
11545                         qsrvname, NULL, srvinfo->dobj.name,
11546                         NULL, srvinfo->rolname,
11547                         srvinfo->srvacl);
11548
11549         /* Dump user mappings */
11550         dumpUserMappings(fout,
11551                                          srvinfo->dobj.name, NULL,
11552                                          srvinfo->rolname,
11553                                          srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11554
11555         /* Dump Foreign Server Comments */
11556         dumpComment(fout, labelq->data,
11557                                 NULL, srvinfo->rolname,
11558                                 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11559
11560         free(qsrvname);
11561
11562         destroyPQExpBuffer(q);
11563         destroyPQExpBuffer(delq);
11564         destroyPQExpBuffer(labelq);
11565 }
11566
11567 /*
11568  * dumpUserMappings
11569  *
11570  * This routine is used to dump any user mappings associated with the
11571  * server handed to this routine. Should be called after ArchiveEntry()
11572  * for the server.
11573  */
11574 static void
11575 dumpUserMappings(Archive *fout,
11576                                  const char *servername, const char *namespace,
11577                                  const char *owner,
11578                                  CatalogId catalogId, DumpId dumpId)
11579 {
11580         PQExpBuffer q;
11581         PQExpBuffer delq;
11582         PQExpBuffer query;
11583         PQExpBuffer tag;
11584         PGresult   *res;
11585         int                     ntups;
11586         int                     i_usename;
11587         int                     i_umoptions;
11588         int                     i;
11589
11590         q = createPQExpBuffer();
11591         tag = createPQExpBuffer();
11592         delq = createPQExpBuffer();
11593         query = createPQExpBuffer();
11594
11595         /*
11596          * We read from the publicly accessible view pg_user_mappings, so as not
11597          * to fail if run by a non-superuser.  Note that the view will show
11598          * umoptions as null if the user hasn't got privileges for the associated
11599          * server; this means that pg_dump will dump such a mapping, but with no
11600          * OPTIONS clause.      A possible alternative is to skip such mappings
11601          * altogether, but it's not clear that that's an improvement.
11602          */
11603         selectSourceSchema(fout, "pg_catalog");
11604
11605         appendPQExpBuffer(query,
11606                                           "SELECT usename, "
11607                                           "array_to_string(ARRAY("
11608                                           "SELECT quote_ident(option_name) || ' ' || "
11609                                           "quote_literal(option_value) "
11610                                           "FROM pg_options_to_table(umoptions) "
11611                                           "ORDER BY option_name"
11612                                           "), E',\n    ') AS umoptions "
11613                                           "FROM pg_user_mappings "
11614                                           "WHERE srvid = '%u' "
11615                                           "ORDER BY usename",
11616                                           catalogId.oid);
11617
11618         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11619
11620         ntups = PQntuples(res);
11621         i_usename = PQfnumber(res, "usename");
11622         i_umoptions = PQfnumber(res, "umoptions");
11623
11624         for (i = 0; i < ntups; i++)
11625         {
11626                 char       *usename;
11627                 char       *umoptions;
11628
11629                 usename = PQgetvalue(res, i, i_usename);
11630                 umoptions = PQgetvalue(res, i, i_umoptions);
11631
11632                 resetPQExpBuffer(q);
11633                 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
11634                 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
11635
11636                 if (umoptions && strlen(umoptions) > 0)
11637                         appendPQExpBuffer(q, " OPTIONS (\n    %s\n)", umoptions);
11638
11639                 appendPQExpBuffer(q, ";\n");
11640
11641                 resetPQExpBuffer(delq);
11642                 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
11643                 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
11644
11645                 resetPQExpBuffer(tag);
11646                 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
11647                                                   usename, servername);
11648
11649                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11650                                          tag->data,
11651                                          namespace,
11652                                          NULL,
11653                                          owner, false,
11654                                          "USER MAPPING", SECTION_PRE_DATA,
11655                                          q->data, delq->data, NULL,
11656                                          &dumpId, 1,
11657                                          NULL, NULL);
11658         }
11659
11660         PQclear(res);
11661
11662         destroyPQExpBuffer(query);
11663         destroyPQExpBuffer(delq);
11664         destroyPQExpBuffer(q);
11665 }
11666
11667 /*
11668  * Write out default privileges information
11669  */
11670 static void
11671 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
11672 {
11673         PQExpBuffer q;
11674         PQExpBuffer tag;
11675         const char *type;
11676
11677         /* Skip if not to be dumped */
11678         if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
11679                 return;
11680
11681         q = createPQExpBuffer();
11682         tag = createPQExpBuffer();
11683
11684         switch (daclinfo->defaclobjtype)
11685         {
11686                 case DEFACLOBJ_RELATION:
11687                         type = "TABLES";
11688                         break;
11689                 case DEFACLOBJ_SEQUENCE:
11690                         type = "SEQUENCES";
11691                         break;
11692                 case DEFACLOBJ_FUNCTION:
11693                         type = "FUNCTIONS";
11694                         break;
11695                 default:
11696                         /* shouldn't get here */
11697                         exit_horribly(NULL,
11698                                                   "unknown object type (%d) in default privileges\n",
11699                                                   (int) daclinfo->defaclobjtype);
11700                         type = "";                      /* keep compiler quiet */
11701         }
11702
11703         appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
11704
11705         /* build the actual command(s) for this tuple */
11706         if (!buildDefaultACLCommands(type,
11707                                                                  daclinfo->dobj.namespace != NULL ?
11708                                                                  daclinfo->dobj.namespace->dobj.name : NULL,
11709                                                                  daclinfo->defaclacl,
11710                                                                  daclinfo->defaclrole,
11711                                                                  fout->remoteVersion,
11712                                                                  q))
11713                 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
11714                                           daclinfo->defaclacl);
11715
11716         ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
11717                                  tag->data,
11718            daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
11719                                  NULL,
11720                                  daclinfo->defaclrole,
11721                                  false, "DEFAULT ACL", SECTION_NONE,
11722                                  q->data, "", NULL,
11723                                  daclinfo->dobj.dependencies, daclinfo->dobj.nDeps,
11724                                  NULL, NULL);
11725
11726         destroyPQExpBuffer(tag);
11727         destroyPQExpBuffer(q);
11728 }
11729
11730 /*----------
11731  * Write out grant/revoke information
11732  *
11733  * 'objCatId' is the catalog ID of the underlying object.
11734  * 'objDumpId' is the dump ID of the underlying object.
11735  * 'type' must be one of
11736  *              TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
11737  *              FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
11738  * 'name' is the formatted name of the object.  Must be quoted etc. already.
11739  * 'subname' is the formatted name of the sub-object, if any.  Must be quoted.
11740  * 'tag' is the tag for the archive entry (typ. unquoted name of object).
11741  * 'nspname' is the namespace the object is in (NULL if none).
11742  * 'owner' is the owner, NULL if there is no owner (for languages).
11743  * 'acls' is the string read out of the fooacl system catalog field;
11744  *              it will be parsed here.
11745  *----------
11746  */
11747 static void
11748 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
11749                 const char *type, const char *name, const char *subname,
11750                 const char *tag, const char *nspname, const char *owner,
11751                 const char *acls)
11752 {
11753         PQExpBuffer sql;
11754
11755         /* Do nothing if ACL dump is not enabled */
11756         if (aclsSkip)
11757                 return;
11758
11759         /* --data-only skips ACLs *except* BLOB ACLs */
11760         if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
11761                 return;
11762
11763         sql = createPQExpBuffer();
11764
11765         if (!buildACLCommands(name, subname, type, acls, owner,
11766                                                   "", fout->remoteVersion, sql))
11767                 exit_horribly(NULL,
11768                                           "could not parse ACL list (%s) for object \"%s\" (%s)\n",
11769                                           acls, name, type);
11770
11771         if (sql->len > 0)
11772                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11773                                          tag, nspname,
11774                                          NULL,
11775                                          owner ? owner : "",
11776                                          false, "ACL", SECTION_NONE,
11777                                          sql->data, "", NULL,
11778                                          &(objDumpId), 1,
11779                                          NULL, NULL);
11780
11781         destroyPQExpBuffer(sql);
11782 }
11783
11784 /*
11785  * dumpSecLabel
11786  *
11787  * This routine is used to dump any security labels associated with the
11788  * object handed to this routine. The routine takes a constant character
11789  * string for the target part of the security-label command, plus
11790  * the namespace and owner of the object (for labeling the ArchiveEntry),
11791  * plus catalog ID and subid which are the lookup key for pg_seclabel,
11792  * plus the dump ID for the object (for setting a dependency).
11793  * If a matching pg_seclabel entry is found, it is dumped.
11794  *
11795  * Note: although this routine takes a dumpId for dependency purposes,
11796  * that purpose is just to mark the dependency in the emitted dump file
11797  * for possible future use by pg_restore.  We do NOT use it for determining
11798  * ordering of the label in the dump file, because this routine is called
11799  * after dependency sorting occurs.  This routine should be called just after
11800  * calling ArchiveEntry() for the specified object.
11801  */
11802 static void
11803 dumpSecLabel(Archive *fout, const char *target,
11804                          const char *namespace, const char *owner,
11805                          CatalogId catalogId, int subid, DumpId dumpId)
11806 {
11807         SecLabelItem *labels;
11808         int                     nlabels;
11809         int                     i;
11810         PQExpBuffer query;
11811
11812         /* do nothing, if --no-security-labels is supplied */
11813         if (no_security_labels)
11814                 return;
11815
11816         /* Comments are schema not data ... except blob comments are data */
11817         if (strncmp(target, "LARGE OBJECT ", 13) != 0)
11818         {
11819                 if (dataOnly)
11820                         return;
11821         }
11822         else
11823         {
11824                 if (schemaOnly)
11825                         return;
11826         }
11827
11828         /* Search for security labels associated with catalogId, using table */
11829         nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
11830
11831         query = createPQExpBuffer();
11832
11833         for (i = 0; i < nlabels; i++)
11834         {
11835                 /*
11836                  * Ignore label entries for which the subid doesn't match.
11837                  */
11838                 if (labels[i].objsubid != subid)
11839                         continue;
11840
11841                 appendPQExpBuffer(query,
11842                                                   "SECURITY LABEL FOR %s ON %s IS ",
11843                                                   fmtId(labels[i].provider), target);
11844                 appendStringLiteralAH(query, labels[i].label, fout);
11845                 appendPQExpBuffer(query, ";\n");
11846         }
11847
11848         if (query->len > 0)
11849         {
11850                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11851                                          target, namespace, NULL, owner,
11852                                          false, "SECURITY LABEL", SECTION_NONE,
11853                                          query->data, "", NULL,
11854                                          &(dumpId), 1,
11855                                          NULL, NULL);
11856         }
11857         destroyPQExpBuffer(query);
11858 }
11859
11860 /*
11861  * dumpTableSecLabel
11862  *
11863  * As above, but dump security label for both the specified table (or view)
11864  * and its columns.
11865  */
11866 static void
11867 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
11868 {
11869         SecLabelItem *labels;
11870         int                     nlabels;
11871         int                     i;
11872         PQExpBuffer query;
11873         PQExpBuffer target;
11874
11875         /* do nothing, if --no-security-labels is supplied */
11876         if (no_security_labels)
11877                 return;
11878
11879         /* SecLabel are SCHEMA not data */
11880         if (dataOnly)
11881                 return;
11882
11883         /* Search for comments associated with relation, using table */
11884         nlabels = findSecLabels(fout,
11885                                                         tbinfo->dobj.catId.tableoid,
11886                                                         tbinfo->dobj.catId.oid,
11887                                                         &labels);
11888
11889         /* If security labels exist, build SECURITY LABEL statements */
11890         if (nlabels <= 0)
11891                 return;
11892
11893         query = createPQExpBuffer();
11894         target = createPQExpBuffer();
11895
11896         for (i = 0; i < nlabels; i++)
11897         {
11898                 const char *colname;
11899                 const char *provider = labels[i].provider;
11900                 const char *label = labels[i].label;
11901                 int                     objsubid = labels[i].objsubid;
11902
11903                 resetPQExpBuffer(target);
11904                 if (objsubid == 0)
11905                 {
11906                         appendPQExpBuffer(target, "%s %s", reltypename,
11907                                                           fmtId(tbinfo->dobj.name));
11908                 }
11909                 else
11910                 {
11911                         colname = getAttrName(objsubid, tbinfo);
11912                         /* first fmtId result must be consumed before calling it again */
11913                         appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
11914                         appendPQExpBuffer(target, ".%s", fmtId(colname));
11915                 }
11916                 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
11917                                                   fmtId(provider), target->data);
11918                 appendStringLiteralAH(query, label, fout);
11919                 appendPQExpBuffer(query, ";\n");
11920         }
11921         if (query->len > 0)
11922         {
11923                 resetPQExpBuffer(target);
11924                 appendPQExpBuffer(target, "%s %s", reltypename,
11925                                                   fmtId(tbinfo->dobj.name));
11926                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11927                                          target->data,
11928                                          tbinfo->dobj.namespace->dobj.name,
11929                                          NULL, tbinfo->rolname,
11930                                          false, "SECURITY LABEL", SECTION_NONE,
11931                                          query->data, "", NULL,
11932                                          &(tbinfo->dobj.dumpId), 1,
11933                                          NULL, NULL);
11934         }
11935         destroyPQExpBuffer(query);
11936         destroyPQExpBuffer(target);
11937 }
11938
11939 /*
11940  * findSecLabels
11941  *
11942  * Find the security label(s), if any, associated with the given object.
11943  * All the objsubid values associated with the given classoid/objoid are
11944  * found with one search.
11945  */
11946 static int
11947 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
11948 {
11949         /* static storage for table of security labels */
11950         static SecLabelItem *labels = NULL;
11951         static int      nlabels = -1;
11952
11953         SecLabelItem *middle = NULL;
11954         SecLabelItem *low;
11955         SecLabelItem *high;
11956         int                     nmatch;
11957
11958         /* Get security labels if we didn't already */
11959         if (nlabels < 0)
11960                 nlabels = collectSecLabels(fout, &labels);
11961
11962         if (nlabels <= 0)                       /* no labels, so no match is possible */
11963         {
11964                 *items = NULL;
11965                 return 0;
11966         }
11967
11968         /*
11969          * Do binary search to find some item matching the object.
11970          */
11971         low = &labels[0];
11972         high = &labels[nlabels - 1];
11973         while (low <= high)
11974         {
11975                 middle = low + (high - low) / 2;
11976
11977                 if (classoid < middle->classoid)
11978                         high = middle - 1;
11979                 else if (classoid > middle->classoid)
11980                         low = middle + 1;
11981                 else if (objoid < middle->objoid)
11982                         high = middle - 1;
11983                 else if (objoid > middle->objoid)
11984                         low = middle + 1;
11985                 else
11986                         break;                          /* found a match */
11987         }
11988
11989         if (low > high)                         /* no matches */
11990         {
11991                 *items = NULL;
11992                 return 0;
11993         }
11994
11995         /*
11996          * Now determine how many items match the object.  The search loop
11997          * invariant still holds: only items between low and high inclusive could
11998          * match.
11999          */
12000         nmatch = 1;
12001         while (middle > low)
12002         {
12003                 if (classoid != middle[-1].classoid ||
12004                         objoid != middle[-1].objoid)
12005                         break;
12006                 middle--;
12007                 nmatch++;
12008         }
12009
12010         *items = middle;
12011
12012         middle += nmatch;
12013         while (middle <= high)
12014         {
12015                 if (classoid != middle->classoid ||
12016                         objoid != middle->objoid)
12017                         break;
12018                 middle++;
12019                 nmatch++;
12020         }
12021
12022         return nmatch;
12023 }
12024
12025 /*
12026  * collectSecLabels
12027  *
12028  * Construct a table of all security labels available for database objects.
12029  * It's much faster to pull them all at once.
12030  *
12031  * The table is sorted by classoid/objid/objsubid for speed in lookup.
12032  */
12033 static int
12034 collectSecLabels(Archive *fout, SecLabelItem **items)
12035 {
12036         PGresult   *res;
12037         PQExpBuffer query;
12038         int                     i_label;
12039         int                     i_provider;
12040         int                     i_classoid;
12041         int                     i_objoid;
12042         int                     i_objsubid;
12043         int                     ntups;
12044         int                     i;
12045         SecLabelItem *labels;
12046
12047         query = createPQExpBuffer();
12048
12049         appendPQExpBuffer(query,
12050                                           "SELECT label, provider, classoid, objoid, objsubid "
12051                                           "FROM pg_catalog.pg_seclabel "
12052                                           "ORDER BY classoid, objoid, objsubid");
12053
12054         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12055
12056         /* Construct lookup table containing OIDs in numeric form */
12057         i_label = PQfnumber(res, "label");
12058         i_provider = PQfnumber(res, "provider");
12059         i_classoid = PQfnumber(res, "classoid");
12060         i_objoid = PQfnumber(res, "objoid");
12061         i_objsubid = PQfnumber(res, "objsubid");
12062
12063         ntups = PQntuples(res);
12064
12065         labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12066
12067         for (i = 0; i < ntups; i++)
12068         {
12069                 labels[i].label = PQgetvalue(res, i, i_label);
12070                 labels[i].provider = PQgetvalue(res, i, i_provider);
12071                 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12072                 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12073                 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12074         }
12075
12076         /* Do NOT free the PGresult since we are keeping pointers into it */
12077         destroyPQExpBuffer(query);
12078
12079         *items = labels;
12080         return ntups;
12081 }
12082
12083 /*
12084  * dumpTable
12085  *        write out to fout the declarations (not data) of a user-defined table
12086  */
12087 static void
12088 dumpTable(Archive *fout, TableInfo *tbinfo)
12089 {
12090         if (tbinfo->dobj.dump)
12091         {
12092                 char       *namecopy;
12093
12094                 if (tbinfo->relkind == RELKIND_SEQUENCE)
12095                         dumpSequence(fout, tbinfo);
12096                 else if (!dataOnly)
12097                         dumpTableSchema(fout, tbinfo);
12098
12099                 /* Handle the ACL here */
12100                 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12101                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12102                                 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12103                                 "TABLE",
12104                                 namecopy, NULL, tbinfo->dobj.name,
12105                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12106                                 tbinfo->relacl);
12107
12108                 /*
12109                  * Handle column ACLs, if any.  Note: we pull these with a separate
12110                  * query rather than trying to fetch them during getTableAttrs, so
12111                  * that we won't miss ACLs on system columns.
12112                  */
12113                 if (fout->remoteVersion >= 80400)
12114                 {
12115                         PQExpBuffer query = createPQExpBuffer();
12116                         PGresult   *res;
12117                         int                     i;
12118
12119                         appendPQExpBuffer(query,
12120                                            "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12121                                                           "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12122                                                           "ORDER BY attnum",
12123                                                           tbinfo->dobj.catId.oid);
12124                         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12125
12126                         for (i = 0; i < PQntuples(res); i++)
12127                         {
12128                                 char       *attname = PQgetvalue(res, i, 0);
12129                                 char       *attacl = PQgetvalue(res, i, 1);
12130                                 char       *attnamecopy;
12131                                 char       *acltag;
12132
12133                                 attnamecopy = pg_strdup(fmtId(attname));
12134                                 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12135                                 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12136                                 /* Column's GRANT type is always TABLE */
12137                                 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12138                                                 namecopy, attnamecopy, acltag,
12139                                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12140                                                 attacl);
12141                                 free(attnamecopy);
12142                                 free(acltag);
12143                         }
12144                         PQclear(res);
12145                         destroyPQExpBuffer(query);
12146                 }
12147
12148                 free(namecopy);
12149         }
12150 }
12151
12152 /*
12153  * dumpTableSchema
12154  *        write the declaration (not data) of one user-defined table or view
12155  */
12156 static void
12157 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12158 {
12159         PQExpBuffer query = createPQExpBuffer();
12160         PQExpBuffer q = createPQExpBuffer();
12161         PQExpBuffer delq = createPQExpBuffer();
12162         PQExpBuffer labelq = createPQExpBuffer();
12163         PGresult   *res;
12164         int                     numParents;
12165         TableInfo **parents;
12166         int                     actual_atts;    /* number of attrs in this CREATE statment */
12167         const char *reltypename;
12168         char       *storage;
12169         char       *srvname;
12170         char       *ftoptions;
12171         int                     j,
12172                                 k;
12173
12174         /* Make sure we are in proper schema */
12175         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12176
12177         if (binary_upgrade)
12178                 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12179                                                                                                 tbinfo->dobj.catId.oid);
12180
12181         /* Is it a table or a view? */
12182         if (tbinfo->relkind == RELKIND_VIEW)
12183         {
12184                 char       *viewdef;
12185
12186                 reltypename = "VIEW";
12187
12188                 /* Fetch the view definition */
12189                 if (fout->remoteVersion >= 70300)
12190                 {
12191                         /* Beginning in 7.3, viewname is not unique; rely on OID */
12192                         appendPQExpBuffer(query,
12193                                                           "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12194                                                           tbinfo->dobj.catId.oid);
12195                 }
12196                 else
12197                 {
12198                         appendPQExpBuffer(query, "SELECT definition AS viewdef "
12199                                                           "FROM pg_views WHERE viewname = ");
12200                         appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12201                         appendPQExpBuffer(query, ";");
12202                 }
12203
12204                 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12205
12206                 if (PQntuples(res) != 1)
12207                 {
12208                         if (PQntuples(res) < 1)
12209                                 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12210                                                   tbinfo->dobj.name);
12211                         else
12212                                 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12213                                                   tbinfo->dobj.name);
12214                 }
12215
12216                 viewdef = PQgetvalue(res, 0, 0);
12217
12218                 if (strlen(viewdef) == 0)
12219                         exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12220                                                   tbinfo->dobj.name);
12221
12222                 /*
12223                  * DROP must be fully qualified in case same name appears in
12224                  * pg_catalog
12225                  */
12226                 appendPQExpBuffer(delq, "DROP VIEW %s.",
12227                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12228                 appendPQExpBuffer(delq, "%s;\n",
12229                                                   fmtId(tbinfo->dobj.name));
12230
12231                 if (binary_upgrade)
12232                         binary_upgrade_set_pg_class_oids(fout, q,
12233                                                                                          tbinfo->dobj.catId.oid, false);
12234
12235                 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12236                 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12237                         appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12238                 appendPQExpBuffer(q, " AS\n    %s\n", viewdef);
12239
12240                 appendPQExpBuffer(labelq, "VIEW %s",
12241                                                   fmtId(tbinfo->dobj.name));
12242
12243                 PQclear(res);
12244         }
12245         else
12246         {
12247                 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12248                 {
12249                         int                     i_srvname;
12250                         int                     i_ftoptions;
12251
12252                         reltypename = "FOREIGN TABLE";
12253
12254                         /* retrieve name of foreign server and generic options */
12255                         appendPQExpBuffer(query,
12256                                                           "SELECT fs.srvname, "
12257                                                           "pg_catalog.array_to_string(ARRAY("
12258                                                           "SELECT pg_catalog.quote_ident(option_name) || "
12259                                                           "' ' || pg_catalog.quote_literal(option_value) "
12260                                                           "FROM pg_catalog.pg_options_to_table(ftoptions) "
12261                                                           "ORDER BY option_name"
12262                                                           "), E',\n    ') AS ftoptions "
12263                                                           "FROM pg_catalog.pg_foreign_table ft "
12264                                                           "JOIN pg_catalog.pg_foreign_server fs "
12265                                                           "ON (fs.oid = ft.ftserver) "
12266                                                           "WHERE ft.ftrelid = '%u'",
12267                                                           tbinfo->dobj.catId.oid);
12268                         res = ExecuteSqlQueryForSingleRow(fout, query->data);
12269                         i_srvname = PQfnumber(res, "srvname");
12270                         i_ftoptions = PQfnumber(res, "ftoptions");
12271                         srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12272                         ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12273                         PQclear(res);
12274                 }
12275                 else
12276                 {
12277                         reltypename = "TABLE";
12278                         srvname = NULL;
12279                         ftoptions = NULL;
12280                 }
12281                 numParents = tbinfo->numParents;
12282                 parents = tbinfo->parents;
12283
12284                 /*
12285                  * DROP must be fully qualified in case same name appears in
12286                  * pg_catalog
12287                  */
12288                 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12289                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12290                 appendPQExpBuffer(delq, "%s;\n",
12291                                                   fmtId(tbinfo->dobj.name));
12292
12293                 appendPQExpBuffer(labelq, "%s %s", reltypename,
12294                                                   fmtId(tbinfo->dobj.name));
12295
12296                 if (binary_upgrade)
12297                         binary_upgrade_set_pg_class_oids(fout, q,
12298                                                                                          tbinfo->dobj.catId.oid, false);
12299
12300                 appendPQExpBuffer(q, "CREATE %s%s %s",
12301                                                   tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12302                                                   "UNLOGGED " : "",
12303                                                   reltypename,
12304                                                   fmtId(tbinfo->dobj.name));
12305
12306                 /*
12307                  * Attach to type, if reloftype; except in case of a binary upgrade,
12308                  * we dump the table normally and attach it to the type afterward.
12309                  */
12310                 if (tbinfo->reloftype && !binary_upgrade)
12311                         appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12312
12313                 /* Dump the attributes */
12314                 actual_atts = 0;
12315                 for (j = 0; j < tbinfo->numatts; j++)
12316                 {
12317                         /*
12318                          * Normally, dump if it's locally defined in this table, and not
12319                          * dropped.  But for binary upgrade, we'll dump all the columns,
12320                          * and then fix up the dropped and nonlocal cases below.
12321                          */
12322                         if (shouldPrintColumn(tbinfo, j))
12323                         {
12324                                 /*
12325                                  * Default value --- suppress if to be printed separately.
12326                                  */
12327                                 bool            has_default = (tbinfo->attrdefs[j] != NULL &&
12328                                                                                    !tbinfo->attrdefs[j]->separate);
12329
12330                                 /*
12331                                  * Not Null constraint --- suppress if inherited, except in
12332                                  * binary-upgrade case where that won't work.
12333                                  */
12334                                 bool            has_notnull = (tbinfo->notnull[j] &&
12335                                                                                    (!tbinfo->inhNotNull[j] ||
12336                                                                                         binary_upgrade));
12337
12338                                 /* Skip column if fully defined by reloftype */
12339                                 if (tbinfo->reloftype &&
12340                                         !has_default && !has_notnull && !binary_upgrade)
12341                                         continue;
12342
12343                                 /* Format properly if not first attr */
12344                                 if (actual_atts == 0)
12345                                         appendPQExpBuffer(q, " (");
12346                                 else
12347                                         appendPQExpBuffer(q, ",");
12348                                 appendPQExpBuffer(q, "\n    ");
12349                                 actual_atts++;
12350
12351                                 /* Attribute name */
12352                                 appendPQExpBuffer(q, "%s ",
12353                                                                   fmtId(tbinfo->attnames[j]));
12354
12355                                 if (tbinfo->attisdropped[j])
12356                                 {
12357                                         /*
12358                                          * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12359                                          * so we will not have gotten a valid type name; insert
12360                                          * INTEGER as a stopgap.  We'll clean things up later.
12361                                          */
12362                                         appendPQExpBuffer(q, "INTEGER /* dummy */");
12363                                         /* Skip all the rest, too */
12364                                         continue;
12365                                 }
12366
12367                                 /* Attribute type */
12368                                 if (tbinfo->reloftype && !binary_upgrade)
12369                                 {
12370                                         appendPQExpBuffer(q, "WITH OPTIONS");
12371                                 }
12372                                 else if (fout->remoteVersion >= 70100)
12373                                 {
12374                                         appendPQExpBuffer(q, "%s",
12375                                                                           tbinfo->atttypnames[j]);
12376                                 }
12377                                 else
12378                                 {
12379                                         /* If no format_type, fake it */
12380                                         appendPQExpBuffer(q, "%s",
12381                                                                           myFormatType(tbinfo->atttypnames[j],
12382                                                                                                    tbinfo->atttypmod[j]));
12383                                 }
12384
12385                                 /* Add collation if not default for the type */
12386                                 if (OidIsValid(tbinfo->attcollation[j]))
12387                                 {
12388                                         CollInfo   *coll;
12389
12390                                         coll = findCollationByOid(tbinfo->attcollation[j]);
12391                                         if (coll)
12392                                         {
12393                                                 /* always schema-qualify, don't try to be smart */
12394                                                 appendPQExpBuffer(q, " COLLATE %s.",
12395                                                                          fmtId(coll->dobj.namespace->dobj.name));
12396                                                 appendPQExpBuffer(q, "%s",
12397                                                                                   fmtId(coll->dobj.name));
12398                                         }
12399                                 }
12400
12401                                 if (has_default)
12402                                         appendPQExpBuffer(q, " DEFAULT %s",
12403                                                                           tbinfo->attrdefs[j]->adef_expr);
12404
12405                                 if (has_notnull)
12406                                         appendPQExpBuffer(q, " NOT NULL");
12407                         }
12408                 }
12409
12410                 /*
12411                  * Add non-inherited CHECK constraints, if any.
12412                  */
12413                 for (j = 0; j < tbinfo->ncheck; j++)
12414                 {
12415                         ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12416
12417                         if (constr->separate || !constr->conislocal)
12418                                 continue;
12419
12420                         if (actual_atts == 0)
12421                                 appendPQExpBuffer(q, " (\n    ");
12422                         else
12423                                 appendPQExpBuffer(q, ",\n    ");
12424
12425                         appendPQExpBuffer(q, "CONSTRAINT %s ",
12426                                                           fmtId(constr->dobj.name));
12427                         appendPQExpBuffer(q, "%s", constr->condef);
12428
12429                         actual_atts++;
12430                 }
12431
12432                 if (actual_atts)
12433                         appendPQExpBuffer(q, "\n)");
12434                 else if (!(tbinfo->reloftype && !binary_upgrade))
12435                 {
12436                         /*
12437                          * We must have a parenthesized attribute list, even though empty,
12438                          * when not using the OF TYPE syntax.
12439                          */
12440                         appendPQExpBuffer(q, " (\n)");
12441                 }
12442
12443                 if (numParents > 0 && !binary_upgrade)
12444                 {
12445                         appendPQExpBuffer(q, "\nINHERITS (");
12446                         for (k = 0; k < numParents; k++)
12447                         {
12448                                 TableInfo  *parentRel = parents[k];
12449
12450                                 if (k > 0)
12451                                         appendPQExpBuffer(q, ", ");
12452                                 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12453                                         appendPQExpBuffer(q, "%s.",
12454                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
12455                                 appendPQExpBuffer(q, "%s",
12456                                                                   fmtId(parentRel->dobj.name));
12457                         }
12458                         appendPQExpBuffer(q, ")");
12459                 }
12460
12461                 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12462                         appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12463
12464                 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12465                   (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12466                 {
12467                         bool            addcomma = false;
12468
12469                         appendPQExpBuffer(q, "\nWITH (");
12470                         if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12471                         {
12472                                 addcomma = true;
12473                                 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12474                         }
12475                         if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12476                         {
12477                                 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12478                                                                   tbinfo->toast_reloptions);
12479                         }
12480                         appendPQExpBuffer(q, ")");
12481                 }
12482
12483                 /* Dump generic options if any */
12484                 if (ftoptions && ftoptions[0])
12485                         appendPQExpBuffer(q, "\nOPTIONS (\n    %s\n)", ftoptions);
12486
12487                 appendPQExpBuffer(q, ";\n");
12488
12489                 /*
12490                  * To create binary-compatible heap files, we have to ensure the same
12491                  * physical column order, including dropped columns, as in the
12492                  * original.  Therefore, we create dropped columns above and drop them
12493                  * here, also updating their attlen/attalign values so that the
12494                  * dropped column can be skipped properly.      (We do not bother with
12495                  * restoring the original attbyval setting.)  Also, inheritance
12496                  * relationships are set up by doing ALTER INHERIT rather than using
12497                  * an INHERITS clause --- the latter would possibly mess up the column
12498                  * order.  That also means we have to take care about setting
12499                  * attislocal correctly, plus fix up any inherited CHECK constraints.
12500                  * Analogously, we set up typed tables using ALTER TABLE / OF here.
12501                  */
12502                 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12503                 {
12504                         for (j = 0; j < tbinfo->numatts; j++)
12505                         {
12506                                 if (tbinfo->attisdropped[j])
12507                                 {
12508                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12509                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12510                                                                           "SET attlen = %d, "
12511                                                                           "attalign = '%c', attbyval = false\n"
12512                                                                           "WHERE attname = ",
12513                                                                           tbinfo->attlen[j],
12514                                                                           tbinfo->attalign[j]);
12515                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12516                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
12517                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12518                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12519
12520                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12521                                                                           fmtId(tbinfo->dobj.name));
12522                                         appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12523                                                                           fmtId(tbinfo->attnames[j]));
12524                                 }
12525                                 else if (!tbinfo->attislocal[j])
12526                                 {
12527                                         appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12528                                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12529                                                                           "SET attislocal = false\n"
12530                                                                           "WHERE attname = ");
12531                                         appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12532                                         appendPQExpBuffer(q, "\n  AND attrelid = ");
12533                                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12534                                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12535                                 }
12536                         }
12537
12538                         for (k = 0; k < tbinfo->ncheck; k++)
12539                         {
12540                                 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12541
12542                                 if (constr->separate || constr->conislocal)
12543                                         continue;
12544
12545                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12546                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12547                                                                   fmtId(tbinfo->dobj.name));
12548                                 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12549                                                                   fmtId(constr->dobj.name));
12550                                 appendPQExpBuffer(q, "%s;\n", constr->condef);
12551                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
12552                                                                   "SET conislocal = false\n"
12553                                                                   "WHERE contype = 'c' AND conname = ");
12554                                 appendStringLiteralAH(q, constr->dobj.name, fout);
12555                                 appendPQExpBuffer(q, "\n  AND conrelid = ");
12556                                 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12557                                 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12558                         }
12559
12560                         if (numParents > 0)
12561                         {
12562                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
12563                                 for (k = 0; k < numParents; k++)
12564                                 {
12565                                         TableInfo  *parentRel = parents[k];
12566
12567                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
12568                                                                           fmtId(tbinfo->dobj.name));
12569                                         if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12570                                                 appendPQExpBuffer(q, "%s.",
12571                                                                 fmtId(parentRel->dobj.namespace->dobj.name));
12572                                         appendPQExpBuffer(q, "%s;\n",
12573                                                                           fmtId(parentRel->dobj.name));
12574                                 }
12575                         }
12576
12577                         if (tbinfo->reloftype)
12578                         {
12579                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
12580                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
12581                                                                   fmtId(tbinfo->dobj.name),
12582                                                                   tbinfo->reloftype);
12583                         }
12584
12585                         appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
12586                         appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12587                                                           "SET relfrozenxid = '%u'\n"
12588                                                           "WHERE oid = ",
12589                                                           tbinfo->frozenxid);
12590                         appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12591                         appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12592
12593                         if (tbinfo->toast_oid)
12594                         {
12595                                 /* We preserve the toast oids, so we can use it during restore */
12596                                 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
12597                                 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12598                                                                   "SET relfrozenxid = '%u'\n"
12599                                                                   "WHERE oid = '%u';\n",
12600                                                                   tbinfo->toast_frozenxid, tbinfo->toast_oid);
12601                         }
12602                 }
12603
12604                 /*
12605                  * Dump additional per-column properties that we can't handle in the
12606                  * main CREATE TABLE command.
12607                  */
12608                 for (j = 0; j < tbinfo->numatts; j++)
12609                 {
12610                         /* None of this applies to dropped columns */
12611                         if (tbinfo->attisdropped[j])
12612                                 continue;
12613
12614                         /*
12615                          * If we didn't dump the column definition explicitly above, and
12616                          * it is NOT NULL and did not inherit that property from a parent,
12617                          * we have to mark it separately.
12618                          */
12619                         if (!shouldPrintColumn(tbinfo, j) &&
12620                                 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
12621                         {
12622                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12623                                                                   fmtId(tbinfo->dobj.name));
12624                                 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
12625                                                                   fmtId(tbinfo->attnames[j]));
12626                         }
12627
12628                         /*
12629                          * Dump per-column statistics information. We only issue an ALTER
12630                          * TABLE statement if the attstattarget entry for this column is
12631                          * non-negative (i.e. it's not the default value)
12632                          */
12633                         if (tbinfo->attstattarget[j] >= 0)
12634                         {
12635                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12636                                                                   fmtId(tbinfo->dobj.name));
12637                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12638                                                                   fmtId(tbinfo->attnames[j]));
12639                                 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
12640                                                                   tbinfo->attstattarget[j]);
12641                         }
12642
12643                         /*
12644                          * Dump per-column storage information.  The statement is only
12645                          * dumped if the storage has been changed from the type's default.
12646                          */
12647                         if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
12648                         {
12649                                 switch (tbinfo->attstorage[j])
12650                                 {
12651                                         case 'p':
12652                                                 storage = "PLAIN";
12653                                                 break;
12654                                         case 'e':
12655                                                 storage = "EXTERNAL";
12656                                                 break;
12657                                         case 'm':
12658                                                 storage = "MAIN";
12659                                                 break;
12660                                         case 'x':
12661                                                 storage = "EXTENDED";
12662                                                 break;
12663                                         default:
12664                                                 storage = NULL;
12665                                 }
12666
12667                                 /*
12668                                  * Only dump the statement if it's a storage type we recognize
12669                                  */
12670                                 if (storage != NULL)
12671                                 {
12672                                         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12673                                                                           fmtId(tbinfo->dobj.name));
12674                                         appendPQExpBuffer(q, "ALTER COLUMN %s ",
12675                                                                           fmtId(tbinfo->attnames[j]));
12676                                         appendPQExpBuffer(q, "SET STORAGE %s;\n",
12677                                                                           storage);
12678                                 }
12679                         }
12680
12681                         /*
12682                          * Dump per-column attributes.
12683                          */
12684                         if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
12685                         {
12686                                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12687                                                                   fmtId(tbinfo->dobj.name));
12688                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12689                                                                   fmtId(tbinfo->attnames[j]));
12690                                 appendPQExpBuffer(q, "SET (%s);\n",
12691                                                                   tbinfo->attoptions[j]);
12692                         }
12693
12694                         /*
12695                          * Dump per-column fdw options.
12696                          */
12697                         if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
12698                                 tbinfo->attfdwoptions[j] &&
12699                                 tbinfo->attfdwoptions[j][0] != '\0')
12700                         {
12701                                 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
12702                                                                   fmtId(tbinfo->dobj.name));
12703                                 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12704                                                                   fmtId(tbinfo->attnames[j]));
12705                                 appendPQExpBuffer(q, "OPTIONS (\n    %s\n);\n",
12706                                                                   tbinfo->attfdwoptions[j]);
12707                         }
12708                 }
12709         }
12710
12711         if (binary_upgrade)
12712                 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
12713
12714         ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12715                                  tbinfo->dobj.name,
12716                                  tbinfo->dobj.namespace->dobj.name,
12717                         (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
12718                                  tbinfo->rolname,
12719                            (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
12720                                  reltypename, SECTION_PRE_DATA,
12721                                  q->data, delq->data, NULL,
12722                                  tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
12723                                  NULL, NULL);
12724
12725
12726         /* Dump Table Comments */
12727         dumpTableComment(fout, tbinfo, reltypename);
12728
12729         /* Dump Table Security Labels */
12730         dumpTableSecLabel(fout, tbinfo, reltypename);
12731
12732         /* Dump comments on inlined table constraints */
12733         for (j = 0; j < tbinfo->ncheck; j++)
12734         {
12735                 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12736
12737                 if (constr->separate || !constr->conislocal)
12738                         continue;
12739
12740                 dumpTableConstraintComment(fout, constr);
12741         }
12742
12743         destroyPQExpBuffer(query);
12744         destroyPQExpBuffer(q);
12745         destroyPQExpBuffer(delq);
12746         destroyPQExpBuffer(labelq);
12747 }
12748
12749 /*
12750  * dumpAttrDef --- dump an attribute's default-value declaration
12751  */
12752 static void
12753 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
12754 {
12755         TableInfo  *tbinfo = adinfo->adtable;
12756         int                     adnum = adinfo->adnum;
12757         PQExpBuffer q;
12758         PQExpBuffer delq;
12759
12760         /* Skip if table definition not to be dumped */
12761         if (!tbinfo->dobj.dump || dataOnly)
12762                 return;
12763
12764         /* Skip if not "separate"; it was dumped in the table's definition */
12765         if (!adinfo->separate)
12766                 return;
12767
12768         q = createPQExpBuffer();
12769         delq = createPQExpBuffer();
12770
12771         appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12772                                           fmtId(tbinfo->dobj.name));
12773         appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
12774                                           fmtId(tbinfo->attnames[adnum - 1]),
12775                                           adinfo->adef_expr);
12776
12777         /*
12778          * DROP must be fully qualified in case same name appears in pg_catalog
12779          */
12780         appendPQExpBuffer(delq, "ALTER TABLE %s.",
12781                                           fmtId(tbinfo->dobj.namespace->dobj.name));
12782         appendPQExpBuffer(delq, "%s ",
12783                                           fmtId(tbinfo->dobj.name));
12784         appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
12785                                           fmtId(tbinfo->attnames[adnum - 1]));
12786
12787         ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
12788                                  tbinfo->attnames[adnum - 1],
12789                                  tbinfo->dobj.namespace->dobj.name,
12790                                  NULL,
12791                                  tbinfo->rolname,
12792                                  false, "DEFAULT", SECTION_PRE_DATA,
12793                                  q->data, delq->data, NULL,
12794                                  adinfo->dobj.dependencies, adinfo->dobj.nDeps,
12795                                  NULL, NULL);
12796
12797         destroyPQExpBuffer(q);
12798         destroyPQExpBuffer(delq);
12799 }
12800
12801 /*
12802  * getAttrName: extract the correct name for an attribute
12803  *
12804  * The array tblInfo->attnames[] only provides names of user attributes;
12805  * if a system attribute number is supplied, we have to fake it.
12806  * We also do a little bit of bounds checking for safety's sake.
12807  */
12808 static const char *
12809 getAttrName(int attrnum, TableInfo *tblInfo)
12810 {
12811         if (attrnum > 0 && attrnum <= tblInfo->numatts)
12812                 return tblInfo->attnames[attrnum - 1];
12813         switch (attrnum)
12814         {
12815                 case SelfItemPointerAttributeNumber:
12816                         return "ctid";
12817                 case ObjectIdAttributeNumber:
12818                         return "oid";
12819                 case MinTransactionIdAttributeNumber:
12820                         return "xmin";
12821                 case MinCommandIdAttributeNumber:
12822                         return "cmin";
12823                 case MaxTransactionIdAttributeNumber:
12824                         return "xmax";
12825                 case MaxCommandIdAttributeNumber:
12826                         return "cmax";
12827                 case TableOidAttributeNumber:
12828                         return "tableoid";
12829         }
12830         exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
12831                                   attrnum, tblInfo->dobj.name);
12832         return NULL;                            /* keep compiler quiet */
12833 }
12834
12835 /*
12836  * dumpIndex
12837  *        write out to fout a user-defined index
12838  */
12839 static void
12840 dumpIndex(Archive *fout, IndxInfo *indxinfo)
12841 {
12842         TableInfo  *tbinfo = indxinfo->indextable;
12843         PQExpBuffer q;
12844         PQExpBuffer delq;
12845         PQExpBuffer labelq;
12846
12847         if (dataOnly)
12848                 return;
12849
12850         q = createPQExpBuffer();
12851         delq = createPQExpBuffer();
12852         labelq = createPQExpBuffer();
12853
12854         appendPQExpBuffer(labelq, "INDEX %s",
12855                                           fmtId(indxinfo->dobj.name));
12856
12857         /*
12858          * If there's an associated constraint, don't dump the index per se, but
12859          * do dump any comment for it.  (This is safe because dependency ordering
12860          * will have ensured the constraint is emitted first.)
12861          */
12862         if (indxinfo->indexconstraint == 0)
12863         {
12864                 if (binary_upgrade)
12865                         binary_upgrade_set_pg_class_oids(fout, q,
12866                                                                                          indxinfo->dobj.catId.oid, true);
12867
12868                 /* Plain secondary index */
12869                 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
12870
12871                 /* If the index is clustered, we need to record that. */
12872                 if (indxinfo->indisclustered)
12873                 {
12874                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12875                                                           fmtId(tbinfo->dobj.name));
12876                         appendPQExpBuffer(q, " ON %s;\n",
12877                                                           fmtId(indxinfo->dobj.name));
12878                 }
12879
12880                 /*
12881                  * DROP must be fully qualified in case same name appears in
12882                  * pg_catalog
12883                  */
12884                 appendPQExpBuffer(delq, "DROP INDEX %s.",
12885                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
12886                 appendPQExpBuffer(delq, "%s;\n",
12887                                                   fmtId(indxinfo->dobj.name));
12888
12889                 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
12890                                          indxinfo->dobj.name,
12891                                          tbinfo->dobj.namespace->dobj.name,
12892                                          indxinfo->tablespace,
12893                                          tbinfo->rolname, false,
12894                                          "INDEX", SECTION_POST_DATA,
12895                                          q->data, delq->data, NULL,
12896                                          indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
12897                                          NULL, NULL);
12898         }
12899
12900         /* Dump Index Comments */
12901         dumpComment(fout, labelq->data,
12902                                 tbinfo->dobj.namespace->dobj.name,
12903                                 tbinfo->rolname,
12904                                 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
12905
12906         destroyPQExpBuffer(q);
12907         destroyPQExpBuffer(delq);
12908         destroyPQExpBuffer(labelq);
12909 }
12910
12911 /*
12912  * dumpConstraint
12913  *        write out to fout a user-defined constraint
12914  */
12915 static void
12916 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
12917 {
12918         TableInfo  *tbinfo = coninfo->contable;
12919         PQExpBuffer q;
12920         PQExpBuffer delq;
12921
12922         /* Skip if not to be dumped */
12923         if (!coninfo->dobj.dump || dataOnly)
12924                 return;
12925
12926         q = createPQExpBuffer();
12927         delq = createPQExpBuffer();
12928
12929         if (coninfo->contype == 'p' ||
12930                 coninfo->contype == 'u' ||
12931                 coninfo->contype == 'x')
12932         {
12933                 /* Index-related constraint */
12934                 IndxInfo   *indxinfo;
12935                 int                     k;
12936
12937                 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
12938
12939                 if (indxinfo == NULL)
12940                         exit_horribly(NULL, "missing index for constraint \"%s\"\n",
12941                                                   coninfo->dobj.name);
12942
12943                 if (binary_upgrade)
12944                         binary_upgrade_set_pg_class_oids(fout, q,
12945                                                                                          indxinfo->dobj.catId.oid, true);
12946
12947                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
12948                                                   fmtId(tbinfo->dobj.name));
12949                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s ",
12950                                                   fmtId(coninfo->dobj.name));
12951
12952                 if (coninfo->condef)
12953                 {
12954                         /* pg_get_constraintdef should have provided everything */
12955                         appendPQExpBuffer(q, "%s;\n", coninfo->condef);
12956                 }
12957                 else
12958                 {
12959                         appendPQExpBuffer(q, "%s (",
12960                                                  coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
12961                         for (k = 0; k < indxinfo->indnkeys; k++)
12962                         {
12963                                 int                     indkey = (int) indxinfo->indkeys[k];
12964                                 const char *attname;
12965
12966                                 if (indkey == InvalidAttrNumber)
12967                                         break;
12968                                 attname = getAttrName(indkey, tbinfo);
12969
12970                                 appendPQExpBuffer(q, "%s%s",
12971                                                                   (k == 0) ? "" : ", ",
12972                                                                   fmtId(attname));
12973                         }
12974
12975                         appendPQExpBuffer(q, ")");
12976
12977                         if (indxinfo->options && strlen(indxinfo->options) > 0)
12978                                 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
12979
12980                         if (coninfo->condeferrable)
12981                         {
12982                                 appendPQExpBuffer(q, " DEFERRABLE");
12983                                 if (coninfo->condeferred)
12984                                         appendPQExpBuffer(q, " INITIALLY DEFERRED");
12985                         }
12986
12987                         appendPQExpBuffer(q, ";\n");
12988                 }
12989
12990                 /* If the index is clustered, we need to record that. */
12991                 if (indxinfo->indisclustered)
12992                 {
12993                         appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12994                                                           fmtId(tbinfo->dobj.name));
12995                         appendPQExpBuffer(q, " ON %s;\n",
12996                                                           fmtId(indxinfo->dobj.name));
12997                 }
12998
12999                 /*
13000                  * DROP must be fully qualified in case same name appears in
13001                  * pg_catalog
13002                  */
13003                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13004                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13005                 appendPQExpBuffer(delq, "%s ",
13006                                                   fmtId(tbinfo->dobj.name));
13007                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13008                                                   fmtId(coninfo->dobj.name));
13009
13010                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13011                                          coninfo->dobj.name,
13012                                          tbinfo->dobj.namespace->dobj.name,
13013                                          indxinfo->tablespace,
13014                                          tbinfo->rolname, false,
13015                                          "CONSTRAINT", SECTION_POST_DATA,
13016                                          q->data, delq->data, NULL,
13017                                          coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13018                                          NULL, NULL);
13019         }
13020         else if (coninfo->contype == 'f')
13021         {
13022                 /*
13023                  * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13024                  * current table data is not processed
13025                  */
13026                 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13027                                                   fmtId(tbinfo->dobj.name));
13028                 appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13029                                                   fmtId(coninfo->dobj.name),
13030                                                   coninfo->condef);
13031
13032                 /*
13033                  * DROP must be fully qualified in case same name appears in
13034                  * pg_catalog
13035                  */
13036                 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13037                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13038                 appendPQExpBuffer(delq, "%s ",
13039                                                   fmtId(tbinfo->dobj.name));
13040                 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13041                                                   fmtId(coninfo->dobj.name));
13042
13043                 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13044                                          coninfo->dobj.name,
13045                                          tbinfo->dobj.namespace->dobj.name,
13046                                          NULL,
13047                                          tbinfo->rolname, false,
13048                                          "FK CONSTRAINT", SECTION_POST_DATA,
13049                                          q->data, delq->data, NULL,
13050                                          coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13051                                          NULL, NULL);
13052         }
13053         else if (coninfo->contype == 'c' && tbinfo)
13054         {
13055                 /* CHECK constraint on a table */
13056
13057                 /* Ignore if not to be dumped separately */
13058                 if (coninfo->separate)
13059                 {
13060                         /* add ONLY if we do not want it to propagate to children */
13061                         appendPQExpBuffer(q, "ALTER TABLE %s %s\n",
13062                                                          coninfo->conisonly ? "ONLY" : "", fmtId(tbinfo->dobj.name));
13063                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13064                                                           fmtId(coninfo->dobj.name),
13065                                                           coninfo->condef);
13066
13067                         /*
13068                          * DROP must be fully qualified in case same name appears in
13069                          * pg_catalog
13070                          */
13071                         appendPQExpBuffer(delq, "ALTER TABLE %s.",
13072                                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13073                         appendPQExpBuffer(delq, "%s ",
13074                                                           fmtId(tbinfo->dobj.name));
13075                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13076                                                           fmtId(coninfo->dobj.name));
13077
13078                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13079                                                  coninfo->dobj.name,
13080                                                  tbinfo->dobj.namespace->dobj.name,
13081                                                  NULL,
13082                                                  tbinfo->rolname, false,
13083                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13084                                                  q->data, delq->data, NULL,
13085                                                  coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13086                                                  NULL, NULL);
13087                 }
13088         }
13089         else if (coninfo->contype == 'c' && tbinfo == NULL)
13090         {
13091                 /* CHECK constraint on a domain */
13092                 TypeInfo   *tyinfo = coninfo->condomain;
13093
13094                 /* Ignore if not to be dumped separately */
13095                 if (coninfo->separate)
13096                 {
13097                         appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13098                                                           fmtId(tyinfo->dobj.name));
13099                         appendPQExpBuffer(q, "    ADD CONSTRAINT %s %s;\n",
13100                                                           fmtId(coninfo->dobj.name),
13101                                                           coninfo->condef);
13102
13103                         /*
13104                          * DROP must be fully qualified in case same name appears in
13105                          * pg_catalog
13106                          */
13107                         appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13108                                                           fmtId(tyinfo->dobj.namespace->dobj.name));
13109                         appendPQExpBuffer(delq, "%s ",
13110                                                           fmtId(tyinfo->dobj.name));
13111                         appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13112                                                           fmtId(coninfo->dobj.name));
13113
13114                         ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13115                                                  coninfo->dobj.name,
13116                                                  tyinfo->dobj.namespace->dobj.name,
13117                                                  NULL,
13118                                                  tyinfo->rolname, false,
13119                                                  "CHECK CONSTRAINT", SECTION_POST_DATA,
13120                                                  q->data, delq->data, NULL,
13121                                                  coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13122                                                  NULL, NULL);
13123                 }
13124         }
13125         else
13126         {
13127                 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13128                                           coninfo->contype);
13129         }
13130
13131         /* Dump Constraint Comments --- only works for table constraints */
13132         if (tbinfo && coninfo->separate)
13133                 dumpTableConstraintComment(fout, coninfo);
13134
13135         destroyPQExpBuffer(q);
13136         destroyPQExpBuffer(delq);
13137 }
13138
13139 /*
13140  * dumpTableConstraintComment --- dump a constraint's comment if any
13141  *
13142  * This is split out because we need the function in two different places
13143  * depending on whether the constraint is dumped as part of CREATE TABLE
13144  * or as a separate ALTER command.
13145  */
13146 static void
13147 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13148 {
13149         TableInfo  *tbinfo = coninfo->contable;
13150         PQExpBuffer labelq = createPQExpBuffer();
13151
13152         appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13153                                           fmtId(coninfo->dobj.name));
13154         appendPQExpBuffer(labelq, "ON %s",
13155                                           fmtId(tbinfo->dobj.name));
13156         dumpComment(fout, labelq->data,
13157                                 tbinfo->dobj.namespace->dobj.name,
13158                                 tbinfo->rolname,
13159                                 coninfo->dobj.catId, 0,
13160                          coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13161
13162         destroyPQExpBuffer(labelq);
13163 }
13164
13165 /*
13166  * findLastBuiltInOid -
13167  * find the last built in oid
13168  *
13169  * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13170  * pg_database entry for the current database
13171  */
13172 static Oid
13173 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13174 {
13175         PGresult   *res;
13176         Oid                     last_oid;
13177         PQExpBuffer query = createPQExpBuffer();
13178
13179         resetPQExpBuffer(query);
13180         appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13181         appendStringLiteralAH(query, dbname, fout);
13182
13183         res = ExecuteSqlQueryForSingleRow(fout, query->data);
13184         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13185         PQclear(res);
13186         destroyPQExpBuffer(query);
13187         return last_oid;
13188 }
13189
13190 /*
13191  * findLastBuiltInOid -
13192  * find the last built in oid
13193  *
13194  * For 7.0, we do this by assuming that the last thing that initdb does is to
13195  * create the pg_indexes view.  This sucks in general, but seeing that 7.0.x
13196  * initdb won't be changing anymore, it'll do.
13197  */
13198 static Oid
13199 findLastBuiltinOid_V70(Archive *fout)
13200 {
13201         PGresult   *res;
13202         int                     last_oid;
13203
13204         res = ExecuteSqlQueryForSingleRow(fout,
13205                                         "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13206         last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13207         PQclear(res);
13208         return last_oid;
13209 }
13210
13211 static void
13212 dumpSequence(Archive *fout, TableInfo *tbinfo)
13213 {
13214         PGresult   *res;
13215         char       *startv,
13216                            *last,
13217                            *incby,
13218                            *maxv = NULL,
13219                            *minv = NULL,
13220                            *cache;
13221         char            bufm[100],
13222                                 bufx[100];
13223         bool            cycled,
13224                                 called;
13225         PQExpBuffer query = createPQExpBuffer();
13226         PQExpBuffer delqry = createPQExpBuffer();
13227         PQExpBuffer labelq = createPQExpBuffer();
13228
13229         /* Make sure we are in proper schema */
13230         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13231
13232         snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13233         snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13234
13235         if (fout->remoteVersion >= 80400)
13236         {
13237                 appendPQExpBuffer(query,
13238                                                   "SELECT sequence_name, "
13239                                                   "start_value, last_value, increment_by, "
13240                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13241                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13242                                                   "     ELSE max_value "
13243                                                   "END AS max_value, "
13244                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13245                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13246                                                   "     ELSE min_value "
13247                                                   "END AS min_value, "
13248                                                   "cache_value, is_cycled, is_called from %s",
13249                                                   bufx, bufm,
13250                                                   fmtId(tbinfo->dobj.name));
13251         }
13252         else
13253         {
13254                 appendPQExpBuffer(query,
13255                                                   "SELECT sequence_name, "
13256                                                   "0 AS start_value, last_value, increment_by, "
13257                                    "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13258                                    "     WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13259                                                   "     ELSE max_value "
13260                                                   "END AS max_value, "
13261                                         "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13262                                    "     WHEN increment_by < 0 AND min_value = %s THEN NULL "
13263                                                   "     ELSE min_value "
13264                                                   "END AS min_value, "
13265                                                   "cache_value, is_cycled, is_called from %s",
13266                                                   bufx, bufm,
13267                                                   fmtId(tbinfo->dobj.name));
13268         }
13269
13270         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13271
13272         if (PQntuples(res) != 1)
13273         {
13274                 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13275                                                                  "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13276                                                                  PQntuples(res)),
13277                                   tbinfo->dobj.name, PQntuples(res));
13278                 exit_nicely(1);
13279         }
13280
13281         /* Disable this check: it fails if sequence has been renamed */
13282 #ifdef NOT_USED
13283         if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13284         {
13285                 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13286                                   tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13287                 exit_nicely(1);
13288         }
13289 #endif
13290
13291         startv = PQgetvalue(res, 0, 1);
13292         last = PQgetvalue(res, 0, 2);
13293         incby = PQgetvalue(res, 0, 3);
13294         if (!PQgetisnull(res, 0, 4))
13295                 maxv = PQgetvalue(res, 0, 4);
13296         if (!PQgetisnull(res, 0, 5))
13297                 minv = PQgetvalue(res, 0, 5);
13298         cache = PQgetvalue(res, 0, 6);
13299         cycled = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
13300         called = (strcmp(PQgetvalue(res, 0, 8), "t") == 0);
13301
13302         /*
13303          * The logic we use for restoring sequences is as follows:
13304          *
13305          * Add a CREATE SEQUENCE statement as part of a "schema" dump (use
13306          * last_val for start if called is false, else use min_val for start_val).
13307          * Also, if the sequence is owned by a column, add an ALTER SEQUENCE OWNED
13308          * BY command for it.
13309          *
13310          * Add a 'SETVAL(seq, last_val, iscalled)' as part of a "data" dump.
13311          */
13312         if (!dataOnly)
13313         {
13314                 /*
13315                  * DROP must be fully qualified in case same name appears in
13316                  * pg_catalog
13317                  */
13318                 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13319                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13320                 appendPQExpBuffer(delqry, "%s;\n",
13321                                                   fmtId(tbinfo->dobj.name));
13322
13323                 resetPQExpBuffer(query);
13324
13325                 if (binary_upgrade)
13326                 {
13327                         binary_upgrade_set_pg_class_oids(fout, query,
13328                                                                                          tbinfo->dobj.catId.oid, false);
13329                         binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13330                                                                                                         tbinfo->dobj.catId.oid);
13331                 }
13332
13333                 appendPQExpBuffer(query,
13334                                                   "CREATE SEQUENCE %s\n",
13335                                                   fmtId(tbinfo->dobj.name));
13336
13337                 if (fout->remoteVersion >= 80400)
13338                         appendPQExpBuffer(query, "    START WITH %s\n", startv);
13339                 else
13340                 {
13341                         /*
13342                          * Versions before 8.4 did not remember the true start value.  If
13343                          * is_called is false then the sequence has never been incremented
13344                          * so we can use last_val.      Otherwise punt and let it default.
13345                          */
13346                         if (!called)
13347                                 appendPQExpBuffer(query, "    START WITH %s\n", last);
13348                 }
13349
13350                 appendPQExpBuffer(query, "    INCREMENT BY %s\n", incby);
13351
13352                 if (minv)
13353                         appendPQExpBuffer(query, "    MINVALUE %s\n", minv);
13354                 else
13355                         appendPQExpBuffer(query, "    NO MINVALUE\n");
13356
13357                 if (maxv)
13358                         appendPQExpBuffer(query, "    MAXVALUE %s\n", maxv);
13359                 else
13360                         appendPQExpBuffer(query, "    NO MAXVALUE\n");
13361
13362                 appendPQExpBuffer(query,
13363                                                   "    CACHE %s%s",
13364                                                   cache, (cycled ? "\n    CYCLE" : ""));
13365
13366                 appendPQExpBuffer(query, ";\n");
13367
13368                 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13369
13370                 /* binary_upgrade:      no need to clear TOAST table oid */
13371
13372                 if (binary_upgrade)
13373                         binary_upgrade_extension_member(query, &tbinfo->dobj,
13374                                                                                         labelq->data);
13375
13376                 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13377                                          tbinfo->dobj.name,
13378                                          tbinfo->dobj.namespace->dobj.name,
13379                                          NULL,
13380                                          tbinfo->rolname,
13381                                          false, "SEQUENCE", SECTION_PRE_DATA,
13382                                          query->data, delqry->data, NULL,
13383                                          tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
13384                                          NULL, NULL);
13385
13386                 /*
13387                  * If the sequence is owned by a table column, emit the ALTER for it
13388                  * as a separate TOC entry immediately following the sequence's own
13389                  * entry.  It's OK to do this rather than using full sorting logic,
13390                  * because the dependency that tells us it's owned will have forced
13391                  * the table to be created first.  We can't just include the ALTER in
13392                  * the TOC entry because it will fail if we haven't reassigned the
13393                  * sequence owner to match the table's owner.
13394                  *
13395                  * We need not schema-qualify the table reference because both
13396                  * sequence and table must be in the same schema.
13397                  */
13398                 if (OidIsValid(tbinfo->owning_tab))
13399                 {
13400                         TableInfo  *owning_tab = findTableByOid(tbinfo->owning_tab);
13401
13402                         if (owning_tab && owning_tab->dobj.dump)
13403                         {
13404                                 resetPQExpBuffer(query);
13405                                 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13406                                                                   fmtId(tbinfo->dobj.name));
13407                                 appendPQExpBuffer(query, " OWNED BY %s",
13408                                                                   fmtId(owning_tab->dobj.name));
13409                                 appendPQExpBuffer(query, ".%s;\n",
13410                                                 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13411
13412                                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13413                                                          tbinfo->dobj.name,
13414                                                          tbinfo->dobj.namespace->dobj.name,
13415                                                          NULL,
13416                                                          tbinfo->rolname,
13417                                                          false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13418                                                          query->data, "", NULL,
13419                                                          &(tbinfo->dobj.dumpId), 1,
13420                                                          NULL, NULL);
13421                         }
13422                 }
13423
13424                 /* Dump Sequence Comments and Security Labels */
13425                 dumpComment(fout, labelq->data,
13426                                         tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13427                                         tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13428                 dumpSecLabel(fout, labelq->data,
13429                                          tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13430                                          tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13431         }
13432
13433         if (!schemaOnly)
13434         {
13435                 resetPQExpBuffer(query);
13436                 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13437                 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13438                 appendPQExpBuffer(query, ", %s, %s);\n",
13439                                                   last, (called ? "true" : "false"));
13440
13441                 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13442                                          tbinfo->dobj.name,
13443                                          tbinfo->dobj.namespace->dobj.name,
13444                                          NULL,
13445                                          tbinfo->rolname,
13446                                          false, "SEQUENCE SET", SECTION_PRE_DATA,
13447                                          query->data, "", NULL,
13448                                          &(tbinfo->dobj.dumpId), 1,
13449                                          NULL, NULL);
13450         }
13451
13452         PQclear(res);
13453
13454         destroyPQExpBuffer(query);
13455         destroyPQExpBuffer(delqry);
13456         destroyPQExpBuffer(labelq);
13457 }
13458
13459 static void
13460 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13461 {
13462         TableInfo  *tbinfo = tginfo->tgtable;
13463         PQExpBuffer query;
13464         PQExpBuffer delqry;
13465         PQExpBuffer labelq;
13466         char       *tgargs;
13467         size_t          lentgargs;
13468         const char *p;
13469         int                     findx;
13470
13471         if (dataOnly)
13472                 return;
13473
13474         query = createPQExpBuffer();
13475         delqry = createPQExpBuffer();
13476         labelq = createPQExpBuffer();
13477
13478         /*
13479          * DROP must be fully qualified in case same name appears in pg_catalog
13480          */
13481         appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13482                                           fmtId(tginfo->dobj.name));
13483         appendPQExpBuffer(delqry, "ON %s.",
13484                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13485         appendPQExpBuffer(delqry, "%s;\n",
13486                                           fmtId(tbinfo->dobj.name));
13487
13488         if (tginfo->tgdef)
13489         {
13490                 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13491         }
13492         else
13493         {
13494                 if (tginfo->tgisconstraint)
13495                 {
13496                         appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13497                         appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13498                 }
13499                 else
13500                 {
13501                         appendPQExpBuffer(query, "CREATE TRIGGER ");
13502                         appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13503                 }
13504                 appendPQExpBuffer(query, "\n    ");
13505
13506                 /* Trigger type */
13507                 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13508                         appendPQExpBuffer(query, "BEFORE");
13509                 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13510                         appendPQExpBuffer(query, "AFTER");
13511                 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13512                         appendPQExpBuffer(query, "INSTEAD OF");
13513                 else
13514                 {
13515                         write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13516                         exit_nicely(1);
13517                 }
13518
13519                 findx = 0;
13520                 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13521                 {
13522                         appendPQExpBuffer(query, " INSERT");
13523                         findx++;
13524                 }
13525                 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13526                 {
13527                         if (findx > 0)
13528                                 appendPQExpBuffer(query, " OR DELETE");
13529                         else
13530                                 appendPQExpBuffer(query, " DELETE");
13531                         findx++;
13532                 }
13533                 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13534                 {
13535                         if (findx > 0)
13536                                 appendPQExpBuffer(query, " OR UPDATE");
13537                         else
13538                                 appendPQExpBuffer(query, " UPDATE");
13539                         findx++;
13540                 }
13541                 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
13542                 {
13543                         if (findx > 0)
13544                                 appendPQExpBuffer(query, " OR TRUNCATE");
13545                         else
13546                                 appendPQExpBuffer(query, " TRUNCATE");
13547                         findx++;
13548                 }
13549                 appendPQExpBuffer(query, " ON %s\n",
13550                                                   fmtId(tbinfo->dobj.name));
13551
13552                 if (tginfo->tgisconstraint)
13553                 {
13554                         if (OidIsValid(tginfo->tgconstrrelid))
13555                         {
13556                                 /* If we are using regclass, name is already quoted */
13557                                 if (fout->remoteVersion >= 70300)
13558                                         appendPQExpBuffer(query, "    FROM %s\n    ",
13559                                                                           tginfo->tgconstrrelname);
13560                                 else
13561                                         appendPQExpBuffer(query, "    FROM %s\n    ",
13562                                                                           fmtId(tginfo->tgconstrrelname));
13563                         }
13564                         if (!tginfo->tgdeferrable)
13565                                 appendPQExpBuffer(query, "NOT ");
13566                         appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
13567                         if (tginfo->tginitdeferred)
13568                                 appendPQExpBuffer(query, "DEFERRED\n");
13569                         else
13570                                 appendPQExpBuffer(query, "IMMEDIATE\n");
13571                 }
13572
13573                 if (TRIGGER_FOR_ROW(tginfo->tgtype))
13574                         appendPQExpBuffer(query, "    FOR EACH ROW\n    ");
13575                 else
13576                         appendPQExpBuffer(query, "    FOR EACH STATEMENT\n    ");
13577
13578                 /* In 7.3, result of regproc is already quoted */
13579                 if (fout->remoteVersion >= 70300)
13580                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13581                                                           tginfo->tgfname);
13582                 else
13583                         appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13584                                                           fmtId(tginfo->tgfname));
13585
13586                 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
13587                                                                                   &lentgargs);
13588                 p = tgargs;
13589                 for (findx = 0; findx < tginfo->tgnargs; findx++)
13590                 {
13591                         /* find the embedded null that terminates this trigger argument */
13592                         size_t          tlen = strlen(p);
13593
13594                         if (p + tlen >= tgargs + lentgargs)
13595                         {
13596                                 /* hm, not found before end of bytea value... */
13597                                 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
13598                                                   tginfo->tgargs,
13599                                                   tginfo->dobj.name,
13600                                                   tbinfo->dobj.name);
13601                                 exit_nicely(1);
13602                         }
13603
13604                         if (findx > 0)
13605                                 appendPQExpBuffer(query, ", ");
13606                         appendStringLiteralAH(query, p, fout);
13607                         p += tlen + 1;
13608                 }
13609                 free(tgargs);
13610                 appendPQExpBuffer(query, ");\n");
13611         }
13612
13613         if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
13614         {
13615                 appendPQExpBuffer(query, "\nALTER TABLE %s ",
13616                                                   fmtId(tbinfo->dobj.name));
13617                 switch (tginfo->tgenabled)
13618                 {
13619                         case 'D':
13620                         case 'f':
13621                                 appendPQExpBuffer(query, "DISABLE");
13622                                 break;
13623                         case 'A':
13624                                 appendPQExpBuffer(query, "ENABLE ALWAYS");
13625                                 break;
13626                         case 'R':
13627                                 appendPQExpBuffer(query, "ENABLE REPLICA");
13628                                 break;
13629                         default:
13630                                 appendPQExpBuffer(query, "ENABLE");
13631                                 break;
13632                 }
13633                 appendPQExpBuffer(query, " TRIGGER %s;\n",
13634                                                   fmtId(tginfo->dobj.name));
13635         }
13636
13637         appendPQExpBuffer(labelq, "TRIGGER %s ",
13638                                           fmtId(tginfo->dobj.name));
13639         appendPQExpBuffer(labelq, "ON %s",
13640                                           fmtId(tbinfo->dobj.name));
13641
13642         ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
13643                                  tginfo->dobj.name,
13644                                  tbinfo->dobj.namespace->dobj.name,
13645                                  NULL,
13646                                  tbinfo->rolname, false,
13647                                  "TRIGGER", SECTION_POST_DATA,
13648                                  query->data, delqry->data, NULL,
13649                                  tginfo->dobj.dependencies, tginfo->dobj.nDeps,
13650                                  NULL, NULL);
13651
13652         dumpComment(fout, labelq->data,
13653                                 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13654                                 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
13655
13656         destroyPQExpBuffer(query);
13657         destroyPQExpBuffer(delqry);
13658         destroyPQExpBuffer(labelq);
13659 }
13660
13661 /*
13662  * dumpRule
13663  *              Dump a rule
13664  */
13665 static void
13666 dumpRule(Archive *fout, RuleInfo *rinfo)
13667 {
13668         TableInfo  *tbinfo = rinfo->ruletable;
13669         PQExpBuffer query;
13670         PQExpBuffer cmd;
13671         PQExpBuffer delcmd;
13672         PQExpBuffer labelq;
13673         PGresult   *res;
13674
13675         /* Skip if not to be dumped */
13676         if (!rinfo->dobj.dump || dataOnly)
13677                 return;
13678
13679         /*
13680          * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
13681          * we do not want to dump it as a separate object.
13682          */
13683         if (!rinfo->separate)
13684                 return;
13685
13686         /*
13687          * Make sure we are in proper schema.
13688          */
13689         selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13690
13691         query = createPQExpBuffer();
13692         cmd = createPQExpBuffer();
13693         delcmd = createPQExpBuffer();
13694         labelq = createPQExpBuffer();
13695
13696         if (fout->remoteVersion >= 70300)
13697         {
13698                 appendPQExpBuffer(query,
13699                                                   "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
13700                                                   rinfo->dobj.catId.oid);
13701         }
13702         else
13703         {
13704                 /* Rule name was unique before 7.3 ... */
13705                 appendPQExpBuffer(query,
13706                                                   "SELECT pg_get_ruledef('%s') AS definition",
13707                                                   rinfo->dobj.name);
13708         }
13709
13710         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13711
13712         if (PQntuples(res) != 1)
13713         {
13714                 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
13715                                   rinfo->dobj.name, tbinfo->dobj.name);
13716                 exit_nicely(1);
13717         }
13718
13719         printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
13720
13721         /*
13722          * Add the command to alter the rules replication firing semantics if it
13723          * differs from the default.
13724          */
13725         if (rinfo->ev_enabled != 'O')
13726         {
13727                 appendPQExpBuffer(cmd, "ALTER TABLE %s.",
13728                                                   fmtId(tbinfo->dobj.namespace->dobj.name));
13729                 appendPQExpBuffer(cmd, "%s ",
13730                                                   fmtId(tbinfo->dobj.name));
13731                 switch (rinfo->ev_enabled)
13732                 {
13733                         case 'A':
13734                                 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
13735                                                                   fmtId(rinfo->dobj.name));
13736                                 break;
13737                         case 'R':
13738                                 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
13739                                                                   fmtId(rinfo->dobj.name));
13740                                 break;
13741                         case 'D':
13742                                 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
13743                                                                   fmtId(rinfo->dobj.name));
13744                                 break;
13745                 }
13746         }
13747
13748         /*
13749          * DROP must be fully qualified in case same name appears in pg_catalog
13750          */
13751         appendPQExpBuffer(delcmd, "DROP RULE %s ",
13752                                           fmtId(rinfo->dobj.name));
13753         appendPQExpBuffer(delcmd, "ON %s.",
13754                                           fmtId(tbinfo->dobj.namespace->dobj.name));
13755         appendPQExpBuffer(delcmd, "%s;\n",
13756                                           fmtId(tbinfo->dobj.name));
13757
13758         appendPQExpBuffer(labelq, "RULE %s",
13759                                           fmtId(rinfo->dobj.name));
13760         appendPQExpBuffer(labelq, " ON %s",
13761                                           fmtId(tbinfo->dobj.name));
13762
13763         ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
13764                                  rinfo->dobj.name,
13765                                  tbinfo->dobj.namespace->dobj.name,
13766                                  NULL,
13767                                  tbinfo->rolname, false,
13768                                  "RULE", SECTION_POST_DATA,
13769                                  cmd->data, delcmd->data, NULL,
13770                                  rinfo->dobj.dependencies, rinfo->dobj.nDeps,
13771                                  NULL, NULL);
13772
13773         /* Dump rule comments */
13774         dumpComment(fout, labelq->data,
13775                                 tbinfo->dobj.namespace->dobj.name,
13776                                 tbinfo->rolname,
13777                                 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
13778
13779         PQclear(res);
13780
13781         destroyPQExpBuffer(query);
13782         destroyPQExpBuffer(cmd);
13783         destroyPQExpBuffer(delcmd);
13784         destroyPQExpBuffer(labelq);
13785 }
13786
13787 /*
13788  * getExtensionMembership --- obtain extension membership data
13789  */
13790 void
13791 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
13792                                            int numExtensions)
13793 {
13794         PQExpBuffer query;
13795         PGresult   *res;
13796         int                     ntups,
13797                                 i;
13798         int                     i_classid,
13799                                 i_objid,
13800                                 i_refclassid,
13801                                 i_refobjid;
13802         DumpableObject *dobj,
13803                            *refdobj;
13804
13805         /* Nothing to do if no extensions */
13806         if (numExtensions == 0)
13807                 return;
13808
13809         /* Make sure we are in proper schema */
13810         selectSourceSchema(fout, "pg_catalog");
13811
13812         query = createPQExpBuffer();
13813
13814         /* refclassid constraint is redundant but may speed the search */
13815         appendPQExpBuffer(query, "SELECT "
13816                                           "classid, objid, refclassid, refobjid "
13817                                           "FROM pg_depend "
13818                                           "WHERE refclassid = 'pg_extension'::regclass "
13819                                           "AND deptype = 'e' "
13820                                           "ORDER BY 3,4");
13821
13822         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13823
13824         ntups = PQntuples(res);
13825
13826         i_classid = PQfnumber(res, "classid");
13827         i_objid = PQfnumber(res, "objid");
13828         i_refclassid = PQfnumber(res, "refclassid");
13829         i_refobjid = PQfnumber(res, "refobjid");
13830
13831         /*
13832          * Since we ordered the SELECT by referenced ID, we can expect that
13833          * multiple entries for the same extension will appear together; this
13834          * saves on searches.
13835          */
13836         refdobj = NULL;
13837
13838         for (i = 0; i < ntups; i++)
13839         {
13840                 CatalogId       objId;
13841                 CatalogId       refobjId;
13842
13843                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
13844                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
13845                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
13846                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
13847
13848                 if (refdobj == NULL ||
13849                         refdobj->catId.tableoid != refobjId.tableoid ||
13850                         refdobj->catId.oid != refobjId.oid)
13851                         refdobj = findObjectByCatalogId(refobjId);
13852
13853                 /*
13854                  * Failure to find objects mentioned in pg_depend is not unexpected,
13855                  * since for example we don't collect info about TOAST tables.
13856                  */
13857                 if (refdobj == NULL)
13858                 {
13859 #ifdef NOT_USED
13860                         fprintf(stderr, "no referenced object %u %u\n",
13861                                         refobjId.tableoid, refobjId.oid);
13862 #endif
13863                         continue;
13864                 }
13865
13866                 dobj = findObjectByCatalogId(objId);
13867
13868                 if (dobj == NULL)
13869                 {
13870 #ifdef NOT_USED
13871                         fprintf(stderr, "no referencing object %u %u\n",
13872                                         objId.tableoid, objId.oid);
13873 #endif
13874                         continue;
13875                 }
13876
13877                 /* Record dependency so that getDependencies needn't repeat this */
13878                 addObjectDependency(dobj, refdobj->dumpId);
13879
13880                 dobj->ext_member = true;
13881
13882                 /*
13883                  * Normally, mark the member object as not to be dumped.  But in
13884                  * binary upgrades, we still dump the members individually, since the
13885                  * idea is to exactly reproduce the database contents rather than
13886                  * replace the extension contents with something different.
13887                  */
13888                 if (!binary_upgrade)
13889                         dobj->dump = false;
13890                 else
13891                         dobj->dump = refdobj->dump;
13892         }
13893
13894         PQclear(res);
13895
13896         /*
13897          * Now identify extension configuration tables and create TableDataInfo
13898          * objects for them, ensuring their data will be dumped even though the
13899          * tables themselves won't be.
13900          *
13901          * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
13902          * user data in a configuration table is treated like schema data. This
13903          * seems appropriate since system data in a config table would get
13904          * reloaded by CREATE EXTENSION.
13905          */
13906         for (i = 0; i < numExtensions; i++)
13907         {
13908                 ExtensionInfo *curext = &(extinfo[i]);
13909                 char       *extconfig = curext->extconfig;
13910                 char       *extcondition = curext->extcondition;
13911                 char      **extconfigarray = NULL;
13912                 char      **extconditionarray = NULL;
13913                 int                     nconfigitems;
13914                 int                     nconditionitems;
13915
13916                 /* Tables of not-to-be-dumped extensions shouldn't be dumped */
13917                 if (!curext->dobj.dump)
13918                         continue;
13919
13920                 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
13921                   parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
13922                         nconfigitems == nconditionitems)
13923                 {
13924                         int                     j;
13925
13926                         for (j = 0; j < nconfigitems; j++)
13927                         {
13928                                 TableInfo  *configtbl;
13929
13930                                 configtbl = findTableByOid(atooid(extconfigarray[j]));
13931                                 if (configtbl == NULL)
13932                                         continue;
13933
13934                                 /*
13935                                  * Note: config tables are dumped without OIDs regardless
13936                                  * of the --oids setting.  This is because row filtering
13937                                  * conditions aren't compatible with dumping OIDs.
13938                                  */
13939                                 makeTableDataInfo(configtbl, false);
13940                                 if (configtbl->dataObj != NULL)
13941                                 {
13942                                         if (strlen(extconditionarray[j]) > 0)
13943                                                 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
13944                                 }
13945                         }
13946                 }
13947                 if (extconfigarray)
13948                         free(extconfigarray);
13949                 if (extconditionarray)
13950                         free(extconditionarray);
13951         }
13952
13953         destroyPQExpBuffer(query);
13954 }
13955
13956 /*
13957  * getDependencies --- obtain available dependency data
13958  */
13959 static void
13960 getDependencies(Archive *fout)
13961 {
13962         PQExpBuffer query;
13963         PGresult   *res;
13964         int                     ntups,
13965                                 i;
13966         int                     i_classid,
13967                                 i_objid,
13968                                 i_refclassid,
13969                                 i_refobjid,
13970                                 i_deptype;
13971         DumpableObject *dobj,
13972                            *refdobj;
13973
13974         /* No dependency info available before 7.3 */
13975         if (fout->remoteVersion < 70300)
13976                 return;
13977
13978         if (g_verbose)
13979                 write_msg(NULL, "reading dependency data\n");
13980
13981         /* Make sure we are in proper schema */
13982         selectSourceSchema(fout, "pg_catalog");
13983
13984         query = createPQExpBuffer();
13985
13986         /*
13987          * PIN dependencies aren't interesting, and EXTENSION dependencies were
13988          * already processed by getExtensionMembership.
13989          */
13990         appendPQExpBuffer(query, "SELECT "
13991                                           "classid, objid, refclassid, refobjid, deptype "
13992                                           "FROM pg_depend "
13993                                           "WHERE deptype != 'p' AND deptype != 'e' "
13994                                           "ORDER BY 1,2");
13995
13996         res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13997
13998         ntups = PQntuples(res);
13999
14000         i_classid = PQfnumber(res, "classid");
14001         i_objid = PQfnumber(res, "objid");
14002         i_refclassid = PQfnumber(res, "refclassid");
14003         i_refobjid = PQfnumber(res, "refobjid");
14004         i_deptype = PQfnumber(res, "deptype");
14005
14006         /*
14007          * Since we ordered the SELECT by referencing ID, we can expect that
14008          * multiple entries for the same object will appear together; this saves
14009          * on searches.
14010          */
14011         dobj = NULL;
14012
14013         for (i = 0; i < ntups; i++)
14014         {
14015                 CatalogId       objId;
14016                 CatalogId       refobjId;
14017                 char            deptype;
14018
14019                 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14020                 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14021                 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14022                 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14023                 deptype = *(PQgetvalue(res, i, i_deptype));
14024
14025                 if (dobj == NULL ||
14026                         dobj->catId.tableoid != objId.tableoid ||
14027                         dobj->catId.oid != objId.oid)
14028                         dobj = findObjectByCatalogId(objId);
14029
14030                 /*
14031                  * Failure to find objects mentioned in pg_depend is not unexpected,
14032                  * since for example we don't collect info about TOAST tables.
14033                  */
14034                 if (dobj == NULL)
14035                 {
14036 #ifdef NOT_USED
14037                         fprintf(stderr, "no referencing object %u %u\n",
14038                                         objId.tableoid, objId.oid);
14039 #endif
14040                         continue;
14041                 }
14042
14043                 refdobj = findObjectByCatalogId(refobjId);
14044
14045                 if (refdobj == NULL)
14046                 {
14047 #ifdef NOT_USED
14048                         fprintf(stderr, "no referenced object %u %u\n",
14049                                         refobjId.tableoid, refobjId.oid);
14050 #endif
14051                         continue;
14052                 }
14053
14054                 /*
14055                  * Ordinarily, table rowtypes have implicit dependencies on their
14056                  * tables.      However, for a composite type the implicit dependency goes
14057                  * the other way in pg_depend; which is the right thing for DROP but
14058                  * it doesn't produce the dependency ordering we need. So in that one
14059                  * case, we reverse the direction of the dependency.
14060                  */
14061                 if (deptype == 'i' &&
14062                         dobj->objType == DO_TABLE &&
14063                         refdobj->objType == DO_TYPE)
14064                         addObjectDependency(refdobj, dobj->dumpId);
14065                 else
14066                         /* normal case */
14067                         addObjectDependency(dobj, refdobj->dumpId);
14068         }
14069
14070         PQclear(res);
14071
14072         destroyPQExpBuffer(query);
14073 }
14074
14075
14076 /*
14077  * selectSourceSchema - make the specified schema the active search path
14078  * in the source database.
14079  *
14080  * NB: pg_catalog is explicitly searched after the specified schema;
14081  * so user names are only qualified if they are cross-schema references,
14082  * and system names are only qualified if they conflict with a user name
14083  * in the current schema.
14084  *
14085  * Whenever the selected schema is not pg_catalog, be careful to qualify
14086  * references to system catalogs and types in our emitted commands!
14087  */
14088 static void
14089 selectSourceSchema(Archive *fout, const char *schemaName)
14090 {
14091         static char *curSchemaName = NULL;
14092         PQExpBuffer query;
14093
14094         /* Not relevant if fetching from pre-7.3 DB */
14095         if (fout->remoteVersion < 70300)
14096                 return;
14097         /* Ignore null schema names */
14098         if (schemaName == NULL || *schemaName == '\0')
14099                 return;
14100         /* Optimize away repeated selection of same schema */
14101         if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14102                 return;
14103
14104         query = createPQExpBuffer();
14105         appendPQExpBuffer(query, "SET search_path = %s",
14106                                           fmtId(schemaName));
14107         if (strcmp(schemaName, "pg_catalog") != 0)
14108                 appendPQExpBuffer(query, ", pg_catalog");
14109
14110         ExecuteSqlStatement(fout, query->data);
14111
14112         destroyPQExpBuffer(query);
14113         if (curSchemaName)
14114                 free(curSchemaName);
14115         curSchemaName = pg_strdup(schemaName);
14116 }
14117
14118 /*
14119  * getFormattedTypeName - retrieve a nicely-formatted type name for the
14120  * given type name.
14121  *
14122  * NB: in 7.3 and up the result may depend on the currently-selected
14123  * schema; this is why we don't try to cache the names.
14124  */
14125 static char *
14126 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
14127 {
14128         char       *result;
14129         PQExpBuffer query;
14130         PGresult   *res;
14131
14132         if (oid == 0)
14133         {
14134                 if ((opts & zeroAsOpaque) != 0)
14135                         return pg_strdup(g_opaque_type);
14136                 else if ((opts & zeroAsAny) != 0)
14137                         return pg_strdup("'any'");
14138                 else if ((opts & zeroAsStar) != 0)
14139                         return pg_strdup("*");
14140                 else if ((opts & zeroAsNone) != 0)
14141                         return pg_strdup("NONE");
14142         }
14143
14144         query = createPQExpBuffer();
14145         if (fout->remoteVersion >= 70300)
14146         {
14147                 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14148                                                   oid);
14149         }
14150         else if (fout->remoteVersion >= 70100)
14151         {
14152                 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14153                                                   oid);
14154         }
14155         else
14156         {
14157                 appendPQExpBuffer(query, "SELECT typname "
14158                                                   "FROM pg_type "
14159                                                   "WHERE oid = '%u'::oid",
14160                                                   oid);
14161         }
14162
14163         res = ExecuteSqlQueryForSingleRow(fout, query->data);
14164
14165         if (fout->remoteVersion >= 70100)
14166         {
14167                 /* already quoted */
14168                 result = pg_strdup(PQgetvalue(res, 0, 0));
14169         }
14170         else
14171         {
14172                 /* may need to quote it */
14173                 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14174         }
14175
14176         PQclear(res);
14177         destroyPQExpBuffer(query);
14178
14179         return result;
14180 }
14181
14182 /*
14183  * myFormatType --- local implementation of format_type for use with 7.0.
14184  */
14185 static char *
14186 myFormatType(const char *typname, int32 typmod)
14187 {
14188         char       *result;
14189         bool            isarray = false;
14190         PQExpBuffer buf = createPQExpBuffer();
14191
14192         /* Handle array types */
14193         if (typname[0] == '_')
14194         {
14195                 isarray = true;
14196                 typname++;
14197         }
14198
14199         /* Show lengths on bpchar and varchar */
14200         if (strcmp(typname, "bpchar") == 0)
14201         {
14202                 int                     len = (typmod - VARHDRSZ);
14203
14204                 appendPQExpBuffer(buf, "character");
14205                 if (len > 1)
14206                         appendPQExpBuffer(buf, "(%d)",
14207                                                           typmod - VARHDRSZ);
14208         }
14209         else if (strcmp(typname, "varchar") == 0)
14210         {
14211                 appendPQExpBuffer(buf, "character varying");
14212                 if (typmod != -1)
14213                         appendPQExpBuffer(buf, "(%d)",
14214                                                           typmod - VARHDRSZ);
14215         }
14216         else if (strcmp(typname, "numeric") == 0)
14217         {
14218                 appendPQExpBuffer(buf, "numeric");
14219                 if (typmod != -1)
14220                 {
14221                         int32           tmp_typmod;
14222                         int                     precision;
14223                         int                     scale;
14224
14225                         tmp_typmod = typmod - VARHDRSZ;
14226                         precision = (tmp_typmod >> 16) & 0xffff;
14227                         scale = tmp_typmod & 0xffff;
14228                         appendPQExpBuffer(buf, "(%d,%d)",
14229                                                           precision, scale);
14230                 }
14231         }
14232
14233         /*
14234          * char is an internal single-byte data type; Let's make sure we force it
14235          * through with quotes. - thomas 1998-12-13
14236          */
14237         else if (strcmp(typname, "char") == 0)
14238                 appendPQExpBuffer(buf, "\"char\"");
14239         else
14240                 appendPQExpBuffer(buf, "%s", fmtId(typname));
14241
14242         /* Append array qualifier for array types */
14243         if (isarray)
14244                 appendPQExpBuffer(buf, "[]");
14245
14246         result = pg_strdup(buf->data);
14247         destroyPQExpBuffer(buf);
14248
14249         return result;
14250 }
14251
14252 /*
14253  * fmtQualifiedId - convert a qualified name to the proper format for
14254  * the source database.
14255  *
14256  * Like fmtId, use the result before calling again.
14257  */
14258 static const char *
14259 fmtQualifiedId(Archive *fout, const char *schema, const char *id)
14260 {
14261         static PQExpBuffer id_return = NULL;
14262
14263         if (id_return)                          /* first time through? */
14264                 resetPQExpBuffer(id_return);
14265         else
14266                 id_return = createPQExpBuffer();
14267
14268         /* Suppress schema name if fetching from pre-7.3 DB */
14269         if (fout->remoteVersion >= 70300 && schema && *schema)
14270         {
14271                 appendPQExpBuffer(id_return, "%s.",
14272                                                   fmtId(schema));
14273         }
14274         appendPQExpBuffer(id_return, "%s",
14275                                           fmtId(id));
14276
14277         return id_return->data;
14278 }
14279
14280 /*
14281  * Return a column list clause for the given relation.
14282  *
14283  * Special case: if there are no undropped columns in the relation, return
14284  * "", not an invalid "()" column list.
14285  */
14286 static const char *
14287 fmtCopyColumnList(const TableInfo *ti)
14288 {
14289         static PQExpBuffer q = NULL;
14290         int                     numatts = ti->numatts;
14291         char      **attnames = ti->attnames;
14292         bool       *attisdropped = ti->attisdropped;
14293         bool            needComma;
14294         int                     i;
14295
14296         if (q)                                          /* first time through? */
14297                 resetPQExpBuffer(q);
14298         else
14299                 q = createPQExpBuffer();
14300
14301         appendPQExpBuffer(q, "(");
14302         needComma = false;
14303         for (i = 0; i < numatts; i++)
14304         {
14305                 if (attisdropped[i])
14306                         continue;
14307                 if (needComma)
14308                         appendPQExpBuffer(q, ", ");
14309                 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
14310                 needComma = true;
14311         }
14312
14313         if (!needComma)
14314                 return "";                              /* no undropped columns */
14315
14316         appendPQExpBuffer(q, ")");
14317         return q->data;
14318 }
14319
14320 /*
14321  * Execute an SQL query and verify that we got exactly one row back.
14322  */
14323 static PGresult *
14324 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
14325 {
14326         PGresult   *res;
14327         int                     ntups;
14328
14329         res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
14330
14331         /* Expecting a single result only */
14332         ntups = PQntuples(res);
14333         if (ntups != 1)
14334                 exit_horribly(NULL,
14335                                           ngettext("query returned %d row instead of one: %s\n",
14336                                                            "query returned %d rows instead of one: %s\n",
14337                                                                  ntups),
14338                                           ntups, query);
14339
14340         return res;
14341 }